@element-hq/element-call-embedded 0.16.2 → 0.16.3

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-jvuzG61C.js","./matrix-sdk-crypto-wasm-DMhr4gdY.js","./polyfill-force-BlR75_rd.js","./index-DS4NG7gp.js","./polyfill-force-CkGZrTiH.js"])))=>i.map(i=>d[i]);
2
- try{let t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="8eb288e4-20f4-412b-86ef-86b06b45cf91",t._sentryDebugIdIdentifier="sentry-dbid-8eb288e4-20f4-412b-86ef-86b06b45cf91")}catch{}function Wge(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in t)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}{let t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"embedded-v0.16.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 n(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=n(i);fetch(i.href,s)}})();var Sat=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function cl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Eat(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var yk={exports:{}},f1={};/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DG_IYqWk.js","./matrix-sdk-crypto-wasm-DMhr4gdY.js","./polyfill-force-C-cqkbSt.js","./index-BHYrFcE-.js","./polyfill-force-C5_YvYDd.js"])))=>i.map(i=>d[i]);
2
+ try{let t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="a83948f9-fc71-47d1-aec2-9884b4c9319a",t._sentryDebugIdIdentifier="sentry-dbid-a83948f9-fc71-47d1-aec2-9884b4c9319a")}catch{}function Wge(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in t)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}{let t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"embedded-v0.16.3"}}(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 n(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=n(i);fetch(i.href,s)}})();var Sat=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function cl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Eat(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var yk={exports:{}},f1={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
5
5
  *
@@ -22,7 +22,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
22
22
  `)+`\r
23
23
  `},Ak}var x$;function G0e(){if(x$)return Na;x$=1;var t=V0e(),e=q0e(),n=zO();return Na.grammar=n,Na.write=e,Na.parse=t.parse,Na.parseParams=t.parseParams,Na.parseFmtpConfig=t.parseFmtpConfig,Na.parsePayloads=t.parsePayloads,Na.parseRemoteCandidates=t.parseRemoteCandidates,Na.parseImageAttributes=t.parseImageAttributes,Na.parseSimulcastStreamList=t.parseSimulcastStreamList,Na}var sA=G0e();function WO(t,e){if(typeof t.toBase64=="function")return t.toBase64(e);var n=btoa(t.reduce((r,i)=>r+String.fromCharCode(i),""));return e.omitPadding&&(n=n.replace(/={1,2}$/,"")),e.alphabet==="base64url"&&(n=n.replace(/\+/g,"-").replace(/\//g,"_")),n}function Cy(t){return WO(t,{alphabet:"base64",omitPadding:!1})}function $J(t){return WO(t,{alphabet:"base64",omitPadding:!0})}function Z3(t){return WO(t,{alphabet:"base64url",omitPadding:!0})}function K0e(t,e){return typeof Uint8Array.fromBase64=="function"?Uint8Array.fromBase64(t,e):Uint8Array.from(atob(t),n=>n.charCodeAt(0))}function Bh(t){return K0e(t.replace(/-/g,"+").replace(/_/g,"/"),{alphabet:"base64",lastChunkHandling:"loose"})}var z0e="abcdefghijklmnopqrstuvwxyz",W0e="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Y0e="0123456789";function BJ(t){var e=new Uint8Array(t);return globalThis.crypto.getRandomValues(e),Z3(e)}function To(t){return X0e(t,W0e+z0e+Y0e)}function X0e(t,e){if(e.length<2||e.length>256)throw new Error("Character set must be between 2 and 256 characters long");if(t<1||t>32768)throw new Error("Requested random string length must be between 1 and 32768");for(var n=256-256%e.length,r=new Uint8Array(Math.floor(t*1.3)),i=r.length,s=[];s.length<t;){i===r.length&&(globalThis.crypto.getRandomValues(r),i=0);var o=r[i++];o<n&&s.push(e[o%e.length])}return s.join("")}var _d="org.matrix.msc3077.sdp_stream_metadata",xn=function(t){return t.Usermedia="m.usermedia",t.Screenshare="m.screenshare",t}({}),Ty=null,oA=0,J0e=()=>(Ty===null&&(Ty=new AudioContext),oA++,Ty),Q0e=()=>{if(oA--,oA===0){var t;(t=Ty)===null||t===void 0||t.close(),Ty=null}},Z0e=200,aA=-60,e1e=8,Lc=function(t){return t.NewStream="new_stream",t.MuteStateChanged="mute_state_changed",t.LocalVolumeChanged="local_volume_changed",t.VolumeChanged="volume_changed",t.ConnectedChanged="connected_changed",t.Speaking="speaking",t.Disposed="disposed",t}({});class iu extends On{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",aA),L(this,"speaking",!1),L(this,"volumeLooperTimeout",void 0),L(this,"_disposed",!1),L(this,"_connected",!1),L(this,"onAddTrack",()=>{this.emit(Lc.NewStream,this.stream)}),L(this,"onCallState",n=>{n===at.Connected?this.connected=!0:n===at.Connecting&&(this.connected=!1)}),L(this,"volumeLooper",()=>{if(this.analyser&&this.measuringVolumeActivity){this.analyser.getFloatFrequencyData(this.frequencyBinCount);var n=-1/0;for(var r of this.frequencyBinCount)r>n&&(n=r);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(n),this.emit(Lc.VolumeChanged,n);var i=!1;for(var s of this.speakingVolumeSamples)if(s>this.speakingThreshold){i=!0;break}this.speaking!==i&&(this.speaking=i,this.emit(Lc.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,Z0e)}}),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(e1e).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(gt.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit(Lc.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,n){if(n!==e){var r=this.measuringVolumeActivity;e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=n,n.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?(this.initVolumeMeasuring(),r&&this.measureVolumeActivity(!0)):this.measureVolumeActivity(!1),this.emit(Lc.NewStream,this.stream)}}initVolumeMeasuring(){if(this.hasAudioTrack){this.audioContext||(this.audioContext=J0e()),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,n=this.client.getRoom(this.roomId);return(e=n?.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,n){e!==null&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),n!==null&&(this.videoMuted=n),this.emit(Lc.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(Lc.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){var e=this.client.getMediaHandler(),n=this.stream.clone();return M.log("CallFeed clone() cloning stream (originalStreamId=".concat(this.stream.id,", newStreamId").concat(n.id,")")),this.purpose===xn.Usermedia?e.userMediaStreams.push(n):e.screensharingStreams.push(n),new iu({client:this.client,roomId:this.roomId,userId:this.userId,deviceId:this.deviceId,stream:n,purpose:this.purpose,audioMuted:this.audioMuted,videoMuted:this.videoMuted})}dispose(){var e,n;clearTimeout(this.volumeLooperTimeout),(e=this.stream)===null||e===void 0||e.removeEventListener("addtrack",this.onAddTrack),(n=this.call)===null||n===void 0||n.removeListener(gt.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,Q0e()),this._disposed=!0,this.emit(Lc.Disposed)}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit(Lc.LocalVolumeChanged,e)}}var t1e=3e3,cA=function(t){return t.Incoming="Call.incoming",t}({});class n1e{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 n=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then(()=>this.evaluateEventBuffer(n)):this.eventBufferPromiseChain=this.evaluateEventBuffer(n)}),L(this,"onRoomTimeline",n=>{this.callEventBuffer.push(n)}),L(this,"onToDeviceEvent",n=>{var r=n.getContent();if(!r.call_id){this.callEventBuffer.push(n);return}if(this.nextSeqByCall.has(r.call_id)||this.nextSeqByCall.set(r.call_id,0),r.seq===void 0){this.callEventBuffer.push(n);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(d=>d.getContent().seq>r.seq);o===-1?s.push(n):s.splice(o,0,n)}else{var a=r.call_id;this.callEventBuffer.push(n),this.nextSeqByCall.set(a,r.seq+1);for(var c=this.toDeviceEventBuffers.get(a),l=c&&c.shift();l&&l.getContent().seq===this.nextSeqByCall.get(a);)this.callEventBuffer.push(l),this.nextSeqByCall.set(a,l.getContent().seq+1),l=c.shift()}}),this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(Le.Sync,this.onSync),this.client.on(ke.Timeline,this.onRoomTimeline),this.client.on(Le.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(Le.Sync,this.onSync),this.client.removeListener(ke.Timeline,this.onRoomTimeline),this.client.removeListener(Le.ToDeviceEvent,this.onToDeviceEvent)}evaluateEventBuffer(e){var n=this;return B(function*(){yield Promise.all(e.map(d=>n.client.decryptEventIfNeeded(d)));var r=e.filter(d=>{var h=d.getType();return h.startsWith("m.call.")||h.startsWith("org.matrix.call.")}),i=new Set;for(var s of r){var o=s.getType();(o===Z.CallAnswer||o===Z.CallHangup)&&i.add(s.getContent().call_id)}for(var a of r){var c=a.getType(),l=a.getContent().call_id;if(!(c===Z.CallInvite&&i.has(l)))try{yield n.handleCallEvent(a)}catch(d){M.error("CallEventHandler evaluateEventBuffer() caught exception handling call event",d)}}})()}handleCallEvent(e){var n=this;return B(function*(){var r;n.client.emit(Le.ReceivedVoipEvent,e);var i=e.getContent(),s=e.getRoomId()||((r=n.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(),c=e.getSender(),l=i.call_id?n.calls.get(i.call_id):void 0,d,h;if(o){if(h=n.client.groupCallEventHandler.getGroupCallById(o),!h){M.warn("CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=".concat(o,", type=").concat(a,")"));return}if(d=i.device_id,!d){M.warn("CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=".concat(c,")")),h.emit(kn.Error,new qJ(c));return}if(i.dest_session_id!==n.client.getSessionId()){M.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring");return}}var m=c===n.client.credentials.userId&&(d===void 0||d===n.client.getDeviceId());if(s){if(a===Z.CallInvite){var g,y,v;if(m||e.getLocalAge()>i.lifetime-t1e||l&&l.state===at.Ended||(l&&M.warn("CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=".concat(i.call_id,")")),i.invitee&&i.invitee!==n.client.getUserId()))return;var w=((g=n.client.getTurnServersExpiry())!==null&&g!==void 0?g:0)-Date.now();if(M.info("CallEventHandler handleCallEvent() current turn creds expire in "+w+" ms"),l=(y=fb(n.client,s,{forceTURN:n.client.forceTURN,opponentDeviceId:d,groupCallId:o,opponentSessionId:i.sender_session_id}))!==null&&y!==void 0?y:void 0,!l){M.log("CallEventHandler handleCallEvent() this client does not support WebRTC (callId=".concat(i.call_id,")"));return}l.callId=i.call_id;var S=(v=h)===null||v===void 0?void 0:v.getGroupCallStats();S&&l.initStats(S);try{yield l.initWithInvite(e)}catch(D){if(D instanceof Gl)if(D.code===Iy.UnknownDevice){var R;(R=h)===null||R===void 0||R.emit(kn.Error,D)}else M.error(D)}if(n.calls.set(l.callId,l),n.candidateEventsByCall.get(l.callId))for(var x of n.candidateEventsByCall.get(l.callId))l.onRemoteIceCandidatesReceived(x);var T;for(var I of n.calls.values()){var k,A=[at.WaitLocalMedia,at.CreateOffer,at.InviteSent].includes(I.state);if(l.roomId===I.roomId&&I.direction===xd.Outbound&&((k=l.getOpponentMember())===null||k===void 0?void 0:k.userId)===I.invitee&&A){T=I;break}}T?T.callId>l.callId?(M.log("CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=".concat(l.callId,", outgoingId=").concat(T.callId,")")),T.replacedBy(l)):(M.log("CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=".concat(l.callId,", outgoingId=").concat(T.callId,")")),l.hangup(ft.Replaced,!0)):n.client.emit(cA.Incoming,l);return}else if(a===Z.CallCandidates){if(m)return;l?l.onRemoteIceCandidatesReceived(e):(n.candidateEventsByCall.has(i.call_id)||n.candidateEventsByCall.set(i.call_id,[]),n.candidateEventsByCall.get(i.call_id).push(e));return}else if([Z.CallHangup,Z.CallReject].includes(a)){if(l)l.state!==at.Ended&&(a===Z.CallHangup?l.onHangupReceived(i):l.onRejectReceived(i),l.state===at.Ended&&n.calls.delete(i.call_id));else{var O;l=(O=fb(n.client,s,{opponentDeviceId:d,opponentSessionId:i.sender_session_id}))!==null&&O!==void 0?O:void 0,l&&(l.callId=i.call_id,l.initWithHangup(e),n.calls.set(i.call_id,l))}return}if(!l||!l.hasPeerConnection){M.info("CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=".concat(a,")"));return}if(e.getContent().party_id!==l.ourPartyId)switch(a){case Z.CallAnswer:m?l.state===at.Ringing&&l.onAnsweredElsewhere(i):l.onAnswerReceived(e);break;case Z.CallSelectAnswer:l.onSelectAnswerReceived(e);break;case Z.CallNegotiate:l.onNegotiateReceived(e);break;case Z.CallAssertedIdentity:case Z.CallAssertedIdentityPrefix:l.onAssertedIdentityReceived(e);break;case Z.CallSDPStreamMetadataChanged:case Z.CallSDPStreamMetadataChangedPrefix:l.onSDPStreamMetadataChangedReceived(e);break}}})()}}var lA=function(t){return t.Incoming="GroupCall.incoming",t.Outgoing="GroupCall.outgoing",t.Ended="GroupCall.ended",t.Participants="GroupCall.participants",t}({});class r1e{constructor(e){this.client=e,L(this,"groupCalls",new Map),L(this,"roomDeferreds",new Map),L(this,"onRoomsChanged",n=>{this.createGroupCallForRoom(n)}),L(this,"onRoomStateChanged",(n,r)=>{var i=n.getType();if(i===Z.GroupCallPrefix){var s=n.getStateKey(),o=n.getContent(),a=this.groupCalls.get(r.roomId);!a&&!o["m.terminated"]&&!n.isRedacted()?this.createGroupCallFromRoomStateEvent(n):a&&a.groupCallId===s?o["m.terminated"]||n.isRedacted()?a.terminate(!1):o["m.type"]!==a.type&&M.warn("GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=".concat(r.roomId,")")):a&&a.groupCallId!==s&&M.warn("GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=".concat(r.roomId,")"))}})}start(){var e=this;return B(function*(){e.client.getSyncState()!==Gt.Syncing&&(M.debug("GroupCallEventHandler start() waiting for client to start syncing"),yield new Promise(i=>{var s=()=>{if(e.client.getSyncState()===Gt.Syncing)return e.client.off(Le.Sync,s),i()};e.client.on(Le.Sync,s)}));var n=e.client.getRooms();for(var r of n)e.createGroupCallForRoom(r);e.client.on(Le.Room,e.onRoomsChanged),e.client.on(pt.Events,e.onRoomStateChanged)})()}stop(){this.client.removeListener(Le.Room,this.onRoomsChanged),this.client.removeListener(pt.Events,this.onRoomStateChanged)}getRoomDeferred(e){var n=this.roomDeferreds.get(e);if(n===void 0){var r;n={prom:new Promise(i=>{r=i})},n.resolve=r,this.roomDeferreds.set(e,n)}return n}waitUntilRoomReadyForGroupCalls(e){return this.getRoomDeferred(e).prom}getGroupCallById(e){return[...this.groupCalls.values()].find(n=>n.groupCallId===e)}createGroupCallForRoom(e){var n=e.currentState.getStateEvents(Z.GroupCallPrefix),r=n.sort((o,a)=>a.getTs()-o.getTs());for(var i of r){var s=i.getContent();if(!(s["m.terminated"]||i.isRedacted())){M.debug("GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=".concat(i.getStateKey(),", ts=").concat(i.getTs(),", roomId=").concat(e.roomId,", numOfPossibleCalls=").concat(n.length,")")),this.createGroupCallFromRoomStateEvent(i);break}}this.getRoomDeferred(e.roomId).resolve()}createGroupCallFromRoomStateEvent(e){var n=e.getRoomId(),r=e.getContent(),i=this.client.getRoom(n);if(!i){M.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=".concat(n,")"));return}var s=e.getStateKey(),o=r["m.type"];if(!Object.values(eT).includes(o)){M.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=".concat(o,", roomId=").concat(n,")"));return}var a=r["m.intent"];if(!Object.values(VJ).includes(a)){M.warn("Received invalid group call intent (type=".concat(o,", roomId=").concat(n,")"));return}var c=!!r["io.element.ptt"],l;if(r!=null&&r.dataChannelsEnabled&&r!==null&&r!==void 0&&r.dataChannelOptions){var{ordered:d,maxPacketLifeTime:h,maxRetransmits:m,protocol:g}=r.dataChannelOptions;l={ordered:d,maxPacketLifeTime:h,maxRetransmits:m,protocol:g}}var y=new YO(this.client,i,o,c,a,s,r?.dataChannelsEnabled||this.client.isVoipWithNoMediaAllowed,l,this.client.isVoipWithNoMediaAllowed,this.client.useLivekitForGroupCalls,r["io.element.livekit_service_url"]);return this.groupCalls.set(i.roomId,y),this.client.emit(lA.Incoming,y),y}}class i1e{constructor(){L(this,"bandwidth",{}),L(this,"bitrate",{}),L(this,"packetLoss",{}),L(this,"transport",[])}}class s1e{static buildBandwidthReport(e){var n=e.availableIncomingBitrate,r=e.availableOutgoingBitrate;return{download:n?Math.round(n/1e3):0,upload:r?Math.round(r/1e3):0}}}class o1e{static buildReport(e,n,r,i){var s=e?.get(n.localCandidateId),o=e?.get(n.remoteCandidateId);if(o&&s){var a=o.ip!==void 0?o.ip:o.address,c=o.port,l="".concat(a,":").concat(c),d=s.ip!==void 0?s.ip:s.address,h=s.port,m="".concat(d,":").concat(h),g=o.protocol;r.some(y=>y.ip===l&&y.type===g&&y.localIp===m)||r.push({ip:l,type:g,localIp:m,isFocus:i,localCandidateType:s.candidateType,remoteCandidateType:o.candidateType,networkType:s.networkType,rtt:n.currentRoundTripTime?n.currentRoundTripTime*1e3:NaN})}return r}}class a1e{constructor(){L(this,"ssrcToMid",{local:new Map,remote:new Map})}findMidBySsrc(e,n){var r;return this.ssrcToMid[n].forEach((i,s)=>{if(i.find(o=>o==e)){r=s;return}}),r}parse(e,n){var r=sA.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(c=>{c.attribute==="cname"&&a.push("".concat(c.id))}),i.set("".concat(s.mid),a)}}),this.ssrcToMid[n]=i}getSsrcToMidMap(e){return this.ssrcToMid[e]}}class c1e{constructor(e){this.pc=e}getLocalTracks(e){var n=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(n)}getTackById(e){return this.pc.getTransceivers().map(n=>{if(n?.sender.track!==null&&n.sender.track.id===e)return n.sender.track;if(n?.receiver.track!==null&&n.receiver.track.id===e)return n.receiver.track}).find(n=>n!==void 0)}getLocalTrackIdByMid(e){var n,r=this.pc.getTransceivers().find(i=>i.mid===e);return r==null||(n=r.sender)===null||n===void 0||(n=n.track)===null||n===void 0?void 0:n.id}getRemoteTrackIdByMid(e){var n,r=this.pc.getTransceivers().find(i=>i.mid===e);return r==null||(n=r.receiver)===null||n===void 0||(n=n.track)===null||n===void 0?void 0:n.id}getActiveSimulcastStreams(){return 3}getTransceiverByTrackId(e){return this.pc.getTransceivers().find(n=>n.receiver.track.id===e||n.sender.track!==null&&n.sender.track.id===e)}}class l1e{constructor(e,n,r){this.trackId=e,this.type=n,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,n){this.audioConcealment.concealedAudio=e,this.audioConcealment.totalAudioDuration=n}getAudioConcealment(){return this.audioConcealment}}class u1e{constructor(e,n){this.mediaSsrcHandler=e,this.mediaTrackHandler=n,L(this,"track2stats",new Map)}findTrack2Stats(e,n){var r;if(e.trackIdentifier)r=e.trackIdentifier;else if(e.mid)r=n==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid);else if(e.ssrc){var i=this.mediaSsrcHandler.findMidBySsrc(e.ssrc,n);if(!i)return;r=n==="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 l1e(r,n,a),this.track2stats.set(r,s)}else return}return s}}findLocalVideoTrackStats(e){var n=this.mediaTrackHandler.getLocalTracks("video");if(n.length!==0)return this.findTrack2Stats(e,"local")}getTrack2stats(){return this.track2stats}findTransceiverByTrackId(e){return this.mediaTrackHandler.getTransceiverByTrackId(e)}}class Ch{static getNonNegativeValue(e){var n=e;return typeof n!="number"&&(n=Number(n)),isNaN(n)?0:Math.max(0,n)}}class bo{static buildFramerateResolution(e,n){var r={height:n.frameHeight,width:n.frameWidth},i=n.framesPerSecond;r.height&&r.width&&e.setResolution(r),e.setFramerate(Math.round(i||0))}static calculateSimulcastFramerate(e,n,r,i){var s=e.getFramerate();if(!s){if(r){var o=n.timestamp-r.timestamp;if(o>0&&n.framesSent){var a=n.framesSent-r.framesSent;s=a/o*1e3}}if(!s)return}s=i?Math.round(s/i):0,e.setFramerate(s)}static buildCodec(e,n,r){var i=e?.get(r.codecId);if(i){var s=i.mimeType.split("/")[1];s&&n.setCodec(s)}}static buildBitrateReceived(e,n,r){e.setBitrate({download:bo.calculateBitrate(n.bytesReceived,r.bytesReceived,n.timestamp,r.timestamp),upload:0})}static buildBitrateSend(e,n,r){e.setBitrate({download:0,upload:this.calculateBitrate(n.bytesSent,r.bytesSent,n.timestamp,r.timestamp)})}static buildPacketsLost(e,n,r){var i=n.type==="outbound-rtp"?"packetsSent":"packetsReceived",s=n[i];(!s||s<0)&&(s=0);var o=Ch.getNonNegativeValue(r[i]),a=Math.max(0,s-o),c=Ch.getNonNegativeValue(n.packetsLost),l=Ch.getNonNegativeValue(r.packetsLost),d=Math.max(0,c-l);e.setLoss({packetsTotal:a+d,packetsLost:d,isDownloadStream:n.type!=="outbound-rtp"})}static calculateBitrate(e,n,r,i){var s=Ch.getNonNegativeValue(e),o=Ch.getNonNegativeValue(n),a=Math.max(0,s-o),c=r-i,l=0;return c>0&&(l=Math.round(a*8/c)),l}static setTrackStatsState(e,n){var r;if(n===void 0){e.alive=!1;return}var i=e.getType()==="remote"?n.receiver.track:n==null||(r=n.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 n={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"?n: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 c,l;a.concealedAudio+=(c=o.getAudioConcealment())===null||c===void 0?void 0:c.concealedAudio,a.totalAudio+=(l=o.getAudioConcealment())===null||l===void 0?void 0:l.totalAudioDuration}}),{audioTrackSummary:r,videoTrackSummary:n}}static buildJitter(e,n){if(n.type==="inbound-rtp"){var r=n?.jitter;if(r!==void 0){var i=Ch.getNonNegativeValue(r);e.setJitter(Math.round(i*1e3))}else e.setJitter(-1)}}static buildAudioConcealment(e,n){if(n.type==="inbound-rtp"){var r=1e3*n?.totalSamplesDuration/n?.totalSamplesReceived,i=r*n?.concealedSamples,s=1e3*n?.totalSamplesDuration;e.setAudioConcealment(i,s)}}}class Ry{static build(e){var n={},r={download:0,upload:0},i={download:0,upload:0},s=0,o=0,a={local:new Map,remote:new Map},c={local:new Map,remote:new Map},l={local:new Map,remote:new Map},d=new Map,h=new Map,m=0,g=0,y=0,v=0,w=0,S=0;for(var[R,x]of e){var T=x.getLoss(),I=T.isDownloadStream?"download":"upload";if(r[I]+=T.packetsTotal,i[I]+=T.packetsLost,s+=x.getBitrate().download,o+=x.getBitrate().upload,x.kind==="audio"){var k=x.getAudioConcealment();w+=k.concealedAudio,S+=k.totalAudioDuration,m+=x.getBitrate().download,g+=x.getBitrate().upload}else y+=x.getBitrate().download,v+=x.getBitrate().upload;a[x.getType()].set(R,x.getResolution()),c[x.getType()].set(R,x.getFramerate()),l[x.getType()].set(R,x.getCodec()),x.getType()==="remote"&&(d.set(R,x.getJitter()),x.kind==="audio"&&h.set(R,x.getAudioConcealment())),x.resetBitrate()}return n.bitrate={upload:o,download:s},n.bitrate.audio={upload:g,download:m},n.bitrate.video={upload:v,download:y},n.packetLoss={total:Ry.calculatePacketLoss(i.download+i.upload,r.download+r.upload),download:Ry.calculatePacketLoss(i.download,r.download),upload:Ry.calculatePacketLoss(i.upload,r.upload)},n.audioConcealment=h,n.totalAudioConcealment={concealedAudio:w,totalAudioDuration:S},n.framerate=c,n.resolution=a,n.codec=l,n.jitter=d,n}static calculatePacketLoss(e,n){return!n||n<=0||!e||e<=0?0:Math.round(e/n*100)}}class qd{static buildCallFeedReport(e,n,r){var i=r.getTransceivers(),s=[],o=[];return i.forEach(a=>{var c,l=(c=a.sender)!==null&&c!==void 0&&c.track?qd.buildTrackStats(a.sender.track,"sender"):null,d=qd.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:l,receiver:d})}),{callId:e,opponentMemberId:n,transceiver:s,callFeeds:o}}static buildTrackStats(e){var n,r,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"--",s=(n=e.getSettings())===null||n===void 0?void 0:n.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,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unknown";return n.forEach(i=>{var s=i.stream.getAudioTracks(),o=i.stream.getVideoTracks(),a=s.length>0?qd.buildTrackStats(i.stream.getAudioTracks()[0],i.purpose):null,c=o.length>0?qd.buildTrackStats(i.stream.getVideoTracks()[0],i.purpose):null,l={stream:i.stream.id,type:i.isLocal()?"local":"remote",audio:a,video:c,purpose:i.purpose,prefix:r,isVideoMuted:i.isVideoMuted(),isAudioMuted:i.isAudioMuted()};e.callFeeds.push(l)}),e}}function A$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function R2(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?A$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):A$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}class d1e{constructor(e,n,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;this.callId=e,this.opponentMemberId=n,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 i1e),L(this,"trackStats",void 0),r.addEventListener("signalingstatechange",this.onSignalStateChange.bind(this)),this.trackStats=new u1e(new a1e,new c1e(r))}processStats(e,n){var r=this;return B(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?.then=="function")return s.then(o=>{var a,c;r.currentStatsReport=typeof o?.result=="function"?o.result():o;try{r.processStatsReport(e,n)}catch(d){return r.handleError(d),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=((c=r.connectionStats.bitrate.video)===null||c===void 0?void 0:c.download)||0;var l=bo.buildTrackSummary(Array.from(r.trackStats.getTrack2stats().values()));return R2(R2({},i),{},{audioTrackSummary:l.audioTrackSummary,videoTrackSummary:l.videoTrackSummary})}).catch(o=>(r.handleError(o),i));r.isActive=!1}return Promise.resolve(i)})()}processStatsReport(e,n){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=s1e.buildBandwidthReport(s),this.connectionStats.transport=o1e.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&&bo.buildPacketsLost(a,s,o),s.type==="inbound-rtp"){bo.buildFramerateResolution(a,s),o&&bo.buildBitrateReceived(a,s,o);var c=this.trackStats.findTransceiverByTrackId(a.trackId);bo.setTrackStatsState(a,c),bo.buildJitter(a,s),bo.buildAudioConcealment(a,s)}else o&&(i.set(a.trackId,Ch.getNonNegativeValue(s.bytesSent)),bo.buildBitrateSend(a,s,o));bo.buildCodec(this.currentStatsReport,a,s)}else if(s.type==="track"&&s.kind==="video"&&!s.remoteSource){var l=this.trackStats.findLocalVideoTrackStats(s);if(!l)return;bo.buildFramerateResolution(l,s),bo.calculateSimulcastFramerate(l,s,o,this.trackStats.mediaTrackHandler.getActiveSimulcastStreams())}}),this.emitter.emitByteSendReport(i),this.emitter.emitCallFeedReport(qd.buildCallFeedReport(this.callId,this.opponentMemberId,this.pc)),this.processAndEmitConnectionStatsReport()}setActive(e){this.isActive=e}getActive(){return this.isActive}handleError(e){this.isActive=!1,M.warn("CallStatsReportGatherer ".concat(this.callId," processStatsReport fails and set to inactive ").concat(e))}processAndEmitConnectionStatsReport(){var e=Ry.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(R2(R2({},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 pu=function(t){return t.CONNECTION_STATS="StatsReport.connection_stats",t.CALL_FEED_REPORT="StatsReport.call_feed_report",t.BYTE_SENT_STATS="StatsReport.byte_sent_stats",t.SUMMARY_STATS="StatsReport.summary_stats",t}({});class f1e extends On{emitByteSendReport(e){this.emit(pu.BYTE_SENT_STATS,e)}emitConnectionStatsReport(e){this.emit(pu.CONNECTION_STATS,e)}emitCallFeedReport(e){this.emit(pu.CALL_FEED_REPORT,e)}emitSummaryStatsReport(e){this.emit(pu.SUMMARY_STATS,e)}}class HJ{constructor(e){this.emitter=e}build(e){var n=e.filter(d=>!d.isFirstCollection),r=n.length,i=e.length;if(r!==0){var s={receivedAudio:0,receivedVideo:0,receivedMedia:0,concealedAudio:0,totalAudio:0},o=0,a=0;n.forEach(d=>{this.countTrackListReceivedMedia(s,d),this.countConcealedAudio(s,d),o=this.buildMaxJitter(o,d),a=this.buildMaxPacketLoss(a,d)});var c=5,l={percentageReceivedMedia:Number((s.receivedMedia/r).toFixed(c)),percentageReceivedVideoMedia:Number((s.receivedVideo/r).toFixed(c)),percentageReceivedAudioMedia:Number((s.receivedAudio/r).toFixed(c)),maxJitter:o,maxPacketLoss:a,percentageConcealedAudio:Number(s.totalAudio>0?(s.concealedAudio/s.totalAudio).toFixed(c):0),peerConnections:i};this.emitter.emitSummaryStatsReport(l)}}static extendSummaryReport(e,n){var r=[],i=[];for(var s of n){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,n){var r=!1,i=!1;(n.receivedAudioMedia>0||n.audioTrackSummary.count===0)&&(e.receivedAudio++,r=!0),(n.receivedVideoMedia>0||n.videoTrackSummary.count===0||n.videoTrackSummary.muted>0&&n.videoTrackSummary.muted===n.videoTrackSummary.count)&&(e.receivedVideo++,i=!0),i&&r&&e.receivedMedia++}buildMaxJitter(e,n){return e<n.videoTrackSummary.maxJitter&&(e=n.videoTrackSummary.maxJitter),e<n.audioTrackSummary.maxJitter&&(e=n.audioTrackSummary.maxJitter),e}buildMaxPacketLoss(e,n){return e<n.videoTrackSummary.maxPacketLoss&&(e=n.videoTrackSummary.maxPacketLoss),e<n.audioTrackSummary.maxPacketLoss&&(e=n.audioTrackSummary.maxPacketLoss),e}countConcealedAudio(e,n){e.concealedAudio+=n.audioTrackSummary.concealedAudio,e.totalAudio+=n.audioTrackSummary.totalAudio}}class h1e{constructor(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1e4;this.groupCallId=e,this.userId=n,this.interval=r,L(this,"timer",void 0),L(this,"gatherers",new Map),L(this,"reports",new f1e),L(this,"summaryStatsReportGatherer",new HJ(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,n,r){return this.hasStatsReportGatherer(e)?!1:(this.gatherers.set(e,new d1e(e,n,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,n){var r;(r=this.getStatsReportGatherer(e))===null||r===void 0||r.setOpponentMemberId(n)}processStats(){var e=[];this.gatherers.forEach(n=>{e.push(n.processStats(this.groupCallId,this.userId))}),Promise.all(e).then(n=>this.summaryStatsReportGatherer.build(n)).catch(n=>{M.error("Could not build summary stats report",n)})}setInterval(e){this.interval=e}}function P$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function I2(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?P$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):P$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var VJ=function(t){return t.Ring="m.ring",t.Prompt="m.prompt",t.Room="m.room",t}({}),eT=function(t){return t.Video="m.video",t.Voice="m.voice",t}({}),p1e=function(t){return t.CallEnded="call_ended",t}({}),kn=function(t){return t.GroupCallStateChanged="group_call_state_changed",t.ActiveSpeakerChanged="active_speaker_changed",t.CallsChanged="calls_changed",t.UserMediaFeedsChanged="user_media_feeds_changed",t.ScreenshareFeedsChanged="screenshare_feeds_changed",t.LocalScreenshareStateChanged="local_screenshare_state_changed",t.LocalMuteStateChanged="local_mute_state_changed",t.ParticipantsChanged="participants_changed",t.Error="group_call_error",t}({}),uy=function(t){return t.ConnectionStats="GroupCall.connection_stats",t.ByteSentStats="GroupCall.byte_sent_stats",t.SummaryStats="GroupCall.summary_stats",t.CallFeedStats="GroupCall.call_feed_stats",t}({}),Iy=function(t){return t.NoUserMedia="no_user_media",t.UnknownDevice="unknown_device",t.PlaceCallFailed="place_call_failed",t}({});class uA extends Error{constructor(e,n,r){r?(super(n+": "+r),L(this,"code",void 0)):(super(n),L(this,"code",void 0)),this.code=e}}class qJ extends uA{constructor(e){super(Iy.UnknownDevice,"No device found for "+e),this.userId=e}}var sr=function(t){return t.LocalCallFeedUninitialized="local_call_feed_uninitialized",t.InitializingLocalCallFeed="initializing_local_call_feed",t.LocalCallFeedInitialized="local_call_feed_initialized",t.Entered="entered",t.Ended="ended",t}({}),L$=1e3*60*60;function k2(t){var e;return((e=t.getOpponentMember())===null||e===void 0?void 0:e.userId)||t.invitee||null}class YO extends On{constructor(e,n,r,i,s,o,a,c,l){var d,h,m=arguments.length>9&&arguments[9]!==void 0?arguments[9]:!1,g=arguments.length>10?arguments[10]:void 0;super(),this.client=e,this.room=n,this.type=r,this.isPtt=i,this.intent=s,this.dataChannelsEnabled=a,this.dataChannelOptions=c,this.useLivekit=m,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",y=>{this.emit(uy.ConnectionStats,{report:y})}),L(this,"onByteSentStats",y=>{this.emit(uy.ByteSentStats,{report:y})}),L(this,"onSummaryStats",y=>{HJ.extendSummaryReport(y,this.participants),this.emit(uy.SummaryStats,{report:y})}),L(this,"onCallFeedReport",y=>{this.localCallFeed&&(y=qd.expandCallFeedReport(y,[this.localCallFeed],"from-local-feed"));var v=[];this.forEachCall(w=>{w.callId===y.callId&&w.getFeeds().forEach(S=>v.push(S))}),y=qd.expandCallFeedReport(y,v,"from-call-feed"),this.emit(uy.CallFeedStats,{report:y})}),L(this,"_state",sr.LocalCallFeedUninitialized),L(this,"_participants",new Map),L(this,"_creationTs",null),L(this,"_enteredViaAnotherSession",!1),L(this,"onIncomingCall",y=>{var v,w;if(y.roomId===this.room.roomId){if(y.state!==at.Ringing){M.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call no longer in ringing state - ignoring"));return}if(!y.groupCallId||y.groupCallId!==this.groupCallId){M.log("GroupCall ".concat(this.groupCallId," onIncomingCall() ignored because it doesn't match the current group call")),y.reject();return}var S=(v=y.getOpponentMember())===null||v===void 0?void 0:v.userId;if(S===void 0){M.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call with no member - ignoring"));return}if(this.useLivekit){M.info("Received incoming call whilst in signaling-only mode! Ignoring.");return}var R=(w=this.calls.get(S))!==null&&w!==void 0?w:new Map,x=R.get(y.getOpponentDeviceId());if(x?.callId!==y.callId){M.log("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call (userId=").concat(S,", callId=").concat(y.callId,")")),x&&x.hangup(ft.Replaced,!1),R.set(y.getOpponentDeviceId(),y),this.calls.set(S,R),this.initCall(y);var T=this.getLocalFeeds().map(k=>k.clone());if(!this.callExpected(y))for(var I of T)Nr(I.stream.getAudioTracks(),!1),Nr(I.stream.getVideoTracks(),!1);y.answerWithCallFeeds(T),this.emit(kn.CallsChanged,this.calls)}}}),L(this,"onRetryCallLoop",()=>{var y=!1;for(var[{userId:v},w]of this.participants){var S=this.calls.get(v),R=this.retryCallCounts.get(v);for(var[x,T]of w){var I,k,A=S?.get(x),O=(I=(k=R)===null||k===void 0?void 0:k.get(x))!==null&&I!==void 0?I:0;A?.getOpponentSessionId()!==T.sessionId&&this.wantsOutgoingCall(v,x)&&O<3&&(R===void 0&&(R=new Map,this.retryCallCounts.set(v,R)),R.set(x,O+1),y=!0)}}y&&this.placeOutgoingCalls()}),L(this,"onCallFeedsChanged",y=>{var v=k2(y),w=y.getOpponentDeviceId();if(!v)throw new Error("Cannot change call feeds without user id");var S=this.getUserMediaFeed(v,w),R=y.remoteUsermediaFeed,x=R!==S,T=this.calls.get(v),I=T?.get(w);if(I?.callId===y.callId){x&&(!S&&R?this.addUserMediaFeed(R):S&&R?this.replaceUserMediaFeed(S,R):S&&!R&&this.removeUserMediaFeed(S));var k=this.getScreenshareFeed(v,w),A=y.remoteScreensharingFeed,O=A!==k;O&&(!k&&A?this.addScreenshareFeed(A):k&&A?this.replaceScreenshareFeed(k,A):k&&!A&&this.removeScreenshareFeed(k))}}),L(this,"onCallStateChanged",(y,v,w)=>{var S;if(v!==at.Ended){var R=this.localCallFeed.isAudioMuted();y.localUsermediaStream&&y.isMicrophoneMuted()!==R&&y.setMicrophoneMuted(R);var x=this.localCallFeed.isVideoMuted();y.localUsermediaStream&&y.isLocalVideoMuted()!==x&&y.setLocalVideoMuted(x);var T=(S=y.getOpponentMember())===null||S===void 0?void 0:S.userId;if(v===at.Connected&&T){var I=this.retryCallCounts.get(T);I?.delete(y.getOpponentDeviceId()),I?.size===0&&this.retryCallCounts.delete(T)}}}),L(this,"onCallHangup",y=>{var v,w;if(y.hangupReason!==ft.Replaced){var S=(v=(w=y.getOpponentMember())===null||w===void 0?void 0:w.userId)!==null&&v!==void 0?v:this.room.getMember(y.invitee).userId,R=this.calls.get(S);R?.get(y.getOpponentDeviceId())===y&&(this.disposeCall(y,y.hangupReason),R.delete(y.getOpponentDeviceId()),R.size===0&&this.calls.delete(S),this.emit(kn.CallsChanged,this.calls))}}),L(this,"onCallReplaced",(y,v)=>{var w=y.getOpponentMember().userId,S=this.calls.get(w);S===void 0&&(S=new Map,this.calls.set(w,S)),y.hangup(ft.Replaced,!1),this.initCall(v),S.set(y.getOpponentDeviceId(),v),this.emit(kn.CallsChanged,this.calls)}),L(this,"onActiveSpeakerLoop",()=>{var y=void 0,v=void 0;for(var w of this.userMediaFeeds)if(!(w.isLocal()&&this.userMediaFeeds.length>1)){var S=w.speakingVolumeSamples.reduce((x,T)=>x+Math.max(T,aA)),R=S/w.speakingVolumeSamples.length;(!y||R>y)&&(y=R,v=w)}v&&this.activeSpeaker!==v&&y&&y>aA&&(this.activeSpeaker=v,this.emit(kn.ActiveSpeakerChanged,this.activeSpeaker))}),L(this,"onRoomState",()=>this.updateParticipants()),L(this,"onParticipantsChanged",()=>{this.forEachCall(y=>{var v=this.callExpected(y);for(var w of y.getLocalFeeds())Nr(w.stream.getAudioTracks(),!w.isAudioMuted()&&v),Nr(w.stream.getVideoTracks(),!w.isVideoMuted()&&v)}),this.state===sr.Entered&&!this.useLivekit&&this.placeOutgoingCalls()}),L(this,"onStateChanged",(y,v)=>{(y===sr.Entered||v===sr.Entered||y===sr.Ended)&&(this.updateParticipants(),this.updateMemberState().catch(w=>M.error("GroupCall ".concat(this.groupCallId,' onStateChanged() failed to update member state devices"'),w)))}),L(this,"onLocalFeedsChanged",()=>{this.state===sr.Entered&&this.updateMemberState().catch(y=>M.error("GroupCall ".concat(this.groupCallId," onLocalFeedsChanged() failed to update member state feeds"),y))}),this.reEmitter=new uJ(this),this.groupCallId=o??Th(),this._livekitServiceURL=g,this.creationTs=(d=(h=n.currentState.getStateEvents(Z.GroupCallPrefix,this.groupCallId))===null||h===void 0?void 0:h.getTs())!==null&&d!==void 0?d:null,this.updateParticipants(),n.on(pt.Update,this.onRoomState),this.on(kn.ParticipantsChanged,this.onParticipantsChanged),this.on(kn.GroupCallStateChanged,this.onStateChanged),this.on(kn.LocalScreenshareStateChanged,this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!l}create(){var e=this;return B(function*(){return e.creationTs=Date.now(),e.client.groupCallEventHandler.groupCalls.set(e.room.roomId,e),e.client.emit(lA.Outgoing,e),yield e.sendCallStateEvent(),e})()}sendCallStateEvent(){var e=this;return B(function*(){var n={"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&&(n["io.element.livekit_service_url"]=e.livekitServiceURL),yield e.client.sendStateEvent(e.room.roomId,Z.GroupCallPrefix,n,e.groupCallId)})()}get livekitServiceURL(){return this._livekitServiceURL}updateLivekitServiceURL(e){return this._livekitServiceURL=e,this.sendCallStateEvent()}get state(){return this._state}set state(e){var n=this._state;e!==n&&(this._state=e,this.emit(kn.GroupCallStateChanged,e,n))}get participants(){return this._participants}set participants(e){var n=this._participants,r=(s,o)=>s.sessionId===o.sessionId&&s.screensharing===o.screensharing,i=(s,o)=>MF(s,o,r);MF(e,n,i)||(this._participants=e,this.emit(kn.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 n of this.calls.values())for(var r of n.values())e(r)}getLocalFeeds(){var e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e,n;return(e=(n=this.participants.get(this.room.getMember(this.client.getUserId())))===null||n===void 0?void 0:n.has(this.client.getDeviceId()))!==null&&e!==void 0?e:!1}callExpected(e){var n,r=k2(e),i=r===null?null:this.room.getMember(r),s=e.getOpponentDeviceId();return i!==null&&s!==void 0&&((n=this.participants.get(i))===null||n===void 0?void 0:n.get(s))!==void 0}initLocalCallFeed(){var e=this;return B(function*(){if(e.useLivekit){M.info("Livekit group call: not starting local call feed.");return}if(e.state!==sr.LocalCallFeedUninitialized)throw new Error('Cannot initialize local call feed in the "'.concat(e.state,'" state.'));if(e.state=sr.InitializingLocalCallFeed,e.initCallFeedPromise)return e.initCallFeedPromise;try{e.initCallFeedPromise=e.initLocalCallFeedInternal(),yield e.initCallFeedPromise}finally{e.initCallFeedPromise=void 0}})()}initLocalCallFeedInternal(){var e=this;return B(function*(){M.log("GroupCall ".concat(e.groupCallId," initLocalCallFeedInternal() running"));var n;try{n=yield e.client.getMediaHandler().getUserMediaStream(!0,e.type===eT.Video)}catch(i){if(e.allowCallWithoutVideoAndAudio)n=new MediaStream;else throw e.state=sr.LocalCallFeedUninitialized,i}if(e._state!==sr.InitializingLocalCallFeed)throw e.client.getMediaHandler().stopUserMediaStream(n),new Error("Group call disposed while gathering media stream");var r=new iu({client:e.client,roomId:e.room.roomId,userId:e.client.getUserId(),deviceId:e.client.getDeviceId(),stream:n,purpose:xn.Usermedia,audioMuted:e.initWithAudioMuted||n.getAudioTracks().length===0||e.isPtt,videoMuted:e.initWithVideoMuted||n.getVideoTracks().length===0});Nr(n.getAudioTracks(),!r.isAudioMuted()),Nr(n.getVideoTracks(),!r.isVideoMuted()),e.localCallFeed=r,e.addUserMediaFeed(r),e.state=sr.LocalCallFeedInitialized})()}updateLocalUsermediaStream(e){var n=this;return B(function*(){if(n.localCallFeed){var r=n.localCallFeed.stream;n.localCallFeed.setNewStream(e);var i=n.localCallFeed.isAudioMuted(),s=n.localCallFeed.isVideoMuted();M.log("GroupCall ".concat(n.groupCallId," updateLocalUsermediaStream() (oldStreamId=").concat(r.id,", newStreamId=").concat(e.id,", micShouldBeMuted=").concat(i,", vidShouldBeMuted=").concat(s,")")),Nr(e.getAudioTracks(),!i),Nr(e.getVideoTracks(),!s),n.client.getMediaHandler().stopUserMediaStream(r)}})()}enter(){var e=this;return B(function*(){if(e.state===sr.LocalCallFeedUninitialized)yield e.initLocalCallFeed();else if(e.state!==sr.LocalCallFeedInitialized)throw new Error('Cannot enter call in the "'.concat(e.state,'" state'));M.log("GroupCall ".concat(e.groupCallId," enter() running")),e.state=sr.Entered,e.client.on(cA.Incoming,e.onIncomingCall);for(var n of e.client.callEventHandler.calls.values())e.onIncomingCall(n);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===sr.Entered&&(this.forEachCall(n=>n.hangup(ft.UserHangup,!1)),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(cA.Incoming,this.onIncomingCall),(e=this.stats)===null||e===void 0||e.stop())}leave(){this.dispose(),this.state=sr.LocalCallFeedUninitialized}terminate(){var e=arguments,n=this;return B(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:!0;if(n.dispose(),n.room.off(pt.Update,n.onRoomState),n.client.groupCallEventHandler.groupCalls.delete(n.room.roomId),n.client.emit(lA.Ended,n),n.state=sr.Ended,r){var i=n.room.currentState.getStateEvents(Z.GroupCallPrefix,n.groupCallId);yield n.client.sendStateEvent(n.room.roomId,Z.GroupCallPrefix,I2(I2({},i.getContent()),{},{"m.terminated":p1e.CallEnded}),n.groupCallId)}})()}isLocalVideoMuted(){return this.localCallFeed?this.localCallFeed.isVideoMuted():!0}isMicrophoneMuted(){return this.localCallFeed?this.localCallFeed.isAudioMuted():!0}setMicrophoneMuted(e){var n=this;return B(function*(){if(!e&&!(yield n.client.getMediaHandler().hasAudioDevice()))return!1;var r=!e&&n.isPtt;n.isPtt&&(!e&&n.isMicrophoneMuted()?n.transmitTimer=setTimeout(()=>{n.setMicrophoneMuted(!0)},n.pttMaxTransmitTime):e&&!n.isMicrophoneMuted()&&(n.transmitTimer!==null&&clearTimeout(n.transmitTimer),n.transmitTimer=null)),n.forEachCall(o=>{var a;return(a=o.localUsermediaFeed)===null||a===void 0?void 0:a.setAudioVideoMuted(e,null)});var i=function(){var o=B(function*(){var a=[];n.forEachCall(c=>a.push(c.sendMetadataUpdate())),yield Promise.all(a).catch(c=>M.info("GroupCall ".concat(n.groupCallId," setMicrophoneMuted() failed to send some metadata updates"),c))});return function(){return o.apply(this,arguments)}}();if(r&&(yield i()),n.localCallFeed){M.log("GroupCall ".concat(n.groupCallId," setMicrophoneMuted() (streamId=").concat(n.localCallFeed.stream.id,", muted=").concat(e,")"));var s=yield n.checkAudioPermissionIfNecessary(e);if(!s)return!1;n.localCallFeed.setAudioVideoMuted(e,null),Nr(n.localCallFeed.stream.getAudioTracks(),!e)}else M.log("GroupCall ".concat(n.groupCallId," setMicrophoneMuted() no stream muted (muted=").concat(e,")")),n.initWithAudioMuted=e;return n.forEachCall(o=>Nr(o.localUsermediaFeed.stream.getAudioTracks(),!e&&n.callExpected(o))),n.emit(kn.LocalMuteStateChanged,e,n.isLocalVideoMuted()),r||(yield i()),!0})()}checkAudioPermissionIfNecessary(e){var n=this;return B(function*(){try{if(!e&&n.localCallFeed&&!n.localCallFeed.hasAudioTrack){var r=yield n.client.getMediaHandler().getUserMediaStream(!0,!n.localCallFeed.isVideoMuted());if(r?.getTracks().length===0)return M.log("GroupCall ".concat(n.groupCallId," setMicrophoneMuted() no device to receive local stream, muted=").concat(e)),!1}}catch{return M.log("GroupCall ".concat(n.groupCallId," setMicrophoneMuted() no device or permission to receive local stream, muted=").concat(e)),!1}return!0})()}setLocalVideoMuted(e){var n=this;return B(function*(){if(!e&&!(yield n.client.getMediaHandler().hasVideoDevice()))return!1;if(n.localCallFeed){M.log("GroupCall ".concat(n.groupCallId," setLocalVideoMuted() (stream=").concat(n.localCallFeed.stream.id,", muted=").concat(e,")"));try{var r=yield n.client.getMediaHandler().getUserMediaStream(!0,!e);yield n.updateLocalUsermediaStream(r),n.localCallFeed.setAudioVideoMuted(null,e),Nr(n.localCallFeed.stream.getVideoTracks(),!e)}catch{return M.log("GroupCall ".concat(n.groupCallId," setLocalVideoMuted() no device or permission to receive local stream, muted=").concat(e)),!1}}else M.log("GroupCall ".concat(n.groupCallId," setLocalVideoMuted() no stream muted (muted=").concat(e,")")),n.initWithVideoMuted=e;var i=[];return n.forEachCall(s=>i.push(s.setLocalVideoMuted(e))),yield Promise.all(i),n.forEachCall(s=>Nr(s.localUsermediaFeed.stream.getVideoTracks(),!e&&n.callExpected(s))),n.emit(kn.LocalMuteStateChanged,n.isMicrophoneMuted(),e),!0})()}setScreensharingEnabled(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:{};if(e===r.isScreensharing())return e;if(e)try{M.log("GroupCall ".concat(r.groupCallId," setScreensharingEnabled() is asking for screensharing permissions"));var s=yield r.client.getMediaHandler().getScreensharingStream(i),o=function*(l){var d=()=>{r.setScreensharingEnabled(!1),l.removeEventListener("ended",d)};l.addEventListener("ended",d)};for(var a of s.getTracks())yield*o(a);return M.log("GroupCall ".concat(r.groupCallId," setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls")),r.localDesktopCapturerSourceId=i.desktopCapturerSourceId,r.localScreenshareFeed=new iu({client:r.client,roomId:r.room.roomId,userId:r.client.getUserId(),deviceId:r.client.getDeviceId(),stream:s,purpose:xn.Screenshare,audioMuted:!1,videoMuted:!1}),r.addScreenshareFeed(r.localScreenshareFeed),r.emit(kn.LocalScreenshareStateChanged,!0,r.localScreenshareFeed,r.localDesktopCapturerSourceId),r.forEachCall(c=>c.pushLocalFeed(r.localScreenshareFeed.clone())),!0}catch(c){if(i.throwOnFail)throw c;return M.error("GroupCall ".concat(r.groupCallId," setScreensharingEnabled() enabling screensharing error"),c),r.emit(kn.Error,new uA(Iy.NoUserMedia,"Failed to get screen-sharing stream: ",c)),!1}else return r.forEachCall(c=>{c.localScreensharingFeed&&c.removeLocalFeed(c.localScreensharingFeed)}),r.client.getMediaHandler().stopScreensharingStream(r.localScreenshareFeed.stream),r.removeScreenshareFeed(r.localScreenshareFeed),r.localScreenshareFeed=void 0,r.localDesktopCapturerSourceId=void 0,r.emit(kn.LocalScreenshareStateChanged,!1,void 0,void 0),!1})()}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,n){var r=this.client.getUserId(),i=this.client.getDeviceId();return e>=r&&(e!==r||n>i)}placeOutgoingCalls(){var e=this,n=!1,r=function(a){var c,l=(c=e.calls.get(a))!==null&&c!==void 0?c:new Map,d=function(y){var v=l.get(y);if(v?.getOpponentSessionId()!==m.sessionId&&e.wantsOutgoingCall(a,y)){n=!0,v!==void 0&&(M.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() replacing call (userId=").concat(a,", deviceId=").concat(y,", callId=").concat(v.callId,")")),v.hangup(ft.NewSession,!1));var w=fb(e.client,e.room.roomId,{invitee:a,opponentDeviceId:y,opponentSessionId:m.sessionId,groupCallId:e.groupCallId});w===null?(M.error("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to create call (userId=").concat(a,", device=").concat(y,")")),l.delete(y)):(e.initCall(w),l.set(y,w),M.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() placing call (userId=").concat(a,", deviceId=").concat(y,", sessionId=").concat(m.sessionId,")")),w.placeCallWithCallFeeds(e.getLocalFeeds().map(S=>S.clone()),m.screensharing).then(()=>{e.dataChannelsEnabled&&w.createDataChannel("datachannel",e.dataChannelOptions)}).catch(S=>{M.warn("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to place call (userId=").concat(a,")"),S),S instanceof Gl&&S.code===Iy.UnknownDevice?e.emit(kn.Error,S):e.emit(kn.Error,new uA(Iy.PlaceCallFailed,"Failed to place call to ".concat(a))),w.hangup(ft.SignallingFailed,!1),l.get(y)===w&&l.delete(y)}))}};for(var[h,m]of s)d(h);l.size>0?e.calls.set(a,l):e.calls.delete(a)};for(var[{userId:i},s]of this.participants)r(i);n&&this.emit(kn.CallsChanged,this.calls)}getMemberStateEvents(e){return e===void 0?this.room.currentState.getStateEvents(Z.GroupCallMemberPrefix):this.room.currentState.getStateEvents(Z.GroupCallMemberPrefix,e)}initCall(e){var n=k2(e);if(!n)throw new Error("Cannot init call without user id");var r=()=>this.onCallFeedsChanged(e),i=(c,l)=>this.onCallStateChanged(e,c,l),s=this.onCallHangup,o=c=>this.onCallReplaced(e,c),a=this.callHandlers.get(n);a===void 0&&(a=new Map,this.callHandlers.set(n,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:r,onCallStateChanged:i,onCallHangup:s,onCallReplaced:o}),e.on(gt.FeedsChanged,r),e.on(gt.State,i),e.on(gt.Hangup,s),e.on(gt.Replaced,o),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(gt)),e.initStats(this.getGroupCallStats()),r()}disposeCall(e,n){var r=k2(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:c,onCallReplaced:l}=s.get(i);if(e.removeListener(gt.FeedsChanged,o),e.removeListener(gt.State,a),e.removeListener(gt.Hangup,c),e.removeListener(gt.Replaced,l),s.delete(r),s.size===0&&this.callHandlers.delete(r),e.hangupReason!==ft.Replaced){var d=this.getUserMediaFeed(r,i);d&&this.removeUserMediaFeed(d);var h=this.getScreenshareFeed(r,i);h&&this.removeScreenshareFeed(h)}}getUserMediaFeed(e,n){return this.userMediaFeeds.find(r=>r.userId===e&&r.deviceId===n)}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit(kn.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(e,n){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,n),e.dispose(),n.measureVolumeActivity(!0),this.emit(kn.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(e){var n=this.userMediaFeeds.findIndex(r=>r.userId===e.userId&&r.deviceId===e.deviceId);if(n===-1)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(n,1),e.dispose(),this.emit(kn.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(kn.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(e,n){return this.screenshareFeeds.find(r=>r.userId===e&&r.deviceId===n)}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit(kn.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(e,n){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,n),e.dispose(),this.emit(kn.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(e){var n=this.screenshareFeeds.findIndex(r=>r.userId===e.userId&&r.deviceId===e.deviceId);if(n===-1)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(n,1),e.dispose(),this.emit(kn.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){var e=this.room.getMember(this.client.getSafeUserId());if(!e){M.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===sr.Ended){this.participants=new Map;return}var n=new Map,r=Date.now(),i=this.state===sr.Entered||this.enteredViaAnotherSession,s=1/0;for(var o of this.getMemberStateEvents()){var a=this.room.getMember(o.getStateKey()),c=o.getContent(),l=Array.isArray(c["m.calls"])?c["m.calls"]:[],d=l.find(w=>w["m.call_id"]===this.groupCallId),h=Array.isArray(d?.["m.devices"])?d["m.devices"]:[],m=h.filter(w=>typeof w.device_id=="string"&&typeof w.session_id=="string"&&typeof w.expires_ts=="number"&&w.expires_ts>r&&Array.isArray(w.feeds));if(!i&&a?.userId===this.client.getUserId()&&(m=m.filter(w=>w.device_id!==this.client.getDeviceId())),m.length>0&&a?.membership===Be.Join){var g=new Map;n.set(a,g);for(var y of m)g.set(y.device_id,{sessionId:y.session_id,screensharing:y.feeds.some(w=>w.purpose===xn.Screenshare)}),y.expires_ts<s&&(s=y.expires_ts)}}if(i){var v=n.get(e);v===void 0&&(v=new Map,n.set(e,v)),v.has(this.client.getDeviceId())||v.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some(w=>w.purpose===xn.Screenshare)})}this.participants=n,s<1/0&&(this.participantsExpirationTimer=setTimeout(()=>this.updateParticipants(),s-r))}updateDevices(e){var n=arguments,r=this;return B(function*(){var i,s=n.length>1&&n[1]!==void 0?n[1]:!1,o=Date.now(),a=r.client.getUserId(),c=r.getMemberStateEvents(a),l=(i=c?.getContent())!==null&&i!==void 0?i:{},d=Array.isArray(l["m.calls"])?l["m.calls"]:[],h=null,m=[];for(var g of d)g["m.call_id"]===r.groupCallId?h=g:m.push(g);h===null&&(h={});var y=Array.isArray(h["m.devices"])?h["m.devices"]:[],v=y.filter(x=>typeof x.device_id=="string"&&typeof x.session_id=="string"&&typeof x.expires_ts=="number"&&x.expires_ts>o&&Array.isArray(x.feeds)),w=e(v);if(w!==null){var S=[...m];w.length>0&&S.push(I2(I2({},h),{},{"m.call_id":r.groupCallId,"m.devices":w}));var R={"m.calls":S};yield r.client.sendStateEvent(r.room.roomId,Z.GroupCallMemberPrefix,R,a,{keepAlive:s})}})()}addDeviceToMemberState(){var e=this;return B(function*(){yield e.updateDevices(n=>[...n.filter(r=>r.device_id!==e.client.getDeviceId()),{device_id:e.client.getDeviceId(),session_id:e.client.getSessionId(),expires_ts:Date.now()+L$,feeds:e.getLocalFeeds().map(r=>({purpose:r.purpose}))}])})()}updateMemberState(){var e=this;return B(function*(){e.resendMemberStateTimer!==null&&(clearInterval(e.resendMemberStateTimer),e.resendMemberStateTimer=null),e.state===sr.Entered?(yield e.addDeviceToMemberState(),e.resendMemberStateTimer=setInterval(B(function*(){M.log("GroupCall ".concat(e.groupCallId,' updateMemberState() resending call member state"'));try{yield e.addDeviceToMemberState()}catch(n){M.error("GroupCall ".concat(e.groupCallId," updateMemberState() failed to resend call member state"),n)}}),L$*3/4)):yield e.updateDevices(n=>n.filter(r=>r.device_id!==e.client.getDeviceId()),!0)})()}cleanMemberState(){var e=this;return B(function*(){var{devices:n}=yield e.client.getDevices(),r=new Map(n.map(i=>[i.device_id,i]));yield e.updateDevices(i=>{var s=i.filter(o=>{var a=r.get(o.device_id);return a?.last_seen_ts!==void 0&&!(o.device_id===e.client.getDeviceId()&&e.state!==sr.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 h1e(this.groupCallId,e,this.statsCollectIntervalTime),this.stats.reports.on(pu.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(pu.BYTE_SENT_STATS,this.onByteSentStats),this.stats.reports.on(pu.SUMMARY_STATS,this.onSummaryStats),this.stats.reports.on(pu.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 O$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function x2(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?O$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):O$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var at=function(t){return t.Fledgling="fledgling",t.InviteSent="invite_sent",t.WaitLocalMedia="wait_local_media",t.CreateOffer="create_offer",t.CreateAnswer="create_answer",t.Connecting="connecting",t.Connected="connected",t.Ringing="ringing",t.Ended="ended",t}({}),M$=function(t){return t.Voice="voice",t.Video="video",t}({}),xd=function(t){return t.Inbound="inbound",t.Outbound="outbound",t}({}),pr=function(t){return t.Local="local",t.Remote="remote",t}({}),gt=function(t){return t.Hangup="hangup",t.State="state",t.Error="error",t.Replaced="replaced",t.LocalHoldUnhold="local_hold_unhold",t.RemoteHoldUnhold="remote_hold_unhold",t.HoldUnhold="hold_unhold",t.FeedsChanged="feeds_changed",t.AssertedIdentityChanged="asserted_identity_changed",t.LengthChanged="length_changed",t.DataChannel="datachannel",t.SendVoipEvent="send_voip_event",t.PeerConnectionCreated="peer_connection_created",t}({}),ft=function(t){return t.UserHangup="user_hangup",t.LocalOfferFailed="local_offer_failed",t.NoUserMedia="no_user_media",t.UnknownDevices="unknown_devices",t.SendInvite="send_invite",t.CreateAnswer="create_answer",t.CreateOffer="create_offer",t.SendAnswer="send_answer",t.SetRemoteDescription="set_remote_description",t.SetLocalDescription="set_local_description",t.AnsweredElsewhere="answered_elsewhere",t.IceFailed="ice_failed",t.InviteTimeout="invite_timeout",t.Replaced="replaced",t.SignallingFailed="signalling_timeout",t.UserBusy="user_busy",t.Transferred="transferred",t.NewSession="new_session",t}({}),m1e="1",g1e="stun:turn.matrix.org",Pk=60*1e3,v1e=1e3,y1e=30*1e3,b1e=2*1e3;class Gl extends Error{constructor(e,n,r){super(n+": "+r),L(this,"code",void 0),this.code=e}}function Th(){return Date.now().toString()+To(16)}function D$(t){var e=[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:t?12e3:void 0}];return e}function Ua(t,e){return t+":"+e}class _1e extends On{constructor(e){var n,r;if(super(),n=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",at.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&&M.warn("Call ".concat(this.callId," gotLocalIceCandidate() got candidate after candidates have ended!")),M.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;M.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),M.debug("Call ".concat(this.callId," onIceGatheringStateChange() ice gathering state complete, set candidates have ended")))}),L(this,"getLocalOfferFailed",s=>{M.error("Call ".concat(this.callId," getLocalOfferFailed() running"),s),this.emit(gt.Error,new Gl(ft.LocalOfferFailed,"Failed to get local offer!",s),this),this.terminate(pr.Local,ft.LocalOfferFailed,!1)}),L(this,"getUserMediaFailed",s=>{if(this.successor){this.successor.getUserMediaFailed(s);return}M.warn("Call ".concat(this.callId," getUserMediaFailed() failed to get user media - ending call"),s),this.emit(gt.Error,new Gl(ft.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",s),this),this.terminate(pr.Local,ft.NoUserMedia,!1)}),L(this,"placeCallFailed",s=>{if(this.successor){this.successor.placeCallFailed(s);return}M.warn("Call ".concat(this.callId," placeCallWithCallFeeds() failed - ending call"),s),this.emit(gt.Error,new Gl(ft.IceFailed,"Couldn't start call! Invalid ICE server configuration.",s),this),this.terminate(pr.Local,ft.IceFailed,!1)}),L(this,"onIceConnectionStateChanged",()=>{var s,o,a,c,l,d;if(!this.callHasEnded()){if(M.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=(c=this.peerConn)===null||c===void 0?void 0:c.iceConnectionState)!==null&&a!==void 0?a:""))clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.iceReconnectionTimeOut&&clearTimeout(this.iceReconnectionTimeOut),this.state=at.Connected,!this.callLengthInterval&&!this.callStartTime&&(this.callStartTime=Date.now(),this.callLengthInterval=setInterval(()=>{this.emit(gt.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3),this)},v1e));else if(((l=this.peerConn)===null||l===void 0?void 0:l.iceConnectionState)=="failed"){var h;if(this.candidatesEnded=!1,(h=this.peerConn)!==null&&h!==void 0&&h.restartIce){var m;this.candidatesEnded=!1,M.debug("Call ".concat(this.callId," onIceConnectionStateChanged() ice restart (state=").concat((m=this.peerConn)===null||m===void 0?void 0:m.iceConnectionState,")")),this.peerConn.restartIce()}else M.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)")),this.hangup(ft.IceFailed,!1)}else((d=this.peerConn)===null||d===void 0?void 0:d.iceConnectionState)=="disconnected"&&(this.candidatesEnded=!1,this.iceReconnectionTimeOut=setTimeout(()=>{var y,v,w;M.info("Call ".concat(this.callId," onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=").concat((y=this.peerConn)===null||y===void 0?void 0:y.iceConnectionState,", conn=").concat((v=this.peerConn)===null||v===void 0?void 0:v.connectionState,")")),(w=this.peerConn)!==null&&w!==void 0&&w.restartIce&&(this.candidatesEnded=!1,this.peerConn.restartIce()),this.iceReconnectionTimeOut=void 0},b1e),this.iceDisconnectedTimeout=setTimeout(()=>{M.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)")),this.hangup(ft.IceFailed,!1)},y1e),this.state=at.Connecting);if(this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState))for(var g of this.getRemoteFeeds())g.setAudioVideoMuted(!0,!0)}}),L(this,"onSignallingStateChanged",()=>{var s;M.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){M.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&&(M.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(gt.DataChannel,s.channel,this)}),L(this,"onNegotiationNeeded",B(function*(){if(M.info("Call ".concat(n.callId," onNegotiationNeeded() negotiation is needed!")),n.state!==at.CreateOffer&&n.opponentVersion===0){M.info("Call ".concat(n.callId," onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event"));return}n.queueGotLocalOffer()})),L(this,"onHangupReceived",s=>{M.debug("Call ".concat(this.callId," onHangupReceived() running")),this.partyIdMatches(s)||this.state===at.Ringing?this.terminate(pr.Remote,s.reason||ft.UserHangup,!0):M.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=>{M.debug("Call ".concat(this.callId," onRejectReceived() running"));var o=[at.InviteSent,at.Ringing].includes(this.state)||this.state===at.Fledgling&&this.direction===xd.Inbound;o?this.terminate(pr.Remote,s.reason||ft.UserHangup,!0):M.debug("Call ".concat(this.callId," onRejectReceived() called in wrong state (state=").concat(this.state,")"))}),L(this,"onAnsweredElsewhere",s=>{M.debug("Call ".concat(this.callId," onAnsweredElsewhere() running")),this.terminate(pr.Remote,ft.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:[g1e]});for(var i of this.turnServers)$X(i,["urls"]);this.callId=Th(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}placeVoiceCall(){var e=this;return B(function*(){yield e.placeCall(!0,!1)})()}placeVideoCall(){var e=this;return B(function*(){yield e.placeCall(!0,!0)})()}createDataChannel(e,n){var r=this.peerConn.createDataChannel(e,n);return this.emit(gt.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 n=this._state;this._state=e,this.emit(gt.State,e,n,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?M$.Video:M$.Voice}get hasLocalUserMediaVideoTrack(){var e;return!!((e=this.localUsermediaStream)!==null&&e!==void 0&&e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some(e=>{var n;return e.purpose===xn.Usermedia&&((n=e.stream)===null||n===void 0?void 0:n.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 n;return e.purpose===xn.Usermedia&&!!((n=e.stream)!==null&&n!==void 0&&n.getAudioTracks().length)})}get hasUserMediaAudioSender(){var e;return!!(!((e=this.transceivers.get(Ua(xn.Usermedia,"audio")))===null||e===void 0)&&e.sender)}get hasUserMediaVideoSender(){var e;return!!(!((e=this.transceivers.get(Ua(xn.Usermedia,"video")))===null||e===void 0)&&e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find(e=>e.purpose===xn.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(e=>e.purpose===xn.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===xn.Usermedia)}get remoteScreensharingFeed(){return this.getRemoteFeeds().find(e=>e.purpose===xn.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(n=>n.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 B(function*(){var n;if(e.opponentDeviceId&&e.client.getUseE2eForGroupCall()){if(!e.client.getCrypto()){e.hasOpponentDeviceInfo=!0;return}var r=e.invitee||((n=e.getOpponentMember())===null||n===void 0?void 0:n.userId);throw r?(e.hasOpponentDeviceInfo=!1,new qJ(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,n={};for(var r of this.getLocalFeeds())e&&(r.sdpMetadataStreamId=r.stream.id),n[r.sdpMetadataStreamId]={purpose:r.purpose,audio_muted:r.isAudioMuted(),video_muted:r.isVideoMuted()};return n}noIncomingFeeds(){return!this.feeds.some(e=>!e.isLocal())}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata()){this.pushRemoteFeedWithoutMetadata(e);return}var n=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){M.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)){M.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 iu({client:this.client,call:this,roomId:this.roomId,userId:n,deviceId:this.getOpponentDeviceId(),stream:e,purpose:r,audioMuted:i,videoMuted:s})),this.emit(gt.FeedsChanged,this.feeds,this),M.info("Call ".concat(this.callId," pushRemoteFeed() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,", purpose=").concat(r,")"))}pushRemoteFeedWithoutMetadata(e){var n,r=this.getOpponentMember().userId,i=xn.Usermedia,s=(n=this.feeds.find(o=>!o.isLocal()))===null||n===void 0?void 0:n.stream;if(s&&e.id!==s.id){M.warn("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=").concat(e.id,")"));return}if(this.getFeedByStreamId(e.id)){M.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 iu({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:r,deviceId:this.getOpponentDeviceId(),stream:e,purpose:i})),this.emit(gt.FeedsChanged,this.feeds,this),M.info("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,")"))}pushNewLocalFeed(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=this.client.getUserId();if(Nr(e.getAudioTracks(),!0),Nr(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)){M.warn("Call ".concat(this.callId," pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.pushLocalFeed(new iu({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:n}),r)}pushLocalFeed(e){var n=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(this.feeds.some(o=>e.stream.id===o.stream.id)){M.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(){M.info("Call ".concat(n.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=Ua(e.purpose,s.kind);if(n.transceivers.has(a)){var c=n.transceivers.get(a);c.sender.replaceTrack(s),c.direction=c.direction==="inactive"?"sendonly":"sendrecv"}else{var l=n.peerConn.addTrack(s,e.stream),d=n.peerConn.getTransceivers().find(h=>h.sender===l);d?n.transceivers.set(a,d):M.warn("Call ".concat(n.callId," pushLocalFeed() didn't find a matching transceiver after adding track!"))}};for(var s of e.stream.getTracks())i()}M.info("Call ".concat(this.callId," pushLocalFeed() pushed stream (id=").concat(e.stream.id,", active=").concat(e.stream.active,", purpose=").concat(e.purpose,")")),this.emit(gt.FeedsChanged,this.feeds,this)}removeLocalFeed(e){var n=Ua(e.purpose,"audio"),r=Ua(e.purpose,"video");for(var i of[n,r])if(this.transceivers.has(i)){var s=this.transceivers.get(i);s.sender&&this.peerConn.removeTrack(s.sender)}e.purpose===xn.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(gt.FeedsChanged,this.feeds,this)}deleteFeedByStream(e){var n=this.getFeedByStreamId(e.id);if(!n){M.warn("Call ".concat(this.callId," deleteFeedByStream() didn't find the feed to delete (streamId=").concat(e.id,")"));return}this.deleteFeed(n)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit(gt.FeedsChanged,this.feeds,this)}getCurrentCallStats(){var e=this;return B(function*(){return e.callHasEnded()?e.callStatsAtEnd:e.collectCallStats()})()}collectCallStats(){var e=this;return B(function*(){if(e.peerConn){var n=yield e.peerConn.getStats(),r=[];return n.forEach(i=>{r.push(i)}),r}})()}initWithInvite(e){var n=this;return B(function*(){var r,i=e.getContent();n.direction=xd.Inbound;var s=yield n.client.checkTurnServers();s||M.warn("Call ".concat(n.callId," initWithInvite() failed to get TURN credentials! Proceeding with call anyway..."));var o=i[_d];o?n.updateRemoteSDPStreamMetadata(o):M.debug("Call ".concat(n.callId," initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams")),n.peerConn=n.createPeerConnection(),n.emit(gt.PeerConnectionCreated,n.peerConn,n),n.chooseOpponent(e),yield n.initOpponentCrypto();try{yield n.peerConn.setRemoteDescription(i.offer),M.debug("Call ".concat(n.callId," initWithInvite() set remote description: ").concat(i.offer.type)),yield n.addBufferedIceCandidates()}catch(d){M.debug("Call ".concat(n.callId," initWithInvite() failed to set remote description"),d),n.terminate(pr.Local,ft.SetRemoteDescription,!1);return}var a=(r=n.feeds.find(d=>!d.isLocal()))===null||r===void 0?void 0:r.stream;if(!n.isOnlyDataChannelAllowed&&(!a||a.getTracks().length===0)){M.error("Call ".concat(n.callId," initWithInvite() no remote stream or no tracks after setting remote description!")),n.terminate(pr.Local,ft.SetRemoteDescription,!1);return}if(n.state=at.Ringing,e.getLocalAge()){var c=setTimeout(()=>{if(n.state==at.Ringing){var d;M.debug("Call ".concat(n.callId," initWithInvite() invite has expired. Hanging up.")),n.hangupParty=pr.Remote,n.state=at.Ended,n.stopAllMedia(),n.peerConn.signalingState!="closed"&&n.peerConn.close(),(d=n.stats)===null||d===void 0||d.removeStatsReportGatherer(n.callId),n.emit(gt.Hangup,n)}},i.lifetime-e.getLocalAge()),l=d=>{d!==at.Ringing&&(clearTimeout(c),n.off(gt.State,l))};n.on(gt.State,l)}})()}initWithHangup(e){this.state=at.Ended}shouldAnswerWithMediaType(e,n,r){return e&&!n?(M.warn("Call ".concat(this.callId," shouldAnswerWithMediaType() unable to answer with ").concat(r," because the other side isn't sending it either.")),!1):!VX(e)&&e!==n&&!this.opponentSupportsSDPStreamMetadata()?(M.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(n,".")),n):e??n}answer(e,n){var r=this;return B(function*(){if(!r.inviteOrAnswerSent){if(e===!1&&n===!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(n,r.hasRemoteUserMediaVideoTrack,"video");r.state=at.WaitLocalMedia,r.waitForLocalAVStream=!0;try{var a,c=yield r.client.getMediaHandler().getUserMediaStream(s,o);r.waitForLocalAVStream=!1;var l=new iu({client:r.client,roomId:r.roomId,userId:r.client.getUserId(),deviceId:(a=r.client.getDeviceId())!==null&&a!==void 0?a:void 0,stream:c,purpose:xn.Usermedia,audioMuted:!1,videoMuted:!1}),d=[l];r.localScreensharingFeed&&d.push(r.localScreensharingFeed),r.answerWithCallFeeds(d)}catch(h){if(o)M.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(h);return}}}else r.waitForLocalAVStream&&(r.state=at.WaitLocalMedia)}})()}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){M.debug("Call ".concat(this.callId," replacedBy() running (newCallId=").concat(e.callId,")")),this.state===at.WaitLocalMedia?(M.debug("Call ".concat(this.callId," replacedBy() telling new call to wait for local media (newCallId=").concat(e.callId,")")),e.waitForLocalAVStream=!0):[at.CreateOffer,at.InviteSent].includes(this.state)&&(e.direction===xd.Outbound?e.queueGotCallFeedsForAnswer([]):(M.debug("Call ".concat(this.callId," replacedBy() handing local stream to new call(newCallId=").concat(e.callId,")")),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(n=>n.clone())))),this.successor=e,this.emit(gt.Replaced,e,this),this.hangup(ft.Replaced,!0)}hangup(e,n){if(!this.callHasEnded()&&(M.debug("Call ".concat(this.callId," hangup() ending call (reason=").concat(e,")")),this.terminate(pr.Local,e,!n),![at.Fledgling,at.WaitLocalMedia].includes(this.state))){var r={};(this.opponentVersion&&this.opponentVersion!==0||e!==ft.UserHangup)&&(r.reason=e),this.sendVoipEvent(Z.CallHangup,r)}}reject(){if(this.state!==at.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion===0){M.info("Call ".concat(this.callId," reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=").concat(this.opponentVersion,")")),this.hangup(ft.UserHangup,!0);return}M.debug("Rejecting call: "+this.callId),this.terminate(pr.Local,ft.UserHangup,!0),this.sendVoipEvent(Z.CallReject,{})}upgradeCall(e,n){var r=this;return B(function*(){if(!(!e&&!n)&&r.opponentSupportsSDPStreamMetadata())try{M.debug("Call ".concat(r.callId," upgradeCall() upgrading call (audio=").concat(e,", video=").concat(n,")"));var i=e||r.hasLocalUserMediaAudioTrack,s=n||r.hasLocalUserMediaVideoTrack,o=yield r.client.getMediaHandler().getUserMediaStream(i,s,!1);yield r.updateLocalUsermediaStream(o,e,n)}catch(a){M.error("Call ".concat(r.callId," upgradeCall() failed to upgrade the call"),a),r.emit(gt.Error,new Gl(ft.NoUserMedia,"Failed to get camera access: ",a),r)}})()}opponentSupportsSDPStreamMetadata(){return!!this.remoteSDPStreamMetadata}isScreensharing(){return!!this.localScreensharingStream}setScreensharingEnabled(e,n){var r=this;return B(function*(){if(e&&r.isScreensharing())return M.warn("Call ".concat(r.callId," setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!")),!0;if(!e&&!r.isScreensharing())return M.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,n);if(M.debug("Call ".concat(r.callId," setScreensharingEnabled() running (enabled=").concat(e,")")),e)try{var i=yield r.client.getMediaHandler().getScreensharingStream(n);return i?(r.pushNewLocalFeed(i,xn.Screenshare),!0):!1}catch(c){return M.error("Call ".concat(r.callId," setScreensharingEnabled() failed to get screen-sharing stream:"),c),!1}else{var s=r.transceivers.get(Ua(xn.Screenshare,"audio")),o=r.transceivers.get(Ua(xn.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,n){var r=this;return B(function*(){if(M.debug("Call ".concat(r.callId," setScreensharingEnabledWithoutMetadataSupport() running (enabled=").concat(e,")")),e)try{var i,s=yield r.client.getMediaHandler().getScreensharingStream(n);if(!s)return!1;var o=s.getTracks().find(m=>m.kind==="video"),a=(i=r.transceivers.get(Ua(xn.Usermedia,"video")))===null||i===void 0?void 0:i.sender;return a?.replaceTrack(o??null),r.pushNewLocalFeed(s,xn.Screenshare,!1),!0}catch(m){return M.error("Call ".concat(r.callId," setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:"),m),!1}else{var c,l,d=(c=r.localUsermediaStream)===null||c===void 0?void 0:c.getTracks().find(m=>m.kind==="video"),h=(l=r.transceivers.get(Ua(xn.Usermedia,"video")))===null||l===void 0?void 0:l.sender;return h?.replaceTrack(d??null),r.client.getMediaHandler().stopScreensharingStream(r.localScreensharingStream),r.deleteFeedByStream(r.localScreensharingStream),!1}})()}updateLocalUsermediaStream(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:!1,s=n.length>2&&n[2]!==void 0?n[2]:!1,o=r.localUsermediaFeed,a=i||!o.isAudioMuted()&&!r.remoteOnHold,c=s||!o.isVideoMuted()&&!r.remoteOnHold;M.log("Call ".concat(r.callId," updateLocalUsermediaStream() running (streamId=").concat(e.id,", audio=").concat(a,", video=").concat(c,")")),Nr(e.getAudioTracks(),a),Nr(e.getVideoTracks(),c);for(var l of r.localUsermediaStream.getTracks())r.localUsermediaStream.removeTrack(l),l.stop();for(var d of e.getTracks())r.localUsermediaStream.addTrack(d);var h=function*(){var y=Ua(xn.Usermedia,m.kind),v=r.transceivers.get(y),w=v?.sender,S=!1;if(w)try{M.info("Call ".concat(r.callId," updateLocalUsermediaStream() replacing track (id=").concat(m.id,", kind=").concat(m.kind,", streamId=").concat(e.id,", streamPurpose=").concat(o.purpose,")")),yield w.replaceTrack(m),v.direction=v.direction==="inactive"?"sendonly":"sendrecv",S=!0}catch(T){M.warn("Call ".concat(r.callId," updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead"),T)}if(!S){M.info("Call ".concat(r.callId," updateLocalUsermediaStream() adding track to peer connection (id=").concat(m.id,", kind=").concat(m.kind,", streamId=").concat(e.id,", streamPurpose=").concat(o.purpose,")"));var R=r.peerConn.addTrack(m,r.localUsermediaStream),x=r.peerConn.getTransceivers().find(T=>T.sender===R);x?r.transceivers.set(y,x):M.warn("Call ".concat(r.callId," updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!"))}};for(var m of e.getTracks())yield*h()})()}setLocalVideoMuted(e){var n=this;return B(function*(){var r;if(M.log("Call ".concat(n.callId," setLocalVideoMuted() running ").concat(e)),!e&&n.stopVideoTrackTimer!==void 0&&(clearTimeout(n.stopVideoTrackTimer),n.stopVideoTrackTimer=void 0),!(yield n.client.getMediaHandler().hasVideoDevice()))return n.isLocalVideoMuted();if(!n.hasUserMediaVideoSender&&!e){var i;return(i=n.localUsermediaFeed)===null||i===void 0||i.setAudioVideoMuted(null,e),yield n.upgradeCall(!1,!0),n.isLocalVideoMuted()}if(!e&&n.localUsermediaStream.getVideoTracks().length===0){var s=yield n.client.getMediaHandler().getUserMediaStream(!0,!0);yield n.updateLocalUsermediaStream(s)}return(r=n.localUsermediaFeed)===null||r===void 0||r.setAudioVideoMuted(null,e),n.updateMuteStatus(),yield n.sendMetadataUpdate(),e&&(n.stopVideoTrackTimer=setTimeout(()=>{for(var o of n.localUsermediaStream.getVideoTracks())o.stop(),n.localUsermediaStream.removeTrack(o)},120)),n.isLocalVideoMuted()})()}isLocalVideoMuted(){var e,n;return(e=(n=this.localUsermediaFeed)===null||n===void 0?void 0:n.isVideoMuted())!==null&&e!==void 0?e:!1}setMicrophoneMuted(e){var n=this;return B(function*(){var r;return M.log("Call ".concat(n.callId," setMicrophoneMuted() running ").concat(e)),(yield n.client.getMediaHandler().hasAudioDevice())?!e&&(!n.hasUserMediaAudioSender||!n.hasLocalUserMediaAudioTrack)?(yield n.upgradeCall(!0,!1),n.isMicrophoneMuted()):((r=n.localUsermediaFeed)===null||r===void 0||r.setAudioVideoMuted(e,null),n.updateMuteStatus(),yield n.sendMetadataUpdate(),n.isMicrophoneMuted()):n.isMicrophoneMuted()})()}isMicrophoneMuted(){var e,n;return(e=(n=this.localUsermediaFeed)===null||n===void 0?void 0:n.isAudioMuted())!==null&&e!==void 0?e:!1}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(var n of this.peerConn.getTransceivers())n.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit(gt.RemoteHoldUnhold,this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!==at.Connected)return!1;var e=!0;for(var n of this.peerConn.getTransceivers()){var r=["inactive","recvonly"].includes(n.currentDirection);r||(e=!1)}return e}sendDtmfDigit(e){for(var n of this.peerConn.getSenders()){var r;if(((r=n.track)===null||r===void 0?void 0:r.kind)==="audio"&&n.dtmf){n.dtmf.insertDTMF(e);return}}throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){var e=this.isMicrophoneMuted()||this.remoteOnHold,n=this.isLocalVideoMuted()||this.remoteOnHold;M.log("Call ".concat(this.callId," updateMuteStatus stream ").concat(this.localUsermediaStream.id," micShouldBeMuted ").concat(e," vidShouldBeMuted ").concat(n)),Nr(this.localUsermediaStream.getAudioTracks(),!e),Nr(this.localUsermediaStream.getVideoTracks(),!n)}sendMetadataUpdate(){var e=this;return B(function*(){yield e.sendVoipEvent(Z.CallSDPStreamMetadataChangedPrefix,{[_d]:e.getLocalSDPStreamMetadata()})})()}gotCallFeedsForInvite(e){var n=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);n&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=at.CreateOffer,M.debug("Call ".concat(this.callId," gotUserMediaForInvite() run"))}sendAnswer(){var e=this;return B(function*(){var n={answer:{sdp:e.peerConn.localDescription.sdp,type:e.peerConn.localDescription.type},[_d]:e.getLocalSDPStreamMetadata(!0)};n.capabilities={"m.call.transferee":e.client.supportsCallTransfer,"m.call.dtmf":!1};var r=e.discardDuplicateCandidates();M.info("Call ".concat(e.callId," sendAnswer() discarding ").concat(r," candidates that will be sent in answer"));try{yield e.sendVoipEvent(Z.CallAnswer,n),e.inviteOrAnswerSent=!0}catch(o){e.state=at.Ringing,o instanceof tr&&o.event&&e.client.cancelPendingEvent(o.event);var i=ft.SendAnswer,s="Failed to send answer";throw o.name=="UnknownDeviceError"&&(i=ft.UnknownDevices,s="Unknown devices present in the room"),e.emit(gt.Error,new Gl(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,n){var r=sA.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 c of n)if(c.mediaType===i.type){if(!o.has(c.codec)){M.info("Call ".concat(this.callId," mungeSdp() ignoring SDP modifications for ").concat(c.codec," as it's not present."));continue}var l=[];c.enableDtx!==void 0&&l.push("usedtx=".concat(c.enableDtx?"1":"0")),c.maxAverageBitrate!==void 0&&l.push("maxaveragebitrate=".concat(c.maxAverageBitrate));var d=!1;for(var h of i.fmtp)s.get(h.payload)===c.codec&&(d=!0,h.config+=";"+l.join(";"));d||i.fmtp.push({payload:o.get(c.codec),config:l.join(";")})}}),e.sdp=sA.write(r)}createOffer(){var e=this;return B(function*(){var n=yield e.peerConn.createOffer();return e.mungeSdp(n,D$(e.isPtt)),n})()}createAnswer(){var e=this;return B(function*(){var n=yield e.peerConn.createAnswer();return e.mungeSdp(n,D$(e.isPtt)),n})()}gotCallFeedsForAnswer(e){var n=this;return B(function*(){if(!n.callHasEnded()){n.waitForLocalAVStream=!1;for(var r of e)n.pushLocalFeed(r);n.state=at.CreateAnswer;var i;try{n.getRidOfRTXCodecs(),i=yield n.createAnswer()}catch(s){M.debug("Call ".concat(n.callId," gotCallFeedsForAnswer() failed to create answer: "),s),n.terminate(pr.Local,ft.CreateAnswer,!0);return}try{if(yield n.peerConn.setLocalDescription(i),n.callHasEnded()||(n.state=at.Connecting,yield new Promise(s=>{setTimeout(s,200)}),n.callHasEnded()))return;n.sendAnswer()}catch(s){M.debug("Call ".concat(n.callId," gotCallFeedsForAnswer() error setting local description!"),s),n.terminate(pr.Local,ft.SetLocalDescription,!0);return}}})()}onRemoteIceCandidatesReceived(e){var n=this;return B(function*(){if(!n.callHasEnded()){var r=e.getContent(),i=r.candidates;if(!i){M.info("Call ".concat(n.callId," onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!"));return}var s=r.version===0?null:r.party_id||null;if(n.opponentPartyId===void 0){if(s){M.info("Call ".concat(n.callId," onRemoteIceCandidatesReceived() buffering ").concat(i.length," candidates until we pick an opponent"));var o=n.remoteCandidateBuffer.get(s)||[];o.push(...i),n.remoteCandidateBuffer.set(s,o)}return}if(!n.partyIdMatches(r)){M.info("Call ".concat(n.callId," onRemoteIceCandidatesReceived() ignoring candidates from party ID ").concat(r.party_id,": we have chosen party ID ").concat(n.opponentPartyId));return}yield n.addIceCandidates(i)}})()}onAnswerReceived(e){var n=this;return B(function*(){var r=e.getContent();if(M.debug("Call ".concat(n.callId," onAnswerReceived() running (hangupParty=").concat(r.party_id,")")),n.callHasEnded()){M.debug("Call ".concat(n.callId," onAnswerReceived() ignoring answer because call has ended"));return}if(n.opponentPartyId!==void 0){M.info("Call ".concat(n.callId," onAnswerReceived() ignoring answer from party ID ").concat(r.party_id,": we already have an answer/reject from ").concat(n.opponentPartyId));return}n.chooseOpponent(e),yield n.addBufferedIceCandidates(),n.state=at.Connecting;var i=r[_d];i?n.updateRemoteSDPStreamMetadata(i):M.warn("Call ".concat(n.callId," onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams"));try{n.isSettingRemoteAnswerPending=!0,yield n.peerConn.setRemoteDescription(r.answer),n.isSettingRemoteAnswerPending=!1,M.debug("Call ".concat(n.callId," onAnswerReceived() set remote description: ").concat(r.answer.type))}catch(s){n.isSettingRemoteAnswerPending=!1,M.debug("Call ".concat(n.callId," onAnswerReceived() failed to set remote description"),s),n.terminate(pr.Local,ft.SetRemoteDescription,!1);return}if(n.opponentPartyId!==null)try{yield n.sendVoipEvent(Z.CallSelectAnswer,{selected_party_id:n.opponentPartyId})}catch(s){M.warn("Call ".concat(n.callId," onAnswerReceived() failed to send select_answer event"),s)}})()}onSelectAnswerReceived(e){var n=this;return B(function*(){if(n.direction!==xd.Inbound){M.warn("Call ".concat(n.callId," onSelectAnswerReceived() got select_answer for an outbound call: ignoring"));return}var r=e.getContent().selected_party_id;if(r==null){M.warn("Call ".concat(n.callId," onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring"));return}r!==n.ourPartyId&&(M.info("Call ".concat(n.callId," onSelectAnswerReceived() got select_answer for party ID ").concat(r,": we are party ID ").concat(n.ourPartyId,".")),yield n.terminate(pr.Remote,ft.AnsweredElsewhere,!0))})()}onNegotiateReceived(e){var n=this;return B(function*(){var r=e.getContent(),i=r.description;if(!i||!i.sdp||!i.type){M.info("Call ".concat(n.callId," onNegotiateReceived() ignoring invalid m.call.negotiate event"));return}var s=n.direction===xd.Inbound,o=!n.makingOffer&&(n.peerConn.signalingState==="stable"||n.isSettingRemoteAnswerPending),a=i.type==="offer"&&!o;if(n.ignoreOffer=!s&&a,n.ignoreOffer){M.info("Call ".concat(n.callId," onNegotiateReceived() ignoring colliding negotiate event because we're impolite"));return}var c=n.isLocalOnHold(),l=r[_d];l?n.updateRemoteSDPStreamMetadata(l):M.warn("Call ".concat(n.callId," onNegotiateReceived() received negotiation event without SDPStreamMetadata!"));try{if(n.isSettingRemoteAnswerPending=i.type=="answer",yield n.peerConn.setRemoteDescription(i),n.isSettingRemoteAnswerPending=!1,M.debug("Call ".concat(n.callId," onNegotiateReceived() set remote description: ").concat(i.type)),i.type==="offer"){var d,h;try{n.getRidOfRTXCodecs(),h=yield n.createAnswer()}catch(g){M.debug("Call ".concat(n.callId," onNegotiateReceived() failed to create answer: "),g),n.terminate(pr.Local,ft.CreateAnswer,!0);return}yield n.peerConn.setLocalDescription(h),M.debug("Call ".concat(n.callId," onNegotiateReceived() create an answer")),n.sendVoipEvent(Z.CallNegotiate,{lifetime:Pk,description:(d=n.peerConn.localDescription)===null||d===void 0?void 0:d.toJSON(),[_d]:n.getLocalSDPStreamMetadata(!0)})}}catch(g){n.isSettingRemoteAnswerPending=!1,M.warn("Call ".concat(n.callId," onNegotiateReceived() failed to complete negotiation"),g)}var m=n.isLocalOnHold();c!==m&&(n.emit(gt.LocalHoldUnhold,m,n),n.emit(gt.HoldUnhold,m))})()}updateRemoteSDPStreamMetadata(e){this.remoteSDPStreamMetadata=qX(this.remoteSDPStreamMetadata||{},e,!0);for(var n of this.getRemoteFeeds()){var r,i=n.stream.id,s=this.remoteSDPStreamMetadata[i];n.setAudioVideoMuted(s?.audio_muted,s?.video_muted),n.purpose=(r=this.remoteSDPStreamMetadata[i])===null||r===void 0?void 0:r.purpose}}onSDPStreamMetadataChangedReceived(e){var n=e.getContent(),r=n[_d];this.updateRemoteSDPStreamMetadata(r)}onAssertedIdentityReceived(e){var n=this;return B(function*(){var r=e.getContent();r.asserted_identity&&(n.remoteAssertedIdentity={id:r.asserted_identity.id,displayName:r.asserted_identity.display_name},n.emit(gt.AssertedIdentityChanged,n))})()}callHasEnded(){return this.state===at.Ended}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.wrappedGotLocalOffer()):this.responsePromiseChain=this.wrappedGotLocalOffer()}wrappedGotLocalOffer(){var e=this;return B(function*(){e.makingOffer=!0;try{yield e.gotLocalOffer()}catch(n){e.getLocalOfferFailed(n);return}finally{e.makingOffer=!1}})()}gotLocalOffer(){var e=this;return B(function*(){if(M.debug("Call ".concat(e.callId," gotLocalOffer() running")),e.callHasEnded()){M.debug("Call ".concat(e.callId,' gotLocalOffer() ignoring newly created offer because the call has ended"'));return}var n;try{e.getRidOfRTXCodecs(),n=yield e.createOffer()}catch(d){M.debug("Call ".concat(e.callId," gotLocalOffer() failed to create offer: "),d),e.terminate(pr.Local,ft.CreateOffer,!0);return}try{yield e.peerConn.setLocalDescription(n)}catch(d){M.debug("Call ".concat(e.callId," gotLocalOffer() error setting local description!"),d),e.terminate(pr.Local,ft.SetLocalDescription,!0);return}if(e.peerConn.iceGatheringState==="gathering"&&(yield new Promise(d=>{setTimeout(d,200)})),!e.callHasEnded()){var r=e.state===at.CreateOffer?Z.CallInvite:Z.CallNegotiate,i={lifetime:Pk};if(r===Z.CallInvite&&e.invitee&&(i.invitee=e.invitee),e.state===at.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[_d]=e.getLocalSDPStreamMetadata(!0);var a=e.discardDuplicateCandidates();M.info("Call ".concat(e.callId," gotLocalOffer() discarding ").concat(a," candidates that will be sent in offer"));try{yield e.sendVoipEvent(r,i)}catch(d){M.error("Call ".concat(e.callId," gotLocalOffer() failed to send invite"),d),d instanceof tr&&d.event&&e.client.cancelPendingEvent(d.event);var c=ft.SignallingFailed,l="Signalling failed";e.state===at.CreateOffer&&(c=ft.SendInvite,l="Failed to send invite"),d.name=="UnknownDeviceError"&&(c=ft.UnknownDevices,l="Unknown devices present in the room"),e.emit(gt.Error,new Gl(c,l,d),e),e.terminate(pr.Local,c,!1);return}e.sendCandidateQueue(),e.state===at.CreateOffer&&(e.inviteOrAnswerSent=!0,e.state=at.InviteSent,e.inviteTimeout=setTimeout(()=>{e.inviteTimeout=void 0,e.state===at.InviteSent&&e.hangup(ft.InviteTimeout,!1)},Pk))}})()}getRidOfRTXCodecs(){if(!(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)){var e=this.transceivers.get(Ua(xn.Screenshare,"video"));if(!(!e||!e.setCodecPreferences)){var n=RTCRtpReceiver.getCapabilities("video").codecs,r=RTCRtpSender.getCapabilities("video").codecs,i=[];for(var s of[...n,...r])if(s.mimeType!=="video/rtx"){i.push(s);try{e.setCodecPreferences(i)}catch(o){M.info("Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences",s,o),i.pop()}}}}}sendVoipEvent(e,n){var r=this;return B(function*(){var i=x2(x2({},n),{},{version:m1e,call_id:r.callId,party_id:r.ourPartyId,conf_id:r.groupCallId});if(r.opponentDeviceId){var s,o=r.toDeviceSeq++,a=x2(x2({},i),{},{device_id:r.client.deviceId,sender_session_id:r.client.getSessionId(),dest_session_id:r.opponentSessionId,seq:o,[X3]:H0e()});r.emit(gt.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 c=r.invitee||r.getOpponentMember().userId;if(r.client.getUseE2eForGroupCall()){if(!r.hasOpponentDeviceInfo){M.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([[c,new Map([[r.opponentDeviceId,a]])]]))}else{var l;r.emit(gt.SendVoipEvent,{type:"sendEvent",eventType:e,roomId:r.roomId,content:i,userId:r.invitee||((l=r.getOpponentMember())===null||l===void 0?void 0:l.userId)},r),yield r.client.sendEvent(r.roomId,e,i)}})()}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,!(this.state===at.Ringing||!this.inviteOrAnswerSent)){var n=this.direction===xd.Inbound?500:2e3;this.candidateSendTries===0&&setTimeout(()=>{this.sendCandidateQueue()},n)}}discardDuplicateCandidates(){for(var e=0,n=[],r=0;r<this.candidateSendQueue.length;r++){var i=this.candidateSendQueue[r];i.candidate===""?n.push(i):e++}return this.candidateSendQueue=n,e}transfer(e){var n=this;return B(function*(){var r=yield n.client.getProfileInfo(e),i=Th(),s={replacement_id:Th(),target_user:{id:e,display_name:r.displayname,avatar_url:r.avatar_url},create_call:i};yield n.sendVoipEvent(Z.CallReplaces,s),yield n.terminate(pr.Local,ft.Transferred,!0)})()}transferToCall(e){var n=this;return B(function*(){var r,i,s=(r=e.getOpponentMember())===null||r===void 0?void 0:r.userId,o=s?yield n.client.getProfileInfo(s):void 0,a=(i=n.getOpponentMember())===null||i===void 0?void 0:i.userId,c=a?yield n.client.getProfileInfo(a):void 0,l=Th(),d={replacement_id:Th(),target_user:{id:a,display_name:c?.displayname,avatar_url:c?.avatar_url},await_call:l};yield e.sendVoipEvent(Z.CallReplaces,d);var h={replacement_id:Th(),target_user:{id:s,display_name:o?.displayname,avatar_url:o?.avatar_url},create_call:l};yield n.sendVoipEvent(Z.CallReplaces,h),yield n.terminate(pr.Local,ft.Transferred,!0),yield e.terminate(pr.Local,ft.Transferred,!0)})()}terminate(e,n,r){var i=this;return B(function*(){var s;if(!i.callHasEnded()){i.hangupParty=e,i.hangupReason=n,i.state=at.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(gt.Hangup,i),i.client.callEventHandler.calls.delete(i.callId)}})()}stopAllMedia(){M.debug("Call ".concat(this.callId," stopAllMedia() running"));for(var e of this.feeds)if(e.isLocal()&&e.purpose===xn.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===xn.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else if(!e.isLocal()){M.debug("Call ".concat(this.callId," stopAllMedia() stopping stream (streamId=").concat(e.stream.id,")"));for(var n of e.stream.getTracks())n.stop()}}checkForErrorListener(){if(this.listeners(WX.Error).length===0)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}sendCandidateQueue(){var e=this;return B(function*(){if(!(e.candidateSendQueue.length===0||e.callHasEnded())){var n=e.candidateSendQueue;e.candidateSendQueue=[],++e.candidateSendTries;var r={candidates:n.map(a=>a.toJSON())};e.candidatesEnded&&r.candidates.push({candidate:""}),M.debug("Call ".concat(e.callId," sendCandidateQueue() attempting to send ").concat(n.length," candidates"));try{yield e.sendVoipEvent(Z.CallCandidates,r),e.candidateSendTries=0,e.sendCandidateQueue()}catch(a){if(a instanceof tr&&a.event&&e.client.cancelPendingEvent(a.event),e.candidateSendQueue.push(...n),e.candidateSendTries>5){M.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates on attempt ").concat(e.candidateSendTries,". Giving up on this call."),a);var i=ft.SignallingFailed,s="Signalling failed";e.emit(gt.Error,new Gl(i,s,a),e),e.hangup(i,!1);return}var o=500*Math.pow(2,e.candidateSendTries);++e.candidateSendTries,M.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates. Retrying in ").concat(o,"ms"),a),setTimeout(()=>{e.sendCandidateQueue()},o)}}})()}placeCall(e,n){var r=this;return B(function*(){if(!e)throw new Error("You CANNOT start a call without audio");r.state=at.WaitLocalMedia;var i;try{var s,o=yield r.client.getMediaHandler().getUserMediaStream(e,n);Nr(o.getAudioTracks(),!0),Nr(o.getVideoTracks(),!0),i=new iu({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:xn.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 n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:!1;r.checkForErrorListener(),r.direction=xd.Outbound,yield r.initOpponentCrypto(),r.client.callEventHandler.calls.set(r.callId,r);var s=yield r.client.checkTurnServers();s||M.warn("Call ".concat(r.callId," placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...")),r.peerConn=r.createPeerConnection(),r.emit(gt.PeerConnectionCreated,r.peerConn,r),r.gotCallFeedsForInvite(e,i)})()}createPeerConnection(){var e,n=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers.length?this.turnServers:void 0,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});n.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),n.addEventListener("signalingstatechange",this.onSignallingStateChanged),n.addEventListener("icecandidate",this.gotLocalIceCandidate),n.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),n.addEventListener("track",this.onTrack),n.addEventListener("negotiationneeded",this.onNegotiationNeeded),n.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,n),n}partyIdMatches(e){var n=e.version===0?null:e.party_id||null;return n===this.opponentPartyId}chooseOpponent(e){var n,r=e.getContent();if(M.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=(n=this.client.getRoom(this.roomId).getMember(e.getSender()))!==null&&n!==void 0?n: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 B(function*(){var n=e.remoteCandidateBuffer.get(e.opponentPartyId);n&&(M.info("Call ".concat(e.callId," addBufferedIceCandidates() adding ").concat(n.length," buffered candidates for opponent ").concat(e.opponentPartyId)),yield e.addIceCandidates(n)),e.remoteCandidateBuffer.clear()})()}addIceCandidates(e){var n=this;return B(function*(){for(var r of e){(r.sdpMid===null||r.sdpMid===void 0)&&(r.sdpMLineIndex===null||r.sdpMLineIndex===void 0)?M.debug("Call ".concat(n.callId," addIceCandidates() got remote ICE end-of-candidates")):M.debug("Call ".concat(n.callId," addIceCandidates() got remote ICE candidate (sdpMid=").concat(r.sdpMid,", candidate=").concat(r.candidate,")"));try{yield n.peerConn.addIceCandidate(r)}catch(i){n.ignoreOffer?M.debug("Call ".concat(n.callId," addIceCandidates() failed to add remote ICE candidate because ignoring offer"),i):M.info("Call ".concat(n.callId," addIceCandidates() failed to add remote ICE candidate"),i)}}})()}get hasPeerConnection(){return!!this.peerConn}initStats(e){this.stats=e,this.stats.start()}}function Nr(t,e){for(var n of t)n.enabled=e}function dA(){if(typeof window>"u"||typeof document>"u")return!1;try{var t,e,n,r=!!((t=(e=(n=window.RTCPeerConnection)!==null&&n!==void 0?n:window.RTCSessionDescription)!==null&&e!==void 0?e:window.RTCIceCandidate)!==null&&t!==void 0?t:navigator.mediaDevices);if(!r)return M.error("WebRTC is not supported in this browser / environment"),!1}catch(i){return M.error("Exception thrown when trying to access WebRTC",i),!1}return!0}function fb(t,e,n){if(!dA())return null;var r=n?n.forceTURN:!1,i={client:t,roomId:e,invitee:n?.invitee,turnServers:t.getTurnServers(),forceTURN:t.forceTURN||r,opponentDeviceId:n?.opponentDeviceId,opponentSessionId:n?.opponentSessionId,groupCallId:n?.groupCallId},s=new _1e(i);return t.reEmitter.reEmit(s,Object.values(gt)),s}var Zd=function(t){return t.DontNotify="dont_notify",t.Notify="notify",t.Coalesce="coalesce",t}({}),XO=function(t){return t.Highlight="highlight",t.Sound="sound",t}({}),S1e=function(t){return t.ExactEquals="==",t.LessThan="<",t.GreaterThan=">",t.GreaterThanOrEqual=">=",t.LessThanOrEqual="<=",t}({}),E1e="2";function w1e(t){return t==="==2"||t==="2"}var Ur=function(t){return t.EventMatch="event_match",t.EventPropertyIs="event_property_is",t.EventPropertyContains="event_property_contains",t.ContainsDisplayName="contains_display_name",t.RoomMemberCount="room_member_count",t.SenderNotificationPermission="sender_notification_permission",t.CallStarted="call_started",t.CallStartedPrefix="org.matrix.msc3914.call_started",t}({}),wi=function(t){return t.Override="override",t.ContentSpecific="content",t.RoomSpecific="room",t.SenderSpecific="sender",t.Underride="underride",t}({}),Ei=function(t){return t.Master=".m.rule.master",t.IsUserMention=".m.rule.is_user_mention",t.IsRoomMention=".m.rule.is_room_mention",t.ContainsDisplayName=".m.rule.contains_display_name",t.ContainsUserName=".m.rule.contains_user_name",t.AtRoomNotification=".m.rule.roomnotif",t.DM=".m.rule.room_one_to_one",t.EncryptedDM=".m.rule.encrypted_room_one_to_one",t.Message=".m.rule.message",t.EncryptedMessage=".m.rule.encrypted",t.InviteToSelf=".m.rule.invite_for_me",t.MemberEvent=".m.rule.member_event",t.IncomingCall=".m.rule.call",t.SuppressNotices=".m.rule.suppress_notices",t.Tombstone=".m.rule.tombstone",t.PollStart=".m.rule.poll_start",t.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",t.PollEnd=".m.rule.poll_end",t.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",t.PollStartOneToOne=".m.rule.poll_start_one_to_one",t.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",t.PollEndOneToOne=".m.rule.poll_end_one_to_one",t.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one",t}({});function N$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function U$(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?N$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):N$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var j$=[wi.Override,wi.ContentSpecific,wi.RoomSpecific,wi.SenderSpecific,wi.Underride],C1e={".m.rule.is_room_mention":{rule_id:".m.rule.is_room_mention",default:!0,enabled:!0,conditions:[{kind:Ur.EventPropertyIs,key:"content.m\\.mentions.room",value:!0},{kind:Ur.SenderNotificationPermission,key:"room"}],actions:[Zd.Notify,{set_tweak:XO.Highlight}]},".m.rule.reaction":{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:Ur.EventMatch,key:"type",pattern:"m.reaction"}],actions:[Zd.DontNotify]},".org.matrix.msc3786.rule.room.server_acl":{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:Ur.EventMatch,key:"type",pattern:Z.RoomServerAcl},{kind:Ur.EventMatch,key:"state_key",pattern:""}],actions:[]}},JO=Symbol("UserDefinedRules"),T1e=[Ei.Master,JO,Ei.SuppressNotices,Ei.InviteToSelf,Ei.MemberEvent,Ei.IsUserMention,Ei.ContainsDisplayName,Ei.IsRoomMention,Ei.AtRoomNotification,Ei.Tombstone,".m.rule.reaction",".m.rule.room.server_acl",".org.matrix.msc3786.rule.room.server_acl",".m.rule.suppress_edits"],R1e={".org.matrix.msc3914.rule.room.call":{rule_id:".org.matrix.msc3914.rule.room.call",default:!0,enabled:!0,conditions:[{kind:Ur.EventMatch,key:"type",pattern:"org.matrix.msc3401.call"},{kind:Ur.CallStarted}],actions:[Zd.Notify,{set_tweak:XO.Sound,value:"default"}]}},I1e=[JO,Ei.IncomingCall,".org.matrix.msc3914.rule.room.call",Ei.EncryptedDM,Ei.DM,Ei.Message,Ei.EncryptedMessage];function F$(t,e,n,r,i){var s=n.filter(y=>y.default),o=n.filter(y=>!y.default);function a(y){y===JO?l.push(...o):y in r?(t.warn("Adding default global ".concat(e," push rule ").concat(y)),l.push(r[y])):t.warn("Missing default global ".concat(e," push rule ").concat(y))}var c=0,l=[];for(var d of s){var h=i.indexOf(d.rule_id);if(h===-1){l.push(d);continue}for(;h>c;){var m=i[c];a(m),c+=1}l.push(d),c+=1}for(var g of i.slice(c))a(g);return l}class qa{constructor(e){this.client=e,L(this,"parsedKeys",new Map)}static actionListToActionsObject(e){var n={notify:!1,tweaks:{}};for(var r of e)r===Zd.Notify?n.notify=!0:typeof r=="object"&&(r.value===void 0&&(r.value=!0),n.tweaks[r.set_tweak]=r.value);return n}static rewriteDefaultRules(e,n){var r=JSON.parse(JSON.stringify(n));return r||(r={}),r.global||(r.global={}),r.global.override||(r.global.override=[]),r.global.underride||(r.global.underride=[]),r.global.override=F$(e,wi.Override,r.global.override,C1e,T1e),r.global.underride=F$(e,wi.Underride,r.global.underride,R1e,I1e),r}static getPushRuleGlobRegex(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"i",[i,s]=n?["(?<=^|\\W)","(?=\\W|$)"]:["^","$"],o="".concat(n,"-").concat(r,"-").concat(e);return qa.cachedGlobToRegex[o]||(qa.cachedGlobToRegex[o]=new RegExp(i+"("+HX(e)+")"+s,r)),qa.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 n=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===Ur.EventMatch&&(n.delete(s.key),this.parsedKeys.set(s.key,qa.partsForDottedKey(s.key)));n.forEach(o=>this.parsedKeys.delete(o))}matchingRuleFromKindSet(e,n){for(var r of j$){var i=n[r];if(i){for(var s of i)if(s.enabled){var o=this.templateRuleToRaw(r,s);if(o&&this.ruleMatchesEvent(o,e))return U$(U$({},s),{},{kind:r})}}}return null}templateRuleToRaw(e,n){var r={rule_id:n.rule_id,actions:n.actions,conditions:[]};switch(e){case wi.Underride:case wi.Override:r.conditions=n.conditions;break;case wi.RoomSpecific:if(!n.rule_id)return null;r.conditions.push({kind:Ur.EventMatch,key:"room_id",value:n.rule_id});break;case wi.SenderSpecific:if(!n.rule_id)return null;r.conditions.push({kind:Ur.EventMatch,key:"user_id",value:n.rule_id});break;case wi.ContentSpecific:if(!n.pattern)return null;r.conditions.push({kind:Ur.EventMatch,key:"content.body",pattern:n.pattern});break}return r}eventFulfillsCondition(e,n){switch(e.kind){case Ur.EventMatch:return this.eventFulfillsEventMatchCondition(e,n);case Ur.EventPropertyIs:return this.eventFulfillsEventPropertyIsCondition(e,n);case Ur.EventPropertyContains:return this.eventFulfillsEventPropertyContains(e,n);case Ur.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,n);case Ur.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,n);case Ur.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,n);case Ur.CallStarted:case Ur.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(e,n)}return!1}eventFulfillsSenderNotifPermCondition(e,n){var r=e.key;if(!r)return!1;var i=this.client.getRoom(n.getRoomId());return i!=null&&i.currentState?i.currentState.mayTriggerNotifOfType(r,n.getSender()):!1}eventFulfillsRoomMemberCountCondition(e,n){if(!e.is)return!1;var r=this.client.getRoom(n.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,n){var r,i=n.getContent();if(n.isEncrypted()&&n.getClearContent()&&(i=n.getClearContent()),!i||!i.body||typeof i.body!="string")return!1;var s=this.client.getRoom(n.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,c=new RegExp("(^|\\W)"+BX(a)+"(\\W|$)","i");return i.body.search(c)>-1}eventFulfillsEventMatchCondition(e,n){if(!e.key)return!1;var r=this.valueForDottedKey(e.key,n);if(typeof r!="string")return!1;if(e.value)return e.value===r;if(typeof e.pattern!="string")return!1;var i=qa.getPushRuleGlobRegex(e.pattern,e.key==="content.body");return!!r.match(i)}eventFulfillsEventPropertyIsCondition(e,n){return!e.key||e.value===void 0?!1:e.value===this.valueForDottedKey(e.key,n)}eventFulfillsEventPropertyContains(e,n){if(!e.key||e.value===void 0)return!1;var r=this.valueForDottedKey(e.key,n);return Array.isArray(r)?r.includes(e.value):!1}eventFulfillsCallStartedCondition(e,n){return["m.ring","m.prompt"].includes(n.getContent()["m.intent"])&&!("m.terminated"in n.getContent())&&(n.getPrevContent()["m.terminated"]!==n.getContent()["m.terminated"]||ff(n.getPrevContent(),{}))}static partsForDottedKey(e){var n=[],r="",i=!1;for(var s of e){if(i){s==="\\"||s==="."?r+=s:r+="\\"+s,i=!1;continue}s=="."?(n.push(r),r=""):s=="\\"?i=!0:r+=s}return i&&(r+="\\"),n.push(r),n}valueForDottedKey(e,n){var r=this.parsedKeys.get(e);r===void 0&&(r=qa.partsForDottedKey(e),this.parsedKeys.set(e,r));var i,s=r[0],o=0;for(s==="content"?(i=n.getContent(),++o):s==="type"?(i=n.getType(),++o):i=n.event;o<r.length;++o){if(VX(i))return;var a=r[o];i=i[a]}return i}matchingRuleForEventWithRulesets(e,n){return!n||e.getSender()===this.client.getSafeUserId()?null:this.matchingRuleFromKindSet(e,n.global)}pushActionsForEventAndRulesets(e,n){var r=this.matchingRuleForEventWithRulesets(e,n);if(!r)return{};var i=qa.actionListToActionsObject(r.actions);return i.tweaks.highlight===void 0&&(i.tweaks.highlight=r.kind==wi.ContentSpecific),{actions:i,rule:r}}ruleMatchesEvent(e,n){var r;return this.client.supportsIntentionalMentions()&&n.getContent()["m.mentions"]!==void 0&&(e.rule_id===Ei.ContainsUserName||e.rule_id===Ei.ContainsDisplayName||e.rule_id===Ei.AtRoomNotification)?!1:!((r=e.conditions)!==null&&r!==void 0&&r.some(i=>!this.eventFulfillsCondition(i,n)))}actionsForEvent(e){var{actions:n}=this.pushActionsForEventAndRulesets(e,this.client.pushRules);return n||{}}actionsAndRuleForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){var n,r=this.getPushRuleAndKindById(e);return(n=r?.rule)!==null&&n!==void 0?n:null}getPushRuleAndKindById(e){for(var n of["global"]){var r;if(((r=this.client.pushRules)===null||r===void 0?void 0:r[n])!==void 0){for(var i of j$)if(this.client.pushRules[n][i]!==void 0){for(var s of this.client.pushRules[n][i])if(s.rule_id===e)return{rule:s,kind:i}}}}return null}}L(qa,"cachedGlobToRegex",{});var hb=["v1.1","v1.2","v1.3","v1.4","v1.5","v1.6","v1.7","v1.8","v1.9"],k1e=hb[0],x1e=hb[hb.length-1],So=function(t){return t.SUCCESS="SUCCESS",t.IGNORE="IGNORE",t.PROMPT="PROMPT",t.FAIL_PROMPT="FAIL_PROMPT",t.FAIL_ERROR="FAIL_ERROR",t}({}),Ia=function(t){return t.Invalid="Invalid homeserver discovery response",t.GenericFailure="Failed to get autodiscovery configuration from server",t.InvalidHsBaseUrl="Invalid base_url for m.homeserver",t.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",t.InvalidIsBaseUrl="Invalid base_url for m.identity_server",t.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",t.InvalidIs="Invalid identity server discovery response",t.MissingWellknown="No .well-known JSON file found",t.InvalidJson="Invalid JSON",t.UnsupportedHomeserverSpecVersion="The homeserver does not meet the version requirements",t}({});class lt{static fromDiscoveryConfig(e){var n=this;return B(function*(){var r,i={"m.homeserver":{state:lt.FAIL_ERROR,error:lt.ERROR_INVALID,base_url:null},"m.identity_server":{state:lt.PROMPT,error:null,base_url:null}};if(!(e!=null&&e["m.homeserver"]))return M.error("No m.homeserver key in config"),i["m.homeserver"].state=lt.FAIL_PROMPT,i["m.homeserver"].error=lt.ERROR_INVALID,Promise.resolve(i);if(!e["m.homeserver"].base_url)return M.error("No m.homeserver base_url in config"),i["m.homeserver"].state=lt.FAIL_PROMPT,i["m.homeserver"].error=lt.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var s=n.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!s)return M.error("Invalid base_url for m.homeserver"),i["m.homeserver"].error=lt.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var o=yield n.fetchWellKnownObject("".concat(s,"/_matrix/client/versions"));if(!o||!Array.isArray((r=o.raw)===null||r===void 0?void 0:r.versions))return M.error("Invalid /versions response"),i["m.homeserver"].error=lt.ERROR_INVALID_HOMESERVER,i["m.homeserver"].base_url=s,Promise.resolve(i);var a=new Set(o.raw.versions),c=!1;for(var l of hb)if(a.has(l)){c=!0;break}if(!c)return M.error("Homeserver does not meet version requirements"),i["m.homeserver"].error=lt.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION,i["m.homeserver"].base_url=s,Promise.resolve(i);i["m.homeserver"]={state:lt.SUCCESS,error:null,base_url:s};var d="";if(e["m.identity_server"]){var h={"m.homeserver":i["m.homeserver"],"m.identity_server":{state:lt.FAIL_PROMPT,error:lt.ERROR_INVALID_IS,base_url:null}};if(d=n.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!d)return M.error("Invalid base_url for m.identity_server"),h["m.identity_server"].error=lt.ERROR_INVALID_IS_BASE_URL,Promise.resolve(h);var m=yield n.fetchWellKnownObject("".concat(d,"/_matrix/identity/v2"));if(!(m!=null&&m.raw)||m.action!==So.SUCCESS)return M.error("Invalid /v2 response"),h["m.identity_server"].error=lt.ERROR_INVALID_IDENTITY_SERVER,h["m.identity_server"].base_url=d,Promise.resolve(h)}return d&&d.toString().length>0&&(i["m.identity_server"]={state:lt.SUCCESS,error:null,base_url:d}),Object.keys(e).forEach(g=>{if(g==="m.homeserver"||g==="m.identity_server"){var y=["error","state","base_url"];for(var v of Object.keys(e[g]))y.includes(v)||(i[g][v]=e[g][v])}else i[g]=e[g]}),Promise.resolve(i)})()}static findClientConfig(e){var n=this;return B(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:lt.FAIL_ERROR,error:lt.ERROR_INVALID,base_url:null},"m.identity_server":{state:lt.PROMPT,error:null,base_url:null}},i=e.includes("://")?e:"https://".concat(e),s=yield n.fetchWellKnownObject("".concat(i,"/.well-known/matrix/client"));return!s||s.action!==So.SUCCESS?(M.error("No response or error when parsing .well-known"),s.reason&&M.error(s.reason),s.action===So.IGNORE?r["m.homeserver"]={state:lt.PROMPT,error:null,base_url:null}:(r["m.homeserver"].state=lt.FAIL_PROMPT,r["m.homeserver"].error=lt.ERROR_INVALID),Promise.resolve(r)):lt.fromDiscoveryConfig(s.raw)})()}static getRawClientConfig(e){var n=this;return B(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 n.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 n,r;try{r=new URL(e)}catch(a){M.error("Could not parse url",a)}if(!((n=r)!==null&&n!==void 0&&n.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 M.error(a),!1}}static fetch(e,n){return this.fetchFn?this.fetchFn(e,n):globalThis.fetch(e,n)}static setFetchFn(e){lt.fetchFn=e}static fetchWellKnownObject(e){return B(function*(){var n;try{if(n=yield lt.fetch(e,{method:de.Get,signal:J3(5e3)}),n.status===404)return{raw:{},action:So.IGNORE,reason:lt.ERROR_MISSING_WELLKNOWN};if(n.status!==200)return{raw:{},action:So.FAIL_PROMPT,reason:"General failure"}}catch(o){var r=o,i="";return typeof r=="object"&&(i=r?.message),{error:r,raw:{},action:So.FAIL_PROMPT,reason:i||"General failure"}}try{return{raw:yield n.json(),action:So.SUCCESS}}catch(o){var s=o;return{error:s,raw:{},action:So.FAIL_PROMPT,reason:s?.name==="SyntaxError"?lt.ERROR_INVALID_JSON:lt.ERROR_INVALID}}})()}}L(lt,"ERROR_INVALID",Ia.Invalid);L(lt,"ERROR_GENERIC_FAILURE",Ia.GenericFailure);L(lt,"ERROR_INVALID_HS_BASE_URL",Ia.InvalidHsBaseUrl);L(lt,"ERROR_INVALID_HOMESERVER",Ia.InvalidHomeserver);L(lt,"ERROR_INVALID_IS_BASE_URL",Ia.InvalidIsBaseUrl);L(lt,"ERROR_INVALID_IDENTITY_SERVER",Ia.InvalidIdentityServer);L(lt,"ERROR_INVALID_IS",Ia.InvalidIs);L(lt,"ERROR_MISSING_WELLKNOWN",Ia.MissingWellknown);L(lt,"ERROR_INVALID_JSON",Ia.InvalidJson);L(lt,"ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION",Ia.UnsupportedHomeserverSpecVersion);L(lt,"ALL_ERRORS",Object.keys(Ia));L(lt,"FAIL_ERROR",So.FAIL_ERROR);L(lt,"FAIL_PROMPT",So.FAIL_PROMPT);L(lt,"PROMPT",So.PROMPT);L(lt,"SUCCESS",So.SUCCESS);L(lt,"fetchFn",void 0);var fA=function(t){return t.IS="SERVICE_TYPE_IS",t.IM="SERVICE_TYPE_IM",t}({});class A1e{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 n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.paginateTokens[n?ht.Backward:ht.Forward]=e??null}addEvents(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;n?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}class tT{static fromJson(e,n){var r=e.context||{},i=(r.events_before||[]).map(n),s=(r.events_after||[]).map(n),o=new A1e(n(e.result)),a=o.ourEvent.threadRootId;return i=i.filter(c=>c.threadRootId===a),s=s.filter(c=>c.threadRootId===a),o.setPaginateToken(r.start,!0),o.addEvents(i,!0),o.addEvents(s,!1),o.setPaginateToken(r.end,!1),new tT(e.rank,o)}constructor(e,n){this.rank=e,this.context=n}}var GJ=function(t){return t.Public="public",t.Private="private",t}({}),nT=function(t){return t.PrivateChat="private_chat",t.TrustedPrivateChat="trusted_private_chat",t.PublicChat="public_chat",t}({}),ef=function(t){return t.Public="public",t.Invite="invite",t.Private="private",t.Knock="knock",t.Restricted="restricted",t}({}),P1e=function(t){return t.RoomMembership="m.room_membership",t}({}),dC=function(t){return t.CanJoin="can_join",t.Forbidden="forbidden",t}({}),QO=function(t){return t.Invited="invited",t.Joined="joined",t.Shared="shared",t.WorldReadable="world_readable",t}({});function $$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function B$(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?$$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):$$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function L1e(t,e){var n=!!e.preventReEmit,r=e.decrypt!==!1;function i(s){var o=t.getRoom(s.room_id),a;o&&s.state_key===void 0&&(a=o.findEventById(s.event_id)),!a||a.status?a=new $i(s):(a.setUnsigned(B$(B$({},a.getUnsigned()),s.unsigned)),n=!0);var c=a.getServerAggregatedRelation(vn.Replace);if(c!=null&&c.content){var l=i(c);a.makeReplaced(l)}var d=o?.findThreadForEvent(a);return d&&a.setThread(d),a.isEncrypted()&&(n||t.reEmitter.reEmit(a,[Kt.Decrypted]),r&&t.decryptEventIfNeeded(a)),n||(t.reEmitter.reEmit(a,[Kt.Replaced,Kt.VisibilityChange]),o?.reEmitter.reEmit(a,[Kt.BeforeRedaction])),a}return i}function H$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Sd(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?H$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):H$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}class V${constructor(e,n,r){this.client=e,this.indexEvent=n,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 B(function*(){yield e.client.sendStateEvent(e.roomId,ru.name,{},e.id),yield e.client.redactEvent(e.roomId,e.id);var n=(yield e.getVersionHistory())[1];n&&(yield n.delete())})()}getName(){return this.indexEvent.getContent().name||"Unnamed File"}setName(e){var n=this;return B(function*(){yield n.client.sendStateEvent(n.roomId,ru.name,Sd(Sd({},n.indexEvent.getContent()),{},{name:e}),n.id)})()}isLocked(){return this.indexEvent.getContent().locked||!1}setLocked(e){var n=this;return B(function*(){yield n.client.sendStateEvent(n.roomId,ru.name,Sd(Sd({},n.indexEvent.getContent()),{},{locked:e}),n.id)})()}getFileInfo(){var e=this;return B(function*(){var n=yield e.getFileEvent(),r=n.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 B(function*(){var n=e.client.getRoom(e.roomId);if(!n)throw new Error("Unknown room");for(var r=n.getUnfilteredTimelineSet().findEventById(e.id);!r&&n.getLiveTimeline().getState(Me.BACKWARDS).paginationToken;)yield e.client.scrollback(n,100),r=n.getUnfilteredTimelineSet().findEventById(e.id);if(!r)throw new Error("Failed to find event");return yield e.client.decryptEventIfNeeded(r),r})()}createNewVersion(e,n,r,i){var s=this;return B(function*(){var o=yield s.directory.createFile(e,n,r,Sd(Sd({},i??{}),{},{"m.new_content":!0,"m.relates_to":{rel_type:vn.Replace,event_id:s.id}}));return yield s.client.sendStateEvent(s.roomId,ru.name,{active:!0,name:e,version:s.version+1},o.event_id),yield s.client.sendStateEvent(s.roomId,ru.name,Sd(Sd({},s.indexEvent.getContent()),{},{active:!1}),s.id),o})()}getVersionHistory(){var e=this;return B(function*(){var n=[];n.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(c=>c.replacingEventId()===o.getId()),s){var a=e.directory.getFile(s.getId());if(a)n.push(a),o=s;else break}while(s);return n})()}}function q$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function ph(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?q$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):q$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var O1e={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[Z.RoomPowerLevels]:100,[Z.RoomHistoryVisibility]:100,[Z.RoomTombstone]:100,[Z.RoomEncryption]:100,[Z.RoomName]:50,[Z.RoomMessage]:50,[Z.RoomMessageEncrypted]:50,[Z.Sticker]:50},users:{}},Om=function(t){return t.Viewer="viewer",t.Editor="editor",t.Owner="owner",t}({});class G${constructor(e,n){if(this.client=e,this.roomId=n,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(Z.SpaceParent);return e!=null&&e.length?e.every(n=>{var r;return!((r=n.getContent())!==null&&r!==void 0&&r.via)}):!0}setName(e){var n=this;return B(function*(){yield n.client.sendStateEvent(n.roomId,Z.RoomName,{name:e},"")})()}invite(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:!0,s=[r.retryInvite(e)];i&&s.push(...r.getDirectories().map(o=>o.invite(e,i))),yield Promise.all(s)})()}retryInvite(e){var n=this;return B(function*(){yield vve(()=>n.client.invite(n.roomId,e),r=>!(r instanceof tr&&r.errcode==="M_FORBIDDEN"))})()}setPermissions(e,n){var r=this;return B(function*(){var i,s=r.room.currentState.getStateEvents(Z.RoomPowerLevels,"");if(Array.isArray(s))throw new Error("Unexpected return type for power levels");var o=s?.getContent()||{},a=o.users_default||0,c=o.events_default||50,l=((i=o.events)===null||i===void 0?void 0:i[Z.RoomPowerLevels])||100,d=o.users||{};switch(n){case Om.Viewer:d[e]=a;break;case Om.Editor:d[e]=c;break;case Om.Owner:d[e]=l;break;default:throw new Error("Invalid role: "+n)}o.users=d,yield r.client.sendStateEvent(r.roomId,Z.RoomPowerLevels,o,"")})()}getPermissions(e){var n,r,i=this.room.currentState.getStateEvents(Z.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");var s=i?.getContent()||{},o=s.users_default||0,a=s.events_default||50,c=((n=s.events)===null||n===void 0?void 0:n[Z.RoomPowerLevels])||100,l=((r=s.users)===null||r===void 0?void 0:r[e])||o;return l>=c?Om.Owner:l>=a?Om.Editor:Om.Viewer}createDirectory(e){var n=this;return B(function*(){var r=yield n.client.unstableCreateFileTree(e);return yield n.client.sendStateEvent(n.roomId,Z.SpaceChild,{via:[n.client.getDomain()]},r.roomId),yield n.client.sendStateEvent(r.roomId,Z.SpaceParent,{via:[n.client.getDomain()]},n.roomId),r})()}getDirectories(){var e=[],n=this.room.currentState.getStateEvents(Z.SpaceChild);for(var r of n)try{var i=r.getStateKey();if(i){var s=this.client.unstableGetFileTreeSpace(i);s&&e.push(s)}}catch(o){M.warn("Unable to create tree space instance for listing. Are we joined?",o)}return e}getDirectory(e){return this.getDirectories().find(n=>n.roomId===e)}delete(){var e=this;return B(function*(){var n=e.getDirectories();for(var r of n)yield r.delete();var i=[Be.Invite,Be.Knock,Be.Join],s=e.room.currentState.getStateEvents(Z.RoomMember);for(var o of s){var a=o.getStateKey()!==e.client.getUserId();if(a&&i.includes(o.getContent().membership)){var c=o.getStateKey();if(!c)throw new Error("State key not found for branch");yield e.client.kick(e.roomId,c,"Room deleted")}}yield e.client.leave(e.roomId)})()}getOrderedChildren(e){var n=e.map(r=>({roomId:r.getStateKey(),order:r.getContent().order})).filter(r=>r.roomId);return n.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,c,l=this.client.getRoom(r.roomId),d=this.client.getRoom(i.roomId);if(!l||!d)return qE(r.roomId,i.roomId);var h=(s=(o=l.currentState.getStateEvents(Z.RoomCreate,""))===null||o===void 0?void 0:o.getTs())!==null&&s!==void 0?s:0,m=(a=(c=d.currentState.getStateEvents(Z.RoomCreate,""))===null||c===void 0?void 0:c.getTs())!==null&&a!==void 0?a:0;return h===m?qE(r.roomId,i.roomId):h-m}else return qE(r.order,i.order)}),n}getParentRoom(){var e=this.room.currentState.getStateEvents(Z.SpaceParent),n=e[0];if(!n)throw new Error("Expected to have a parent in a non-top level space");var r=n.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(),n=e.currentState.getStateEvents(Z.SpaceChild),r=this.getOrderedChildren(n);return r.findIndex(i=>i.roomId===this.roomId)}setOrder(e){var n=this;return B(function*(){var r;if(n.isTopLevel)throw new Error("Cannot set order of top level spaces currently");var i=n.getParentRoom(),s=i.currentState.getStateEvents(Z.SpaceChild),o=n.getOrderedChildren(s);e=Math.max(Math.min(e,o.length-1),0);var a=n.getOrder(),c=a<e;c&&e===o.length-1?e--:!c&&e===0&&e++;var l=o[c?e:e-1],d=o[c?e+1:e],h=hf[0],m=!1;if(!l)d!=null&&d.order&&(h=LF(d.order));else if(e===o.length-1)d!=null&&d.order&&(h=h1(d.order));else{var g=l?.order,y=d?.order;g&&y?g===y?h=h1(g):h=yve(g,y):g?h=h1(g):y?h=LF(y):m=!0}if(m){for(var v,w=0;w<=e;w++){var S=o[w];if(w===0&&(v=S.order),S.order)v=S.order;else{var R;v=v?h1(v):hf[0];var x=i.currentState.getStateEvents(Z.SpaceChild,S.roomId),T=(R=x?.getContent())!==null&&R!==void 0?R:{via:[n.client.getDomain()]};yield n.client.sendStateEvent(i.roomId,Z.SpaceChild,ph(ph({},T),{},{order:v}),S.roomId)}}v&&(h=h1(v))}var I=i.currentState.getStateEvents(Z.SpaceChild,n.roomId),k=(r=I?.getContent())!==null&&r!==void 0?r:{via:[n.client.getDomain()]};yield n.client.sendStateEvent(i.roomId,Z.SpaceChild,ph(ph({},k),{},{order:h}),n.roomId)})()}createFile(e,n,r,i){var s=this;return B(function*(){var{content_uri:o}=yield s.client.uploadContent(n,{includeFilename:!1});r.url=o;var a={msgtype:ll.File,body:e,url:o,file:r};i=i??{},i["m.new_content"]&&(i["m.new_content"]=a);var c=yield s.client.sendMessage(s.roomId,ph(ph(ph({},i),a),{},{[YX.name]:{}}));return yield s.client.sendStateEvent(s.roomId,ru.name,{active:!0,name:e},c.event_id),c})()}getFile(e){var n=this.room.currentState.getStateEvents(ru.name,e);return n?new V$(this.client,n,this):null}listFiles(){return this.listAllFiles().filter(e=>e.isActive)}listAllFiles(){var e,n=(e=this.room.currentState.getStateEvents(ru.name))!==null&&e!==void 0?e:[];return n.map(r=>new V$(this.client,r,this))}}var KJ=function(t){return t.Recent="recent",t.Rank="rank",t}({}),Rh=function(t){return t.LocalStreamsChanged="local_streams_changed",t}({});class M1e extends On{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,n){this.audioInput=e,this.videoInput=n}setAudioInput(e){var n=this;return B(function*(){M.info("MediaHandler setAudioInput() running (deviceId=".concat(e,")")),n.audioInput!==e&&(n.audioInput=e,yield n.updateLocalUsermediaStreams())})()}setAudioSettings(e){var n=this;return B(function*(){M.info("MediaHandler setAudioSettings() running (opts=".concat(JSON.stringify(e),")")),n.audioSettings=Object.assign({},e),yield n.updateLocalUsermediaStreams()})()}setVideoInput(e){var n=this;return B(function*(){M.info("MediaHandler setVideoInput() running (deviceId=".concat(e,")")),n.videoInput!==e&&(n.videoInput=e,yield n.updateLocalUsermediaStreams())})()}setMediaInputs(e,n){var r=this;return B(function*(){M.log("MediaHandler setMediaInputs() running (audioInput: ".concat(e," videoInput: ").concat(n,")")),r.audioInput=e,r.videoInput=n,yield r.updateLocalUsermediaStreams()})()}updateLocalUsermediaStreams(){var e=this;return B(function*(){if(e.userMediaStreams.length!==0){var n=new Map;for(var r of e.client.callEventHandler.calls.values())n.set(r.callId,{audio:r.hasLocalUserMediaAudioTrack,video:r.hasLocalUserMediaVideoTrack});for(var i of e.userMediaStreams){M.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()||!n.has(o.callId))){var{audio:a,video:c}=n.get(o.callId);M.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=".concat(o.callId,")"));var l=yield e.getUserMediaStream(a,c);o.callHasEnded()||(yield o.updateLocalUsermediaStream(l))}for(var d of e.client.groupCallEventHandler.groupCalls.values())if(d.localCallFeed){M.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=".concat(d.groupCallId,")"));var h=yield e.getUserMediaStream(!0,d.type===eT.Video);d.state!==sr.Ended&&(yield d.updateLocalUsermediaStream(h))}e.emit(Rh.LocalStreamsChanged)}})()}hasAudioDevice(){return B(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(n=>n.kind==="audioinput").length>0}catch(n){return M.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",n),!1}})()}hasVideoDevice(){return B(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(n=>n.kind==="videoinput").length>0}catch(n){return M.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",n),!1}})()}getUserMediaStream(e,n){var r=arguments,i=this;return B(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:!0;return i.getMediaStreamPromise?i.getMediaStreamPromise=i.getMediaStreamPromise.then(()=>i.getUserMediaStreamInternal(e,n,s)):i.getMediaStreamPromise=i.getUserMediaStreamInternal(e,n,s),i.getMediaStreamPromise})()}getUserMediaStreamInternal(e,n,r){var i=this;return B(function*(){var s=e&&(yield i.hasAudioDevice()),o=n&&(yield i.hasVideoDevice()),a,c=!0;if(i.localUserMediaStream){var l,d;s!==i.localUserMediaStream.getAudioTracks().length>0&&(c=!1),o!==i.localUserMediaStream.getVideoTracks().length>0&&(c=!1),s&&((l=i.localUserMediaStream.getAudioTracks()[0])===null||l===void 0||(l=l.getSettings())===null||l===void 0?void 0:l.deviceId)!==i.audioInput&&(c=!1),o&&((d=i.localUserMediaStream.getVideoTracks()[0])===null||d===void 0||(d=d.getSettings())===null||d===void 0?void 0:d.deviceId)!==i.videoInput&&(c=!1)}else c=!1;if(c){var y;if(a=i.localUserMediaStream.clone(),M.log("MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=".concat((y=i.localUserMediaStream)===null||y===void 0?void 0:y.id," newStreamId=").concat(a.id," shouldRequestAudio=").concat(s," shouldRequestVideo=").concat(o,")")),!s)for(var v of a.getAudioTracks())a.removeTrack(v);if(!o)for(var w of a.getVideoTracks())a.removeTrack(w)}else{var h=i.getUserMediaContraints(s,o);a=yield navigator.mediaDevices.getUserMedia(h),M.log("MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=".concat(a.id,", shouldRequestAudio=").concat(s,", shouldRequestVideo=").concat(o,", constraints=").concat(JSON.stringify(h),")"));for(var m of a.getTracks()){var g=m.getSettings();m.kind==="audio"?i.audioInput=g.deviceId:m.kind==="video"&&(i.videoInput=g.deviceId)}r&&(i.localUserMediaStream=a)}return r&&i.userMediaStreams.push(a),i.emit(Rh.LocalStreamsChanged),a})()}stopUserMediaStream(e){M.log("MediaHandler stopUserMediaStream() stopping (streamId=".concat(e.id,")"));for(var n of e.getTracks())n.stop();var r=this.userMediaStreams.indexOf(e);if(r!==-1&&(M.debug("MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=".concat(e.id,")"),e.id),this.userMediaStreams.splice(r,1)),this.emit(Rh.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,n=this;return B(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(n.screensharingStreams.length===0){var o=n.getScreenshareContraints(r);r.desktopCapturerSourceId?(M.debug("MediaHandler getScreensharingStream() calling getUserMedia() (opts=".concat(JSON.stringify(r),")")),s=yield navigator.mediaDevices.getUserMedia(o)):(M.debug("MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=".concat(JSON.stringify(r),")")),s=yield navigator.mediaDevices.getDisplayMedia(o))}else{var a=n.screensharingStreams[n.screensharingStreams.length-1];M.log("MediaHandler getScreensharingStream() cloning (streamId=".concat(a.id,")")),s=a.clone()}return i&&n.screensharingStreams.push(s),n.emit(Rh.LocalStreamsChanged),s})()}stopScreensharingStream(e){M.debug("MediaHandler stopScreensharingStream() stopping stream (streamId=".concat(e.id,")"));for(var n of e.getTracks())n.stop();var r=this.screensharingStreams.indexOf(e);r!==-1&&(M.debug("MediaHandler stopScreensharingStream() splicing stream out (streamId=".concat(e.id,")")),this.screensharingStreams.splice(r,1)),this.emit(Rh.LocalStreamsChanged)}stopAllStreams(){for(var e of this.userMediaStreams){M.log("MediaHandler stopAllStreams() stopping (streamId=".concat(e.id,")"));for(var n of e.getTracks())n.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(Rh.LocalStreamsChanged)}getUserMediaContraints(e,n){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:n?{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:n,audio:r}=e;return n?{audio:r??!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n}}}:{audio:r??!1,video:!0}}}var K$=function(t){return t.RequestFinished="FINISHED",t.Complete="COMPLETE",t}({}),h_=function(t){return t.PreProcess="ExtState.PreProcess",t.PostProcess="ExtState.PostProcess",t}({}),hA=function(t){return t.RoomData="SlidingSync.RoomData",t.Lifecycle="SlidingSync.Lifecycle",t}({}),D1e=3;class N1e{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return h_.PreProcess}onRequest(e){var n=this;return B(function*(){return e&&(M.log("ExtensionE2EE: invalidating all device lists due to missing 'pos'"),yield n.crypto.markAllTrackedUsersAsDirty()),{enabled:!0}})()}onResponse(e){var n=this;return B(function*(){e.device_lists&&(yield n.crypto.processDeviceLists(e.device_lists)),yield n.crypto.processKeyCounts(e.device_one_time_keys_count,e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]),n.crypto.onSyncCompleted({})})()}}class U1e{constructor(e,n){this.client=e,this.cryptoCallbacks=n,L(this,"nextBatch",null)}name(){return"to_device"}when(){return h_.PreProcess}onRequest(e){var n=this;return B(function*(){return{since:n.nextBatch!==null?n.nextBatch:void 0,limit:100,enabled:!0}})()}onResponse(e){var n=this;return B(function*(){var r=e.events||[],i;n.cryptoCallbacks?i=yield n.cryptoCallbacks.preprocessToDeviceMessages(r):i=r.map(s=>({message:s,encryptionInfo:null})),FJ(i,n.client),n.nextBatch=e.next_batch})()}}class j1e{constructor(e){this.client=e}name(){return"account_data"}when(){return h_.PostProcess}onRequest(e){return B(function*(){return{enabled:!0}})()}onResponse(e){var n=this;return B(function*(){e.global&&e.global.length>0&&n.processGlobalAccountData(e.global);for(var r in e.rooms){var i=Tg(n.client,r,e.rooms[r]),s=n.client.getRoom(r);if(!s){M.warn("got account data for room but room doesn't exist on client:",r);continue}s.addAccountData(i),i.forEach(o=>{n.client.emit(Le.Event,o)})}})()}processGlobalAccountData(e){var n=Tg(this.client,void 0,e),r=n.reduce((i,s)=>(i[s.getType()]=this.client.store.getAccountData(s.getType()),i),{});this.client.store.storeAccountDataEvents(n),n.forEach(i=>{if(i.getType()===Z.PushRules){var s=i.getContent();this.client.setPushRules(s)}var o=r[i.getType()];return this.client.emit(Le.AccountData,i,o),i})}}class F1e{constructor(e){this.client=e}name(){return"typing"}when(){return h_.PostProcess}onRequest(e){return B(function*(){return{enabled:!0}})()}onResponse(e){var n=this;return B(function*(){if(e!=null&&e.rooms)for(var r in e.rooms)WJ(n.client,r,[e.rooms[r]])})()}}class $1e{constructor(e){this.client=e}name(){return"receipts"}when(){return h_.PostProcess}onRequest(e){return B(function*(){return{enabled:!0}})()}onResponse(e){var n=this;return B(function*(){if(e!=null&&e.rooms)for(var r in e.rooms)WJ(n.client,r,[e.rooms[r]])})()}}class zJ{constructor(e,n,r,i){this.slidingSync=e,this.client=n,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=NJ(r),this.syncOpts=UJ(i),n.getNotifTimelineSet()&&n.reEmitter.reEmit(n.getNotifTimelineSet(),[ke.Timeline,ke.TimelineReset]),this.slidingSync.on(hA.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(hA.RoomData,this.onRoomData.bind(this));var s=[new U1e(this.client,this.syncOpts.cryptoCallbacks),new j1e(this.client),new F1e(this.client),new $1e(this.client)];this.syncOpts.cryptoCallbacks&&s.push(new N1e(this.syncOpts.cryptoCallbacks)),s.forEach(o=>{this.slidingSync.registerExtension(o)})}onRoomData(e,n){var r=this;return B(function*(){var i=r.client.store.getRoom(e);if(!i){if(!n.initial){r.syncOpts.logger.debug("initial flag not set but no stored room exists for room ",e,n);return}i=jJ(r.client,e,r.opts)}yield r.processRoomData(r.client,i,n)})()}onLifecycle(e,n,r){switch(r&&this.syncOpts.logger.debug("onLifecycle",e,r),e){case K$.Complete:if(this.purgeNotifications(),!n)break;this.lastPos||this.updateSyncState(Gt.Prepared,{oldSyncToken:void 0,nextSyncToken:n.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(Gt.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:n.pos,catchingUp:!1,fromCache:!1}),this.lastPos=n.pos;break;case K$.RequestFinished:if(r){if(this.failCount+=1,this.updateSyncState(this.failCount>D1e?Gt.Error:Gt.Reconnecting,{error:new tr(r)}),this.shouldAbortSync(new tr(r)))return}else this.failCount=0,this.syncOpts.logger.debug("SlidingSyncState.RequestFinished with ".concat(Object.keys(n?.rooms||[]).length," rooms"));break}}syncLeftRooms(){return B(function*(){return[]})()}peek(e){return B(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:n}=this.client,r=new Q3(e,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:n});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,[pt.Events,pt.Members,pt.NewMember,pt.Update]),e.currentState.on(pt.NewMember,(n,r,i)=>{var s;i.user=(s=this.client.getUser(i.userId))!==null&&s!==void 0?s:void 0,this.client.reEmitter.reEmit(i,[Vs.Name,Vs.Typing,Vs.PowerLevel,Vs.Membership])})}shouldAbortSync(e){return e.errcode==="M_UNKNOWN_TOKEN"?(this.syncOpts.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(Gt.Error,{error:e}),!0):!1}processRoomData(e,n,r){var i=this;return B(function*(){r=B1e(e,n.roomId,r);var s=Tg(i.client,n.roomId,r.required_state),o=Tg(i.client,n.roomId,r.timeline,!1),a=[];if(r.limited||r.initial){var c=new Set;n.getLiveTimeline().getEvents().forEach(R=>{c.add(R.getId())});for(var l=[],d=[],h=!1,m=o.length-1;m>=0;m--){var g=o[m];if(c.has(g.getId())){h=!0;continue}h?l.push(g):d.unshift(g)}o=d,l.length>0&&n.addEventsToTimeline(l,!0,!1,n.getLiveTimeline(),r.prev_batch)}var y=n.hasEncryptionStateEvent();if(r.notification_count!=null&&n.setUnreadNotificationCount(Jt.Total,r.notification_count),r.highlight_count!=null&&(!y||y&&n.getUnreadNotificationCount(Jt.Highlight)<=0)&&n.setUnreadNotificationCount(Jt.Highlight,r.highlight_count),r.bump_stamp&&n.setBumpStamp(r.bump_stamp),Number.isInteger(r.invited_count)&&n.currentState.setInvitedMemberCount(r.invited_count),Number.isInteger(r.joined_count)&&n.currentState.setJoinedMemberCount(r.joined_count),r.invite_state){var v=Tg(i.client,n.roomId,r.invite_state);yield i.injectRoomEvents(n,v),r.initial&&(n.recalculate(),i.client.store.storeRoom(n),i.client.emit(Le.Room,n)),v.forEach(R=>{i.client.emit(Le.Event,R)});return}if(r.limited){var w;n.getLiveTimeline().setPaginationToken((w=r.prev_batch)!==null&&w!==void 0?w:null,Me.BACKWARDS)}yield i.injectRoomEvents(n,s,o,r.num_live),n.addEphemeralEvents(a),n.updateMyMembership(Be.Join),n.setMSC4186SummaryData(r.heroes,r.joined_count,r.invited_count),n.recalculate(),r.initial&&(e.store.storeRoom(n),e.emit(Le.Room,n)),i.addNotifications(o);var S=function(){var R=B(function*(x){e.emit(Le.Event,x),x.isState()&&x.getType()==Z.RoomEncryption&&i.syncOpts.cryptoCallbacks&&(yield i.syncOpts.cryptoCallbacks.onCryptoEvent(n,x))});return function(T){return R.apply(this,arguments)}}();yield og(s,S),yield og(o,S),a.forEach(function(R){e.emit(Le.Event,R)}),n.decryptCriticalEvents()})()}injectRoomEvents(e,n){var r=arguments,i=this;return B(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(),c=a.getEvents().length==0;if(c){for(var l of n)i.client.getPushActionsForEvent(l);a.initialiseState(n)}c||(e.oldState.setStateEvents(n),e.currentState.setStateEvents(n));var d=[];o>0&&(d=s.slice(-1*o),s=s.slice(0,-1*d.length)),yield e.addLiveEvents(s,{fromCache:!0,addToState:!1}),d.length>0&&(yield e.addLiveEvents(d,{fromCache:!1,addToState:!1})),e.recalculate(),i.resolveInvites(e)})()}resolveInvites(e){if(!(!e||!this.opts.resolveInvitesToProfiles)){var n=this.client;e.getMembersWithMembership(Be.Invite).forEach(function(r){if(!r.requestedProfileInfo){r.requestedProfileInfo=!0;var i=n.getUser(r.userId),s;i?s=Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):s=n.getProfileInfo(r.userId),s.then(function(o){var a=r.events.member;a.getContent().membership===Be.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 B(function*(){for(e.syncOpts.logger.debug("Sliding sync init loop");!e.client.isGuest();)try{e.syncOpts.logger.debug("Getting push rules...");var n=yield e.client.getPushRules();e.syncOpts.logger.debug("Got push rules"),e.client.pushRules=n;break}catch(r){if(e.syncOpts.logger.error("Getting push rules failed",r),e.shouldAbortSync(r))return}yield e.slidingSync.start()})()}stop(){this.syncOpts.logger.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,n){var r=this.syncState;this.syncState=e,this.syncStateData=n,this.client.emit(Le.Sync,this.syncState,r,n)}addNotifications(e){if(this.client.getNotifTimelineSet())for(var n of e){var r=this.client.getPushActionsForEvent(n);r&&r.notify&&r.tweaks&&r.tweaks.highlight&&this.notifEvents.push(n)}}purgeNotifications(){this.notifEvents.sort(function(e,n){return e.getTs()-n.getTs()}),this.notifEvents.forEach(e=>{var n;(n=this.client.getNotifTimelineSet())===null||n===void 0||n.addLiveEvent(e,{addToState:!1})}),this.notifEvents=[]}}function B1e(t,e,n){if(!n.name)return n;for(var r of n.required_state)if(r.type===Z.RoomName&&r.state_key==="")return r.content={name:n.name},n;return n.required_state.push({event_id:"$fake-sliding-sync-name-event-"+e,state_key:"",type:Z.RoomName,content:{name:n.name},sender:t.getUserId(),origin_server_ts:new Date().getTime()}),n}function Tg(t,e,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=t.getEventMapper({decrypt:r});return n.map(function(s){return s.room_id=e,i(s)})}function WJ(t,e,n){var r=Tg(t,e,n),i=t.getRoom(e);if(!i){M.warn("got ephemeral events for room but room doesn't exist on client:",e);return}i.addEphemeralEvents(r),r.forEach(s=>{t.emit(Le.Event,s)})}var ZO=new Ar("m.beacon_info","org.matrix.msc3672.beacon_info"),pA=new Ar("m.beacon","org.matrix.msc3672.beacon");class rv{static RETRY_BACKOFF_RATELIMIT(e,n,r){return GO(r,n,!1)}static QUEUE_MESSAGES(e){return e.getType()===Z.RoomMessage||e.hasAssociation()?"message":null}constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:rv.RETRY_BACKOFF_RATELIMIT,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:rv.QUEUE_MESSAGES;this.retryAlgorithm=e,this.queueAlgorithm=n,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.resolvers.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?(M.info("Queue '%s' giving up on event %s",r,i.event.getId()),this.clearQueue(r,s)):setTimeout(this.processQueue,o,r)})})}getQueueForEvent(e){var n=this.queueAlgorithm(e);return!n||!this.queues[n]?null:this.queues[n].map(function(r){return r.event})}removeEventFromQueue(e){var n=this.queueAlgorithm(e);if(!n||!this.queues[n])return!1;var r=!1;return tC(this.queues[n],i=>i.event.getId()===e.getId()?(r=!0,!0):!1),r}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){var n=this.queueAlgorithm(e);if(!n)return null;this.queues[n]||(this.queues[n]=[]);var r=Promise.withResolvers();return this.queues[n].push({event:e,resolvers: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 n=this.activeQueues.indexOf(e);n>=0&&this.activeQueues.splice(n,1),M.info("Stopping queue '%s' as it is now empty",e)}clearQueue(e,n){M.info("clearing queue '%s'",e);for(var r;r=this.removeNextEvent(e);)r.resolvers.reject(n);this.disableQueue(e)}peekNextEvent(e){var n=this.queues[e];if(Array.isArray(n))return n[0]}removeNextEvent(e){var n=this.queues[e];if(Array.isArray(n))return n.shift()}}var z$=20;class H1e{constructor(e,n){var r=this;this.client=e,this.logger=n,L(this,"sending",!1),L(this,"running",!0),L(this,"retryTimeout",null),L(this,"retryAttempts",0),L(this,"sendQueue",B(function*(){if(r.retryTimeout!==null&&clearTimeout(r.retryTimeout),r.retryTimeout=null,!(r.sending||!r.running)){r.logger.debug("Attempting to send queued to-device messages"),r.sending=!0;var i;try{for(;r.running&&(i=yield r.client.store.getOldestToDeviceBatch(),i!==null);)yield r.sendBatch(i),yield r.client.store.removeToDeviceBatch(i.id),r.retryAttempts=0;if(!r.running)return;r.logger.debug("All queued to-device messages sent")}catch(o){++r.retryAttempts;var s=rv.RETRY_BACKOFF_RATELIMIT(null,r.retryAttempts,o);if(s===-1){Math.floor(o.httpStatus/100)===4?(r.logger.error("Fatal error when sending to-device message - dropping to-device batch!",o),yield r.client.store.removeToDeviceBatch(i.id)):r.logger.info("Automatic retry limit reached for to-device messages.");return}r.logger.info("Failed to send batch of to-device messages. Will retry in ".concat(s,"ms"),o),r.retryTimeout=setTimeout(r.sendQueue,s)}finally{r.sending=!1}}})),L(this,"onResumedSync",(i,s)=>{i===Gt.Syncing&&s!==Gt.Syncing&&(this.logger.info("Resuming queue after resumed sync"),this.sendQueue())})}start(){this.running=!0,this.sendQueue(),this.client.on(Le.Sync,this.onResumedSync)}stop(){this.running=!1,this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.client.removeListener(Le.Sync,this.onResumedSync)}queueBatch(e){var n=this;return B(function*(){for(var r=[],i=0;i<e.batch.length;i+=z$){var s={eventType:e.eventType,batch:e.batch.slice(i,i+z$),txnId:n.client.makeTxnId()};r.push(s);var o=s.batch.map(a=>"".concat(a.userId,"/").concat(a.deviceId," (msgid ").concat(a.payload[X3],")"));n.logger.info("Enqueuing batch of to-device messages. type=".concat(e.eventType," txnid=").concat(s.txnId),o)}yield n.client.store.saveToDeviceBatches(r),n.sendQueue()})()}sendBatch(e){var n=this;return B(function*(){var r=new vu(()=>new Map);for(var i of e.batch)r.getOrCreate(i.userId).set(i.deviceId,i.payload);n.logger.info("Sending batch of ".concat(e.batch.length," to-device messages with ID ").concat(e.id," and txnId ").concat(e.txnId)),yield n.client.sendToDevice(e.eventType,r,e.txnId)})()}}var Lk=new to.UnstableValue("m.policies","org.matrix.msc3847.policies"),A2=new to.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites"),W$=function(t){return t.Ban="m.ban",t}({}),Rg=function(t){return t.User="m.policy.user",t.Room="m.policy.room",t.Server="m.policy.server",t}({}),Y$={[Rg.User]:Z.PolicyRuleUser,[Rg.Room]:Z.PolicyRuleRoom,[Rg.Server]:Z.PolicyRuleServer};class V1e{constructor(e){this.client=e}addRule(e,n,r){var i=this;return B(function*(){var s=yield i.getOrCreateTargetRoom(),o=yield i.client.sendStateEvent(s.roomId,Y$[e],{entity:n,reason:r,recommendation:W$.Ban});return o.event_id})()}removeRule(e){var n=this;return B(function*(){yield n.client.redactEvent(e.getRoomId(),e.getId())})()}addSource(e){var n=this;return B(function*(){yield n.client.joinRoom(e);var r=(yield n.getOrCreateSourceRooms()).map(i=>i.roomId);return r.includes(e)?!1:(r.push(e),yield n.withIgnoreInvitesPolicies(i=>{i.sources=r}),!0)})()}getRuleForInvite(e){var n=this;return B(function*(){var{sender:r,roomId:i}=e,s=yield n.getOrCreateSourceRooms(),o=r.split(":")[1],a=i.split(":")[1];for(var c of s){var l=c.getUnfilteredTimelineSet().getLiveTimeline().getState(Me.FORWARDS);for(var{scope:d,entities:h}of[{scope:Rg.Room,entities:[i]},{scope:Rg.User,entities:[r]},{scope:Rg.Server,entities:[o,a]}]){var m=l.getStateEvents(Y$[d]);for(var g of m){var y=g.getContent();if(y?.recommendation==W$.Ban){var v=y?.entity;if(v){var w=void 0;try{w=new RegExp(HX(v))}catch{continue}for(var S of h)if(S&&w.test(S))return g}}}}}return null})()}getOrCreateTargetRoom(){var e=this;return B(function*(){var n=e.getIgnoreInvitesPolicies(),r=n.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:nT.PrivateChat})).room_id,yield e.withIgnoreInvitesPolicies(s=>{s.target=r}),e.client.getRoom(r)})()}getOrCreateSourceRooms(){var e=this;return B(function*(){var n=e.getIgnoreInvitesPolicies(),r=n.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 n=this;return B(function*(){var{policies:r,ignoreInvitesPolicies:i}=n.getPoliciesAndIgnoreInvitesPolicies();e(i),r[A2.name]=i,yield n.client.setAccountData(Lk.name,r)})()}getPoliciesAndIgnoreInvitesPolicies(){var e={};for(var n of[Lk.name,Lk.altName]){var r;if(n){var i=(r=this.client.getAccountData(n))===null||r===void 0?void 0:r.getContent();if(i){e=i;break}}}var s={},o=!1;for(var a of[A2.name,A2.altName])if(a){var c=e[a];if(c&&typeof c=="object"){s=c,o=!0;break}}return o||(e[A2.name]=s),{policies:e,ignoreInvitesPolicies:s}}}var Ok="matrix-js-sdk";function q1e(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const d=t.charAt(l),h=d.charCodeAt(0);if(e[h]!==255)throw new TypeError(d+" is ambiguous");e[h]=l}const n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let d=0,h=0,m=0;const g=l.length;for(;m!==g&&l[m]===0;)m++,d++;const y=(g-m)*s+1>>>0,v=new Uint8Array(y);for(;m!==g;){let R=l[m],x=0;for(let T=y-1;(R!==0||x<h)&&T!==-1;T--,x++)R+=256*v[T]>>>0,v[T]=R%n>>>0,R=R/n>>>0;if(R!==0)throw new Error("Non-zero carry");h=x,m++}let w=y-h;for(;w!==y&&v[w]===0;)w++;let S=r.repeat(d);for(;w<y;++w)S+=t.charAt(v[w]);return S}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let d=0,h=0,m=0;for(;l[d]===r;)h++,d++;const g=(l.length-d)*i+1>>>0,y=new Uint8Array(g);for(;d<l.length;){const R=l.charCodeAt(d);if(R>255)return;let x=e[R];if(x===255)return;let T=0;for(let I=g-1;(x!==0||T<m)&&I!==-1;I--,T++)x+=n*y[I]>>>0,y[I]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=T,d++}let v=g-m;for(;v!==g&&y[v]===0;)v++;const w=new Uint8Array(h+(g-v));let S=h;for(;v!==g;)w[S++]=y[v++];return w}function c(l){const d=a(l);if(d)return d;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var G1e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const kat=q1e(G1e);var gi=function(t){return t.UserTrustStatusChanged="userTrustStatusChanged",t.KeyBackupStatus="crypto.keyBackupStatus",t.KeyBackupFailed="crypto.keyBackupFailed",t.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",t.KeyBackupDecryptionKeyCached="crypto.keyBackupDecryptionKeyCached",t.VerificationRequestReceived="crypto.verificationRequestReceived",t.WillUpdateDevices="crypto.willUpdateDevices",t.DevicesUpdated="crypto.devicesUpdated",t.KeysChanged="crossSigning.keysChanged",t.LegacyCryptoStoreMigrationProgress="crypto.legacyCryptoStoreMigrationProgress",t.DehydratedDeviceCreated="dehydration.DehydratedDeviceCreated",t.DehydratedDeviceUploaded="dehydration.DehydratedDeviceUploaded",t.RehydrationStarted="dehydration.RehydrationStarted",t.RehydrationProgress="dehydration.RehydrationProgress",t.RehydrationCompleted="dehydration.RehydrationCompleted",t.RehydrationError="dehydration.RehydrationError",t.DehydrationKeyCached="dehydration.DehydrationKeyCached",t.DehydratedDeviceRotationError="dehydration.DehydratedDeviceRotationError",t}({}),K1e=function(t){return t.MEGOLM_UNKNOWN_INBOUND_SESSION_ID="MEGOLM_UNKNOWN_INBOUND_SESSION_ID",t.MEGOLM_KEY_WITHHELD="MEGOLM_KEY_WITHHELD",t.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE="MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE",t.OLM_UNKNOWN_MESSAGE_INDEX="OLM_UNKNOWN_MESSAGE_INDEX",t.HISTORICAL_MESSAGE_NO_KEY_BACKUP="HISTORICAL_MESSAGE_NO_KEY_BACKUP",t.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED="HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED",t.HISTORICAL_MESSAGE_WORKING_BACKUP="HISTORICAL_MESSAGE_WORKING_BACKUP",t.HISTORICAL_MESSAGE_USER_NOT_JOINED="HISTORICAL_MESSAGE_USER_NOT_JOINED",t.SENDER_IDENTITY_PREVIOUSLY_VERIFIED="SENDER_IDENTITY_PREVIOUSLY_VERIFIED",t.UNSIGNED_SENDER_DEVICE="UNSIGNED_SENDER_DEVICE",t.UNKNOWN_SENDER_DEVICE="UNKNOWN_SENDER_DEVICE",t.UNKNOWN_ERROR="UNKNOWN_ERROR",t}({}),z1e=function(t){return t[t.AllDevicesIsolationMode=0]="AllDevicesIsolationMode",t[t.OnlySignedDevicesIsolationMode=1]="OnlySignedDevicesIsolationMode",t}({});class xat{constructor(e){this.errorOnVerifiedUserProblems=e,L(this,"kind",z1e.AllDevicesIsolationMode)}}class Aat{constructor(e,n,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;this.crossSigningVerified=e,this.crossSigningVerifiedBefore=n,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 Pat{constructor(e){var n,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=(n=e.signedByOwner)!==null&&n!==void 0?n:!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 Lat=function(t){return t.Fetch="fetch",t.LoadKeys="load_keys",t}({}),Oat=function(t){return t.Master="master",t.SelfSigning="self_signing",t.UserSigning="user_signing",t}({}),Mat=function(t){return t[t.NONE=0]="NONE",t[t.GREY=1]="GREY",t[t.RED=2]="RED",t}({}),Dat=function(t){return t[t.UNKNOWN=0]="UNKNOWN",t[t.UNVERIFIED_IDENTITY=1]="UNVERIFIED_IDENTITY",t[t.UNSIGNED_DEVICE=2]="UNSIGNED_DEVICE",t[t.UNKNOWN_DEVICE=3]="UNKNOWN_DEVICE",t[t.AUTHENTICITY_NOT_GUARANTEED=4]="AUTHENTICITY_NOT_GUARANTEED",t[t.MISMATCHED_SENDER_KEY=5]="MISMATCHED_SENDER_KEY",t[t.SENT_IN_CLEAR=6]="SENT_IN_CLEAR",t[t.VERIFICATION_VIOLATION=7]="VERIFICATION_VIOLATION",t[t.MISMATCHED_SENDER=8]="MISMATCHED_SENDER",t}({}),W1e=new Uint8Array(8);function YJ(t,e){return mA.apply(this,arguments)}function mA(){return mA=B(function*(t,e){var n=yield globalThis.crypto.subtle.importKey("raw",t,{name:"HKDF"},!1,["deriveBits"]),r=yield globalThis.crypto.subtle.deriveBits({name:"HKDF",salt:W1e,info:new TextEncoder().encode(e),hash:"SHA-256"},n,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])}),mA.apply(this,arguments)}function XJ(t,e,n,r){return gA.apply(this,arguments)}function gA(){return gA=B(function*(t,e,n,r){var i;r?i=Bh(r):(i=new Uint8Array(16),globalThis.crypto.getRandomValues(i),i[8]&=127);var[s,o]=yield YJ(e,n),a=new TextEncoder().encode(t),c=yield globalThis.crypto.subtle.encrypt({name:"AES-CTR",counter:i,length:64},s,a),l=yield globalThis.crypto.subtle.sign({name:"HMAC"},o,c);return{iv:Cy(i),ciphertext:Cy(new Uint8Array(c)),mac:Cy(new Uint8Array(l))}}),gA.apply(this,arguments)}function Y1e(t,e,n){return vA.apply(this,arguments)}function vA(){return vA=B(function*(t,e,n){var[r,i]=yield YJ(e,n),s=Bh(t.ciphertext);if(!(yield globalThis.crypto.subtle.verify({name:"HMAC"},i,Bh(t.mac),s)))throw new Error("Error decrypting secret ".concat(n,": bad MAC"));var o=yield globalThis.crypto.subtle.decrypt({name:"AES-CTR",counter:Bh(t.iv),length:64},r,s);return new TextDecoder().decode(new Uint8Array(o))}),vA.apply(this,arguments)}var Ih="m.secret_storage.v1.aes-hmac-sha2";class JJ{constructor(e,n){this.accountDataAdapter=e,this.callbacks=n}getDefaultKeyId(){var e=this;return B(function*(){var n,r=yield e.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return r&&(n=r.key)!==null&&n!==void 0?n:null})()}setDefaultKeyId(e){return new Promise((n,r)=>{var i=o=>{if(o.getType()==="m.secret_storage.default_key"){var a=o.getContent(),c=e===null?Object.keys(a).length===0:a.key===e;c&&(this.accountDataAdapter.removeListener(Le.AccountData,i),n())}};this.accountDataAdapter.on(Le.AccountData,i);var s=e===null?{}:{key:e};this.accountDataAdapter.setAccountData("m.secret_storage.default_key",s).catch(o=>{this.accountDataAdapter.removeListener(Le.AccountData,i),r(o)})})}addKey(e,n,r){var i=this;return B(function*(){if(e!==Ih)throw new Error("Unknown key algorithm ".concat(e));var s={algorithm:e};n.name&&(s.name=n.name),n.passphrase&&(s.passphrase=n.passphrase);var{iv:o,mac:a}=yield bA(n.key);if(s.iv=o,s.mac=a,!r)do r=To(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 n=this;return B(function*(){if(e||(e=yield n.getDefaultKeyId()),!e)return null;var r=yield n.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(e));return r?[e,r]:null})()}hasKey(e){var n=this;return B(function*(){var r=yield n.getKey(e);return!!r})()}checkKey(e,n){return B(function*(){if(n.algorithm===Ih)if(n.mac){var{mac:r}=yield bA(e,n.iv);return yA(n.mac)===yA(r)}else return!0;else throw new Error("Unknown algorithm")})()}store(e,n,r){var i=this;return B(function*(){if(n===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 c=yield i.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(a));if(!c)throw new Error("Unknown key: "+a);if(c.algorithm===Ih){var l={[a]:c},[,d]=yield i.getSecretStorageKey(l,e);s[a]=yield d.encrypt(n)}else M.warn("unknown algorithm for secret storage key "+a+": "+c.algorithm)}yield i.accountDataAdapter.setAccountData(e,{encrypted:s})})()}get(e){var n=this;return B(function*(){var r=yield n.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 n.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(s)),a=r.encrypted[s];o?.algorithm===Ih&&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[c,l]=yield n.getSecretStorageKey(i,e),d=r.encrypted[c];return l.decrypt(d)}})()}isStored(e){var n=this;return B(function*(){var r=yield n.accountDataAdapter.getAccountDataFromServer(e);if(!(r!=null&&r.encrypted))return null;var i={};for(var s of Object.keys(r.encrypted)){var o=yield n.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(s));if(o){var a=r.encrypted[s];o.algorithm===Ih&&a.iv&&a.ciphertext&&a.mac&&(i[s]=o)}}return Object.keys(i).length?i:null})()}getSecretStorageKey(e,n){var r=this;return B(function*(){if(!r.callbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");var i=yield r.callbacks.getSecretStorageKey({keys:e},n);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===Ih){var a={encrypt:function(l){return XJ(l,o,n)},decrypt:function(l){return Y1e(l,o,n)}};return[s,a]}else throw new Error("Unknown key type: "+e[s].algorithm)})()}}function yA(t){for(var e=t.length;e>=1&&t.charCodeAt(e-1)==61;)e--;return e<t.length?t.substring(0,e):t}var X1e="\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 bA(t,e){return XJ(X1e,t,"",e)}const J1e=Object.freeze(Object.defineProperty({__proto__:null,SECRET_STORAGE_ALGORITHM_V1_AES:Ih,ServerSideSecretStorageImpl:JJ,calculateKeyCheck:bA,trimTrailingEquals:yA},Symbol.toStringTag,{value:"Module"}));var QJ=t=>t.type==="livekit"&&"livekit_service_url"in t,ZJ=t=>QJ(t)&&"livekit_alias"in t,eQ=t=>t.type==="livekit"&&"focus_selection"in t,tQ=1e3*60*60*4,Q1e=(t,e)=>{var n,r="Malformed session membership event: ";return typeof t.device_id!="string"&&e.push(r+"device_id must be string"),typeof t.call_id!="string"&&e.push(r+"call_id must be string"),typeof t.application!="string"&&e.push(r+"application must be a string"),typeof((n=t.focus_active)===null||n===void 0?void 0:n.type)!="string"&&e.push(r+"focus_active.type must be a string"),Array.isArray(t.foci_preferred)||e.push(r+"foci_preferred must be an array"),t.created_ts!==void 0&&typeof t.created_ts!="number"&&e.push(r+"created_ts must be number"),t.scope!==void 0&&typeof t.scope!="string"&&e.push(r+"scope must be string"),t["m.call.intent"]!==void 0&&typeof t["m.call.intent"]!="string"&&e.push(r+"m.call.intent must be a string"),e.length===0};class X${static equal(e,n){return ff(e.membershipData,n.membershipData)}constructor(e,n){this.parentEvent=e,L(this,"membershipData",void 0);var r=[];if(Q1e(n,r))this.membershipData=n;else throw Error("unknown CallMembership data. Does not match MSC4143 call.member (".concat(r.join(" & "),") events this could be a legacy membership event: (").concat(n,")"))}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 callIntent(){return this.membershipData["m.call.intent"]}get sessionDescription(){return{application:this.membershipData.application,id:this.membershipData.call_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:tQ)}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(eQ(e))return e.focus_selection}}var zE=function(t){return t.Cancel="cancel",t.Restart="restart",t.Send="send",t}({}),e7=function(t){return t.TooNew="TOO_NEW",t}({});class t7 extends Error{constructor(e){var n="Crypto store is invalid because ".concat(e,", ")+"please stop the client, delete all data and start the client again";super(n),this.reason=e,this.name="InvalidCryptoStoreError"}}L(t7,"TOO_NEW",e7.TooNew);class Z1e extends Error{constructor(e,n){super(e),this.value=n}}class eye extends Error{constructor(){super("MatrixClient has been stopped")}}class Gd extends Error{constructor(e,n){super(e),this.clientEndpoint=n,this.name="UnsupportedDelayedEventsEndpointError"}}var Ad=function(t){return t.Disconnected="Disconnected",t.Connecting="Connecting",t.ConnectingFailed="ConnectingFailed",t.Connected="Connected",t.Reconnecting="Reconnecting",t.Disconnecting="Disconnecting",t.Stuck="Stuck",t.Unknown="Unknown",t}({}),WE=(t,e,n)=>t.sender===e&&t.deviceId===n;class tye{constructor(e,n){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=(n??M).getChild("[NewMembershipActionScheduler]")}get actions(){return this._actions}startWithJoin(){var e=this;return B(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 n=function*(){e._actions.sort((l,d)=>l.ts-d.ts);var i=e._actions[0],s=void 0,o=new Promise(l=>{e.wakeup=d=>{s=d,l()}});i.ts>Date.now()&&(yield Promise.race([o,_p(i.ts-Date.now())]));var a={};if(!s){e.logger.debug("Current MembershipManager processing: ".concat(i.type,`
24
24
  Queue:`),e._actions,`
25
- Date.now: "`.concat(Date.now()));try{a=yield e.membershipLoopHandler(i.type)}catch(l){throw Error("The MembershipManager shut down because of the end condition: ".concat(l))}}e._actions.splice(0,1);var c=s??a;"replace"in c?e._actions=c.replace:"insert"in c&&e._actions.push(...c.insert)};e._actions.length>0;)yield*n()}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 Hh=function(t){return t.StatusChanged="StatusChanged",t.ProbablyLeft="ProbablyLeft",t}({});function J$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function nye(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?J$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):J$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var ot=function(t){return t.SendDelayedEvent="SendDelayedEvent",t.SendJoinEvent="SendJoinEvent",t.RestartDelayedEvent="RestartDelayedEvent",t.UpdateExpiry="UpdateExpiry",t.SendScheduledDelayedLeaveEvent="SendScheduledDelayedLeaveEvent",t.SendLeaveEvent="SendLeaveEvent",t}({});class fC extends On{isActivated(){return this.activated}isJoined(){return this.isActivated()}join(e,n,r){if(this.scheduler.running){this.logger.error("MembershipManager is already running. Ignoring join request.");return}this.fociPreferred=e,this.focusActive=n,this.leavePromiseResolvers=void 0,this.activated=!0,this.oldStatus=this.status,this.state=fC.defaultState,this.scheduler.startWithJoin().catch(i=>{this.logger.error("MembershipManager stopped because: ",i),r?.(i)}).finally(()=>{if(this.activated=!1,this.oldStatus&&this.oldStatus!==this.status&&this.emit(Hh.StatusChanged,this.oldStatus,this.status),!this.scheduler.running){var i;(i=this.leavePromiseResolvers)===null||i===void 0||i.resolve(!0),this.leavePromiseResolvers=void 0}})}leave(e){return this.scheduler.running?(this.leavePromiseResolvers||(this.leavePromiseResolvers=Promise.withResolvers(),this.activated=!1,this.scheduler.initiateLeave(),e&&setTimeout(()=>{var n;return(n=this.leavePromiseResolvers)===null||n===void 0?void 0:n.resolve(!1)},e)),this.leavePromiseResolvers.promise):(this.logger.warn("Called MembershipManager.leave() even though the MembershipManager is not running"),Promise.resolve(!0))}onRTCSessionMemberUpdate(e){if(!this.isActivated())return Promise.resolve();var n=this.client.getUserId(),r=this.client.getDeviceId();if(!n||!r)return this.logger.error("MembershipManager.onRTCSessionMemberUpdate called without user or device id"),Promise.resolve();if(this._ownMembership=e.find(s=>WE(s,n,r)),!this._ownMembership){var i=[ot.SendDelayedEvent,ot.SendJoinEvent];this.logger.warn("Missing own membership: force re-join"),this.state.hasMemberStateEvent=!1,this.scheduler.actions.some(s=>i.includes(s.type))?this.logger.error("tried adding another `SendDelayedEvent` actions even though we already have one in the Queue\nActionQueueOnMemberUpdate:",this.scheduler.actions):this.scheduler.initiateJoin()}return Promise.resolve()}getActiveFocus(){if(this.focusActive)if(eQ(this.focusActive)){if(this.focusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e?.getPreferredFoci()[0]}}else this.logger.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{var n=this.getOldestMembership();return n?.getPreferredFoci()[0]}}updateCallIntent(e){var n=this;return B(function*(){if(!n.activated||!n.ownMembership)throw Error("You cannot update your intent before joining the call");n.ownMembership.callIntent!==e&&(n.callIntent=e,yield n.sendJoinEvent())})()}constructor(e,n,r,i,s,o){super(),this.joinConfig=e,this.room=n,this.client=r,this.getOldestMembership=i,this.sessionDescription=s,L(this,"activated",!1),L(this,"logger",void 0),L(this,"callIntent",void 0),L(this,"leavePromiseResolvers",void 0),L(this,"_ownMembership",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,"delayedLeaveEventDelayMsOverride",void 0),this.logger=(o??M).getChild("[MembershipManager]");var[a,c]=[this.client.getUserId(),this.client.getDeviceId()];if(a===null)throw Error("Missing userId in client");if(c===null)throw Error("Missing deviceId in client");this.deviceId=c,this.stateKey=this.makeMembershipStateKey(a,c),this.state=fC.defaultState,this.callIntent=e?.callIntent,this.scheduler=new tye(l=>(this.oldStatus&&(this.logger.debug("MembershipManager applied action changes. Status: ".concat(this.oldStatus," -> ").concat(this.status)),this.oldStatus!==this.status&&this.emit(Hh.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)}get ownMembership(){return this._ownMembership}static get defaultState(){return{hasMemberStateEvent:!1,delayId:void 0,startTime:0,rateLimitRetries:new Map,networkErrorRetries:new Map,expireUpdateIterations:1,probablyLeft:!1}}get networkErrorRetryMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.networkErrorRetryMs)!==null&&e!==void 0?e:3e3}get membershipEventExpiryMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.membershipEventExpiryMs)!==null&&e!==void 0?e:tQ}get membershipEventExpiryHeadroomMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.membershipEventExpiryHeadroomMs)!==null&&e!==void 0?e:5e3}computeNextExpiryActionTs(e){return this.state.startTime+this.membershipEventExpiryMs*e-this.membershipEventExpiryHeadroomMs}get delayedLeaveEventDelayMs(){var e,n,r;return(e=(n=this.delayedLeaveEventDelayMsOverride)!==null&&n!==void 0?n:(r=this.joinConfig)===null||r===void 0?void 0:r.delayedLeaveEventDelayMs)!==null&&e!==void 0?e:8e3}get delayedLeaveEventRestartMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.delayedLeaveEventRestartMs)!==null&&e!==void 0?e:5e3}get maximumRateLimitRetryCount(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.maximumRateLimitRetryCount)!==null&&e!==void 0?e:10}get maximumNetworkErrorRetryCount(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.maximumNetworkErrorRetryCount)!==null&&e!==void 0?e:10}get delayedLeaveEventRestartLocalTimeoutMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.delayedLeaveEventRestartLocalTimeoutMs)!==null&&e!==void 0?e:2e3}membershipLoopHandler(e){var n=this;return B(function*(){switch(e){case ot.SendDelayedEvent:return n.state.delayId?n.cancelKnownDelayIdBeforeSendDelayedEvent(n.state.delayId):n.sendOrResendDelayedLeaveEvent();case ot.RestartDelayedEvent:return n.state.delayId?n.restartDelayedEvent(n.state.delayId):Go(ot.SendDelayedEvent);case ot.SendScheduledDelayedLeaveEvent:return n.state.hasMemberStateEvent?n.state.delayId?n.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(n.state.delayId):Go(ot.SendLeaveEvent):{replace:[]};case ot.SendJoinEvent:return n.sendJoinEvent();case ot.UpdateExpiry:return n.updateExpiryOnJoinedEvent();case ot.SendLeaveEvent:return n.state.hasMemberStateEvent?n.sendFallbackLeaveEvent():{replace:[]}}})()}sendOrResendDelayedLeaveEvent(){var e=this;return B(function*(){return yield e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.delayedLeaveEventDelayMs},Z.GroupCallMemberPrefix,{},e.stateKey).then(n=>(e.state.expectedServerDelayLeaveTs=Date.now()+e.delayedLeaveEventDelayMs,e.setAndEmitProbablyLeft(!1),e.resetRateLimitCounter(ot.SendDelayedEvent),e.state.delayId=n.delay_id,e.state.hasMemberStateEvent?Go(ot.RestartDelayedEvent,e.delayedLeaveEventRestartMs):Go(ot.SendJoinEvent))).catch(n=>{var r=ot.SendDelayedEvent;if(e.manageMaxDelayExceededSituation(n))return Go(r);var i=e.actionUpdateFromErrors(n,r,"sendDelayedStateEvent");if(i)return i;if(e.state.hasMemberStateEvent){if(e.isUnsupportedDelayedEndpoint(n))return{};throw Error("Could not send delayed event, even though delayed events are supported. "+n)}else return e.isUnsupportedDelayedEndpoint(n)?e.logger.info("Not using delayed event because the endpoint is not supported"):e.logger.info("Not using delayed event because: "+n),Go(ot.SendJoinEvent)})})()}cancelKnownDelayIdBeforeSendDelayedEvent(e){var n=this;return B(function*(){return yield n.client._unstable_updateDelayedEvent(e,zE.Cancel).then(()=>(n.state.delayId=void 0,n.resetRateLimitCounter(ot.SendDelayedEvent),Mk(ot.SendDelayedEvent))).catch(r=>{var i=ot.SendDelayedEvent,s=n.actionUpdateFromErrors(r,i,"updateDelayedEvent");if(s)return s;if(n.isNotFoundError(r))return n.state.delayId=void 0,Mk(i);if(n.isUnsupportedDelayedEndpoint(r))return Mk(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")})})()}setAndEmitProbablyLeft(e){this.state.probablyLeft!==e&&(this.state.probablyLeft=e,this.emit(Hh.ProbablyLeft,this.state.probablyLeft))}restartDelayedEvent(e){var n=this;return B(function*(){var r=n.state.expectedServerDelayLeaveTs?n.state.expectedServerDelayLeaveTs-Date.now():void 0,i=new Promise((s,o)=>{setTimeout(()=>{o(new FX("Restart delayed event timed out before the HS responded"))},r!==void 0&&!n.state.probablyLeft?Math.min(n.delayedLeaveEventRestartLocalTimeoutMs,r):n.delayedLeaveEventRestartLocalTimeoutMs)});return yield Promise.race([n.client._unstable_updateDelayedEvent(e,zE.Restart),i]).then(()=>(n.state.expectedServerDelayLeaveTs=Date.now()+n.delayedLeaveEventDelayMs,n.resetRateLimitCounter(ot.RestartDelayedEvent),n.setAndEmitProbablyLeft(!1),Go(ot.RestartDelayedEvent,n.delayedLeaveEventRestartMs))).catch(s=>{n.state.expectedServerDelayLeaveTs&&n.state.expectedServerDelayLeaveTs<=Date.now()&&n.setAndEmitProbablyLeft(!0);var o=ot.RestartDelayedEvent;if(n.isNotFoundError(s))return n.state.delayId=void 0,Go(ot.SendDelayedEvent);if(n.isUnsupportedDelayedEndpoint(s))return{};var a=n.actionUpdateFromErrors(s,o,"updateDelayedEvent");if(a)return a;throw Error("Could not restart delayed event, even though delayed events are supported. "+s)})})()}sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(e){var n=this;return B(function*(){return yield n.client._unstable_updateDelayedEvent(e,zE.Send).then(()=>(n.state.hasMemberStateEvent=!1,n.resetRateLimitCounter(ot.SendScheduledDelayedLeaveEvent),{replace:[]})).catch(r=>{var i=ot.SendLeaveEvent;if(n.isUnsupportedDelayedEndpoint(r))return{};if(n.isNotFoundError(r))return n.state.delayId=void 0,Go(i);var s=n.actionUpdateFromErrors(r,i,"updateDelayedEvent");return s||(n.logger.warn("Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent",r),Go(i))})})()}sendJoinEvent(){var e=this;return B(function*(){return yield e.client.sendStateEvent(e.room.roomId,Z.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryMs),e.stateKey).then(()=>{e.setAndEmitProbablyLeft(!1),e.state.startTime=Date.now(),e.state.expireUpdateIterations=1,e.state.hasMemberStateEvent=!0,e.resetRateLimitCounter(ot.SendJoinEvent);var n=e.scheduler.actions.filter(r=>r.type!==ot.UpdateExpiry&&r.type!==ot.SendJoinEvent);return{replace:[...n,{ts:Date.now(),type:ot.RestartDelayedEvent},{ts:e.computeNextExpiryActionTs(e.state.expireUpdateIterations),type:ot.UpdateExpiry}]}}).catch(n=>{var r=e.actionUpdateFromErrors(n,ot.SendJoinEvent,"sendStateEvent");if(r)return r;throw n})})()}updateExpiryOnJoinedEvent(){var e=this;return B(function*(){var n=e.state.expireUpdateIterations+1;return yield e.client.sendStateEvent(e.room.roomId,Z.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryMs*n),e.stateKey).then(()=>(e.resetRateLimitCounter(ot.UpdateExpiry),e.state.expireUpdateIterations=n,{insert:[{ts:e.computeNextExpiryActionTs(n),type:ot.UpdateExpiry}]})).catch(r=>{var i=e.actionUpdateFromErrors(r,ot.UpdateExpiry,"sendStateEvent");if(i)return i;throw r})})()}sendFallbackLeaveEvent(){var e=this;return B(function*(){return yield e.client.sendStateEvent(e.room.roomId,Z.GroupCallMemberPrefix,{},e.stateKey).then(()=>(e.resetRateLimitCounter(ot.SendLeaveEvent),e.state.hasMemberStateEvent=!1,{replace:[]})).catch(n=>{var r=e.actionUpdateFromErrors(n,ot.SendLeaveEvent,"sendStateEvent");if(r)return r;throw n})})()}makeMembershipStateKey(e,n){var r="".concat(e,"_").concat(n,"_").concat(this.sessionDescription.application).concat(this.sessionDescription.id);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:"_".concat(r)}makeMyMembership(e){var n,r,i=!!this.ownMembership;return nye({application:this.sessionDescription.application,call_id:this.sessionDescription.id,scope:"m.room",device_id:this.deviceId,expires:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(n=this.fociPreferred)!==null&&n!==void 0?n:[],"m.call.intent":this.callIntent},i?{created_ts:(r=this.ownMembership)===null||r===void 0?void 0:r.createdTs()}:void 0)}isNotFoundError(e){return e instanceof tr&&e.errcode==="M_NOT_FOUND"}manageMaxDelayExceededSituation(e){if(e instanceof tr&&e.errcode==="M_UNKNOWN"&&e.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var n=e.data["org.matrix.msc4140.max_delay"];return typeof n=="number"&&this.delayedLeaveEventDelayMs>n&&(this.delayedLeaveEventDelayMsOverride=n),this.logger.warn("Retry sending delayed disconnection event due to server timeout limitations:",e),!0}return!1}actionUpdateFromErrors(e,n,r){var i=this.actionUpdateFromRateLimitError(e,r,n);if(i)return i;var s=this.actionUpdateFromNetworkErrorRetry(e,n);if(s)return s}actionUpdateFromRateLimitError(e,n,r){var i;if((e instanceof ep||e instanceof tr)&&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 c;o=(c=e.getRetryAfterMs())!==null&&c!==void 0?c:a,this.logger.info("Rate limited by server, retrying in ".concat(o,"ms"))}catch(l){this.logger.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(a),l),o=a}return this.state.rateLimitRetries.set(r,s+1),Go(r,o)}throw Error("Exceeded maximum retries for "+r+" attempts (client."+n+"): "+e)}}actionUpdateFromNetworkErrorRetry(e,n){var r,i=(r=this.state.networkErrorRetries.get(n))!==null&&r!==void 0?r:0,s=this.networkErrorRetryMs/1e3+"s",o="("+i+"/"+this.maximumNetworkErrorRetryCount+")",a=this.networkErrorRetryMs;if(e instanceof Error&&e.name==="AbortError")a=0,this.logger.warn("Network local timeout error while sending event, immediate retry ("+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 wp)this.logger.warn("Network connection error while sending event, retrying in "+s+" "+o,e);else if((e instanceof ep||e instanceof tr)&&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(n,i+1),Go(n,a);throw Error("Reached maximum ("+this.maximumNetworkErrorRetryCount+") retries cause by: "+e)}isUnsupportedDelayedEndpoint(e){return e instanceof Gd}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:n}=e[0];switch(n){case ot.SendDelayedEvent:case ot.SendJoinEvent:return Ad.Connecting;case ot.UpdateExpiry:return Ad.Connected;case ot.SendScheduledDelayedLeaveEvent:case ot.SendLeaveEvent:return Ad.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 Ad.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 Ad.Connected}return this.scheduler.running?(this.logger.error("MembershipManager has an unknown state. Actions: ",e),Ad.Unknown):Ad.Disconnected}get probablyLeft(){return this.state.probablyLeft}}function Go(t,e){return{insert:[{ts:Date.now()+(e??0),type:t}]}}function Mk(t,e){return{replace:[{ts:Date.now()+0,type:t}]}}var Wc=function(t){return t.ReceivedKeys="received_keys",t.NotSupportedError="not_supported_error",t}({});class rye{constructor(){L(this,"tsBuffer",new Map)}isOutdated(e,n){var r;this.tsBuffer.has(e)||this.tsBuffer.set(e,new Map);var i=(r=this.tsBuffer.get(e))===null||r===void 0?void 0:r.get(n.keyIndex);return i&&i>n.creationTS?!0:(this.tsBuffer.get(e).set(n.keyIndex,n.creationTS),!1)}}function Vh(t,e){return"".concat(t,":").concat(e)}class nQ extends Error{constructor(e){super(e)}get name(){return"NotSupportedError"}}class iye extends On{setParentLogger(e){this.logger=e.getChild("[ToDeviceKeyTransport]")}constructor(e,n,r,i,s,o){super(),this.userId=e,this.deviceId=n,this.roomId=r,this.client=i,this.statistics=s,L(this,"logger",M),L(this,"onToDeviceEvent",a=>{if(a.getType()===Z.CallEncryptionKeysPrefix){var c=this.getValidEventContent(a);c&&a.getSender()&&this.receiveCallKeyEvent(a.getSender(),c)}}),this.setParentLogger(o??M)}start(){this.client.on(Le.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.off(Le.ToDeviceEvent,this.onToDeviceEvent)}sendKey(e,n,r){var i=this;return B(function*(){var s={keys:{index:n,key:e},room_id:i.roomId,member:{claimed_device_id:i.deviceId},session:{call_id:"",application:"m.call",scope:"m.room"},sent_ts:Date.now()},o=r.map(a=>({userId:a.userId,deviceId:a.deviceId})).filter(a=>!(a.userId==i.userId&&a.deviceId==i.deviceId));o.length>0?(yield i.client.encryptAndSendToDevice(Z.CallEncryptionKeysPrefix,o,s).catch(a=>{var c=a.message;if(c.includes("unknown variant")&&c.includes("send_to_device")||c.includes("not supported"))throw new nQ("The widget driver does not support to-device encryption")}),i.statistics.counters.roomEventEncryptionKeysSent+=1):i.logger.warn("No targets found for sending key")})()}receiveCallKeyEvent(e,n){this.statistics.counters.roomEventEncryptionKeysReceived+=1;var r=Date.now(),i=r-(typeof n.sent_ts=="number"?n.sent_ts:r);this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=i,this.emit(Wc.ReceivedKeys,e,n.member.claimed_device_id,n.keys.key,n.keys.index,r)}getValidEventContent(e){var n=e.getContent(),r=n.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(!n.keys||!n.keys.key||typeof n.keys.index!="number"){this.logger.warn("Malformed Event: Missing keys field");return}if(!n.member||!n.member.claimed_device_id){this.logger.warn("Malformed Event: Missing claimed_device_id");return}return n}}var p_=function(t){return t.EnabledTransportsChanged="enabled_transports_changed",t}({});class n7 extends On{constructor(e,n,r){var i;super(),i=this,this.toDeviceTransport=e,this.roomKeyTransport=n,L(this,"logger",void 0),L(this,"_enabled",{toDevice:!0,room:!1}),this.logger=(r??M).getChild("[RoomAndToDeviceTransport]"),this.toDeviceTransport.setParentLogger(this.logger),this.roomKeyTransport.setParentLogger(this.logger),this.roomKeyTransport.on(Wc.ReceivedKeys,function(){i._enabled.room||(i.logger.debug("Received room key, enabling room key transport, disabling toDevice transport"),i.setEnabled({toDevice:!1,room:!0}));for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];i.emit(Wc.ReceivedKeys,...o)}),this.toDeviceTransport.on(Wc.ReceivedKeys,function(){if(i._enabled.toDevice){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];i.emit(Wc.ReceivedKeys,...o)}else i.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(p_.EnabledTransportsChanged,e))}get enabled(){return this._enabled}start(){this.roomKeyTransport.start(),this.toDeviceTransport.start()}stop(){this.roomKeyTransport.stop(),this.toDeviceTransport.stop()}sendKey(e,n,r){var i=this;return B(function*(){if(i.logger.debug("Sending key with index ".concat(n," 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,n,r)),i._enabled.toDevice)try{yield i.toDeviceTransport.sendKey(e,n,r)}catch(s){s instanceof nQ&&!i._enabled.room&&(i.logger.warn("To device is not supported enabling room key transport, disabling toDevice transport"),i.setEnabled({toDevice:!1,room:!0}),yield i.sendKey(e,n,r))}})()}}class sye{get updateEncryptionKeyThrottle(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.updateEncryptionKeyThrottle)!==null&&e!==void 0?e:3e3}get makeKeyDelay(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.makeKeyDelay)!==null&&e!==void 0?e:3e3}get useKeyDelay(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.useKeyDelay)!==null&&e!==void 0?e:5e3}constructor(e,n,r,i,s,o,a){var c=this;this.userId=e,this.deviceId=n,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 l=B(function*(d){if(c.keysEventUpdateTimeout!==void 0&&(clearTimeout(c.keysEventUpdateTimeout),c.keysEventUpdateTimeout=void 0),c.lastEncryptionKeyUpdateRequest=Date.now(),!!c.joined){var h=c.getKeysForParticipant(c.userId,c.deviceId);if(!h){c.logger.warn("Tried to send encryption keys event but no keys found!");return}if(typeof d!="number"&&c.latestGeneratedKeyIndex===-1){c.logger.warn("Tried to send encryption keys event but no current key index found!");return}var m=d??c.latestGeneratedKeyIndex;c.logger.info("Try sending encryption keys event. keyIndexToSend=".concat(m," (method parameter: ").concat(d,")"));var g=h[m];try{c.statistics.counters.roomEventEncryptionKeysSent+=1;var y=c.getMemberships().filter(w=>w.sender!=null).map(w=>({userId:w.sender,deviceId:w.deviceId,membershipTs:w.createdTs()}));yield c.transport.sendKey($J(g),m,y),c.logger.debug("sendEncryptionKeysEvent participantId=".concat(c.userId,":").concat(c.deviceId," numKeys=").concat(h.length," currentKeyIndex=").concat(c.latestGeneratedKeyIndex," keyIndexToSend=").concat(m))}catch(w){if(c.keysEventUpdateTimeout===void 0){var v=HO(w,5e3);c.logger.warn("Failed to send m.call.encryption_key, retrying in ".concat(v),w),c.keysEventUpdateTimeout=setTimeout(()=>void c.sendEncryptionKeysEvent(),v)}else c.logger.info("Not scheduling key resend as another re-send is already pending")}}});return function(d){return l.apply(this,arguments)}}()),L(this,"onTransportChanged",()=>{this.requestSendCurrentKey()}),L(this,"onNewKeyReceived",(l,d,h,m,g)=>{this.logger.debug("Received key over key transport ".concat(l,":").concat(d," at index ").concat(m)),this.setEncryptionKey(l,d,m,h,g)}),L(this,"onRotateKeyTimeout",()=>{if(this.manageMediaKeys){this.makeNewKeyTimeout=void 0,this.logger.info("Making new sender key for key rotation");var l=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(l)}}),this.logger=(a??M).getChild("[EncryptionManager]")}getEncryptionKeys(){var e=new Map;for(var[n,r]of this.encryptionKeys){var i=r.map((s,o)=>({key:s.key,keyIndex:o}));e.set(n,i)}return e}join(e){var n,r,i;this.joinConfig=e,this.joined=!0,this.manageMediaKeys=(n=(r=this.joinConfig)===null||r===void 0?void 0:r.manageMediaKeys)!==null&&n!==void 0?n:this.manageMediaKeys,this.transport.on(Wc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof n7&&this.transport.on(p_.EnabledTransportsChanged,this.onTransportChanged),this.transport.start(),(i=this.joinConfig)!==null&&i!==void 0&&i.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey())}leave(){this.encryptionKeys.set(Vh(this.userId,this.deviceId),[]),this.transport.off(Wc.ReceivedKeys,this.onNewKeyReceived),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 n=new Set(e.filter(l=>!WE(l,this.userId,this.deviceId)).map(Dk)),r=new Set(this.getMemberships().filter(l=>!WE(l,this.userId,this.deviceId)).map(Dk)),i=Array.from(n).some(l=>!r.has(l)),s=Array.from(r).some(l=>!n.has(l)),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,c=Array.from(o).some(l=>!a.has(l))||Array.from(a).some(l=>!o.has(l));c&&(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,n=BJ(16),r=this.getNewEncryptionKeyIndex();return this.logger.info("Generated new key at index "+r),this.setEncryptionKey(this.userId,this.deviceId,r,n,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,n){var r;return(r=this.encryptionKeys.get(Vh(e,n)))===null||r===void 0?void 0:r.map(i=>i.key)}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.getMemberships().filter(e=>!WE(e,this.userId,this.deviceId)).map(e=>"".concat(Dk(e),":").concat(e.createdTs())))}getNewEncryptionKeyIndex(){return this.latestGeneratedKeyIndex===-1?0:(this.latestGeneratedKeyIndex+1)%256}setEncryptionKey(e,n,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(n," at index ").concat(r));var a=Bh(i),c=Vh(e,n);this.encryptionKeys.has(c)||this.encryptionKeys.set(c,[]);var l=this.encryptionKeys.get(c),d=l[r];if(d){if(d.timestamp>s){this.logger.info("Ignoring new key at index ".concat(r," for ").concat(c," as it is older than existing known key"));return}if(oye(d.key,a)){d.timestamp=s;return}}if(e===this.userId&&n===this.deviceId&&(this.latestGeneratedKeyIndex=r),l[r]={key:a,timestamp:s},o){var h=setTimeout(()=>{this.setNewKeyTimeouts.delete(h),this.logger.info("Delayed-emitting key changed event for ".concat(c," index ").concat(r)),this.onEncryptionKeysChanged(a,r,c)},this.useKeyDelay);this.setNewKeyTimeouts.add(h)}else this.onEncryptionKeysChanged(a,r,c)}}function oye(t,e){return t===e?!0:!!t&&!!e&&t.length===e.length&&t.every((n,r)=>n===e[r])}var Dk=t=>Vh(t.sender,t.deviceId);class Q$ extends On{setParentLogger(e){this.logger=e.getChild("[RoomKeyTransport]")}constructor(e,n,r,i){super(),this.room=e,this.client=n,this.statistics=r,L(this,"logger",M),this.setParentLogger(i??M)}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 n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[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()!==Z.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,n,r){var i=this;return B(function*(){var s={keys:[{index:n,key:e}],device_id:i.client.getDeviceId(),call_id:"",sent_ts:Date.now()};try{yield i.client.sendEvent(i.room.roomId,Z.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 n=e.getSender(),r=e.getContent(),i=r.device_id,s=r.call_id;if(!n){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(n,", 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(n===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 c=a.key,l=a.index;!c||l===void 0||l===null||s===void 0||s===null||typeof i!="string"||typeof s!="string"||typeof c!="string"||typeof l!="number"?this.logger.warn("Malformed call encryption_key: userId=".concat(n,", deviceId=").concat(i,", encryptionKeyIndex=").concat(l," callId=").concat(s)):(this.logger.debug("onCallEncryption userId=".concat(n,":").concat(i," encryptionKeyIndex=").concat(l," age=").concat(o,"ms")),this.emit(Wc.ReceivedKeys,n,i,c,l,e.getTs()))}}}class aye{constructor(e,n,r,i,s,o,a){this.userId=e,this.deviceId=n,this.getMemberships=r,this.transport=i,this.statistics=s,this.onEncryptionKeysChanged=o,L(this,"manageMediaKeys",!1),L(this,"participantKeyRings",new Map),L(this,"outboundSession",null),L(this,"currentKeyDistributionPromise",null),L(this,"useKeyDelay",5e3),L(this,"keyRotationGracePeriodMs",1e4),L(this,"needToEnsureKeyAgain",!1),L(this,"keyBuffer",new rye),L(this,"logger",void 0),L(this,"onTransportChanged",()=>{var c;(c=this.logger)===null||c===void 0||c.info("Transport change detected, restarting key distribution"),this.currentKeyDistributionPromise?this.currentKeyDistributionPromise.then(()=>{this.outboundSession&&(this.outboundSession.sharedWith=[],this.ensureKeyDistribution())}).catch(l=>{var d;(d=this.logger)===null||d===void 0||d.error("Failed to restart key distribution",l)}):this.outboundSession&&(this.outboundSession.sharedWith=[],this.ensureKeyDistribution())}),L(this,"onNewKeyReceived",(c,l,d,h,m)=>{var g;if(!this.manageMediaKeys){var y;(y=this.logger)===null||y===void 0||y.warn("Received key over transport ".concat(c,":").concat(l," at index ").concat(h," but media keys are disabled"));return}(g=this.logger)===null||g===void 0||g.debug("Received key over transport ".concat(c,":").concat(l," at index ").concat(h));var v=Vh(c,l),w=Bh(d),S={key:w,participantId:v,keyIndex:h,creationTS:m},R=this.keyBuffer.isOutdated(v,S);if(!R)this.addKeyToParticipant(S.key,S.keyIndex,S.participantId),this.statistics.counters.roomEventEncryptionKeysReceived+=1;else{var x;(x=this.logger)===null||x===void 0||x.info("Received an out of order key for ".concat(c,":").concat(l,", dropping it"))}}),this.logger=a?.getChild("[EncryptionManager]")}getEncryptionKeys(){return new Map(this.participantKeyRings)}addKeyToParticipant(e,n,r){this.participantKeyRings.has(r)||this.participantKeyRings.set(r,[]),this.participantKeyRings.get(r).push({key:e,keyIndex:n}),this.onEncryptionKeysChanged(e,n,r)}join(e){var n,r,i,s;this.manageMediaKeys=(n=e?.manageMediaKeys)!==null&&n!==void 0?n:!0,(r=this.logger)===null||r===void 0||r.info("Joining room"),this.useKeyDelay=(i=e?.useKeyDelay)!==null&&i!==void 0?i:1e3,this.keyRotationGracePeriodMs=(s=e?.keyRotationGracePeriodMs)!==null&&s!==void 0?s:1e4,this.transport.on(Wc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof n7&&this.transport.on(p_.EnabledTransportsChanged,this.onTransportChanged),this.transport.start()}leave(){this.transport.off(Wc.ReceivedKeys,this.onNewKeyReceived),this.transport.stop(),this.participantKeyRings.clear()}ensureKeyDistribution(){if(this.manageMediaKeys)if(this.currentKeyDistributionPromise==null){var e;(e=this.logger)===null||e===void 0||e.debug("No active rollout, start a new one"),this.currentKeyDistributionPromise=this.rolloutOutboundKey().then(()=>{var r;if((r=this.logger)===null||r===void 0||r.debug("Rollout completed"),this.currentKeyDistributionPromise=null,this.needToEnsureKeyAgain){var i;(i=this.logger)===null||i===void 0||i.debug("New Rollout needed"),this.needToEnsureKeyAgain=!1,this.ensureKeyDistribution()}})}else{var n;(n=this.logger)===null||n===void 0||n.debug("Rollout in progress, a new rollout will be started after the current one"),this.needToEnsureKeyAgain=!0}}onMembershipsUpdate(){var e;(e=this.logger)===null||e===void 0||e.trace("onMembershipsUpdate"),this.ensureKeyDistribution()}rolloutOutboundKey(){var e=this;return B(function*(){var n,r,i=e.outboundSession==null;i&&(e.outboundSession={key:e.generateRandomKey(),creationTS:Date.now(),sharedWith:[],keyId:0},e.addKeyToParticipant(e.outboundSession.key,e.outboundSession.keyId,Vh(e.userId,e.deviceId)));var s=e.getMemberships().filter(A=>A.sender!=null).map(A=>({userId:A.sender,deviceId:A.deviceId,membershipTs:A.createdTs()})),o=(n=(r=e.outboundSession)===null||r===void 0?void 0:r.sharedWith)!==null&&n!==void 0?n:[];o=o.filter(A=>!s.some(O=>A.userId==O.userId&&A.deviceId==O.deviceId&&A.membershipTs!=O.membershipTs));var a=o.filter(A=>!s.some(O=>A.userId==O.userId&&A.deviceId==O.deviceId&&A.membershipTs==O.membershipTs)),c=s.filter(A=>!o.some(O=>A.userId==O.userId&&A.deviceId==O.deviceId&&A.membershipTs==O.membershipTs)),l=[],d,h=!1;if(a.length>0){var m=e.createNewOutboundSession();h=!0,l=s,d=m}else if(c.length>0){var g=Date.now(),y=g-e.outboundSession.creationTS;if(y<e.keyRotationGracePeriodMs){var v;(v=e.logger)===null||v===void 0||v.debug("New joiners detected, but the key is recent enough (age:".concat(y,"), keeping it")),l=c,d=e.outboundSession}else{var w;(w=e.logger)===null||w===void 0||w.debug("New joiners detected, rotating the key");var S=e.createNewOutboundSession();h=!0,l=s,d=S}}else return;try{var R,x;if((R=e.logger)===null||R===void 0||R.trace("Sending key..."),yield e.transport.sendKey(Cy(d.key),d.keyId,l),e.statistics.counters.roomEventEncryptionKeysSent+=1,d.sharedWith.push(...l),(x=e.logger)===null||x===void 0||x.trace("key index:".concat(d.keyId," sent to ").concat(d.sharedWith.map(A=>"".concat(A.userId,":").concat(A.deviceId)).join(","))),h){var T,I;(T=e.logger)===null||T===void 0||T.trace("Delay Rollout for key:".concat(d.keyId,"...")),yield _p(e.useKeyDelay),(I=e.logger)===null||I===void 0||I.trace("...Delayed rollout of index:".concat(d.keyId," ")),e.addKeyToParticipant(d.key,d.keyId,Vh(e.userId,e.deviceId))}}catch(A){var k;(k=e.logger)===null||k===void 0||k.error("Failed to rollout key",A)}})()}createNewOutboundSession(){var e,n={key:this.generateRandomKey(),creationTS:Date.now(),sharedWith:[],keyId:this.nextKeyIndex()};return(e=this.logger)===null||e===void 0||e.info("creating new outbound key index:".concat(n.keyId)),this.outboundSession=n,n}nextKeyIndex(){return this.outboundSession?(this.outboundSession.keyId+1)%256:0}generateRandomKey(){var e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),e}}function Z$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function P2(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Z$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Z$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var ei=function(t){return t.MembershipsChanged="memberships_changed",t.JoinStateChanged="join_state_changed",t.EncryptionKeyChanged="encryption_key_changed",t.MembershipManagerError="membership_manager_error",t.DidSendCallNotification="did_send_call_notification",t}({});class Zl extends On{get membershipStatus(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.status}get probablyLeft(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.probablyLeft}get callId(){return this._callId}static callMembershipsForRoom(e){return Zl.sessionMembershipsForRoom(e,{id:"",application:"m.call"})}static sessionMembershipsForRoom(e,n){var r=M.getChild("[MatrixRTCSession ".concat(e.roomId,"]")),i=e.getLiveTimeline().getState(Me.FORWARDS);if(!i)throw r.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);var s=i.getStateEvents(Z.GroupCallMemberPrefix),o=[];for(var a of s){var c=a.getContent(),l=Object.keys(c).length;if(l!==0){var d=[];if(l>1&&"focus_active"in c?d.push(c):l===1&&"memberships"in c&&r.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session"),d.length!==0)for(var h of d)try{var m,g=new X$(a,h);if(!ff(g.sessionDescription,n)){r.info("Ignoring membership of user ".concat(g.sender," for a different session: ").concat(JSON.stringify(g.sessionDescription)));continue}if(g.isExpired()){r.info("Ignoring expired device membership ".concat(g.sender,"/").concat(g.deviceId));continue}if(!e.hasMembershipState((m=g.sender)!==null&&m!==void 0?m:"",Be.Join)){r.info("Ignoring membership of user ".concat(g.sender," who is not in the room."));continue}o.push(g)}catch(y){r.warn("Couldn't construct call membership: ",y)}}}return o.sort((y,v)=>y.createdTs()-v.createdTs()),o.length>1&&r.debug("Call memberships in room ".concat(e.roomId,", in order: "),o.map(y=>[y.createdTs(),y.sender])),o}static roomSessionForRoom(e,n){var r=Zl.sessionMembershipsForRoom(n,{id:"",application:"m.call"});return new Zl(e,n,r,{id:"",application:"m.call"})}static sessionForRoom(e,n,r){var i=Zl.sessionMembershipsForRoom(n,r);return new Zl(e,n,i,r)}get room(){return this.roomSubset}constructor(e,n,r,i){var s;super(),this.client=e,this.roomSubset=n,this.memberships=r,this.sessionDescription=i,L(this,"membershipManager",void 0),L(this,"encryptionManager",void 0),L(this,"_callId",void 0),L(this,"joinConfig",void 0),L(this,"logger",void 0),L(this,"pendingNotificationToSend",void 0),L(this,"expiryTimeout",void 0),L(this,"statistics",{counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}}),L(this,"reEmitter",new $v(this)),L(this,"onRoomMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"onRTCSessionMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"recalculateSessionMembers",()=>{var a,c,l,d=this.memberships;this.memberships=Zl.sessionMembershipsForRoom(this.room,this.sessionDescription),this._callId=(a=this._callId)!==null&&a!==void 0?a:(c=this.memberships[0])===null||c===void 0?void 0:c.sessionDescription.id;var h=d.length!=this.memberships.length||d.some((w,S)=>!X$.equal(w,this.memberships[S]));if(h){var m,g;this.logger.info("Memberships for call in room ".concat(this.roomSubset.roomId," have changed: emitting (").concat(this.memberships.length," members)")),gve(this.logger,"emit MatrixRTCSessionEvent.MembershipsChanged",()=>{this.emit(ei.MembershipsChanged,d,this.memberships)}),(m=this.membershipManager)===null||m===void 0||m.onRTCSessionMemberUpdate(this.memberships);var y=(g=this.membershipManager)===null||g===void 0?void 0:g.ownMembership;if(this.pendingNotificationToSend&&y&&d.length===0){var v;y.eventId&&(v=this.joinConfig)!==null&&v!==void 0&&v.notificationType?this.sendCallNotify(y.eventId,this.joinConfig.notificationType,y.callIntent):this.logger.warn("Own membership eventId is undefined, cannot send call notification")}this.memberships.length>0&&(this.pendingNotificationToSend=void 0)}(l=this.encryptionManager)===null||l===void 0||l.onMembershipsUpdate(d),this.setExpiryTimer()}),this.logger=M.getChild("[MatrixRTCSession ".concat(n.roomId,"]")),this._callId=(s=r[0])===null||s===void 0?void 0:s.sessionDescription.id;var o=this.roomSubset.getLiveTimeline().getState(Me.FORWARDS);o?.on(pt.Members,this.onRoomMemberUpdate),this.setExpiryTimer()}isJoined(){var e,n;return(e=(n=this.membershipManager)===null||n===void 0?void 0:n.isJoined())!==null&&e!==void 0?e:!1}stop(){var e=this;return B(function*(){var n;yield(n=e.membershipManager)===null||n===void 0?void 0:n.leave(1e3),e.expiryTimeout&&(clearTimeout(e.expiryTimeout),e.expiryTimeout=void 0);var r=e.roomSubset.getLiveTimeline().getState(Me.FORWARDS);r?.off(pt.Members,e.onRoomMemberUpdate)})()}joinRoomSession(e,n,r){var i;if(this.isJoined()){this.logger.info("Already joined to session in room ".concat(this.roomSubset.roomId,": ignoring join call"));return}else{this.membershipManager=new fC(r,this.roomSubset,this.client,()=>this.getOldestMembership(),this.sessionDescription,this.logger),this.reEmitter.reEmit(this.membershipManager,[Hh.ProbablyLeft,Hh.StatusChanged]);var s;if(r!=null&&r.useExperimentalToDeviceTransport){this.logger.info("Using experimental to-device transport for encryption keys"),this.logger.info("Using to-device with room fallback transport for encryption keys");var[o,a]=[this.client.getUserId(),this.client.getDeviceId()],[c,l,d]=[this.roomSubset,this.client,this.statistics],h=new Q$(c,l,d),m=new iye(o,a,c.roomId,l,d);s=new n7(m,h,this.logger),this.reEmitter.reEmit(s,[p_.EnabledTransportsChanged]),this.encryptionManager=new aye(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,s,this.statistics,(g,y,v)=>{this.emit(ei.EncryptionKeyChanged,g,y,v)},this.logger)}else s=new Q$(this.roomSubset,this.client,this.statistics),this.encryptionManager=new sye(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,s,this.statistics,(g,y,v)=>{this.emit(ei.EncryptionKeyChanged,g,y,v)})}this.joinConfig=r,this.pendingNotificationToSend=(i=this.joinConfig)===null||i===void 0?void 0:i.notificationType,this.membershipManager.join(e,n,g=>{this.logger.error("MembershipManager encountered an unrecoverable error: ",g),this.emit(ei.MembershipManagerError,g),this.emit(ei.JoinStateChanged,this.isJoined())}),this.encryptionManager.join(r),this.emit(ei.JoinStateChanged,!0)}leaveRoomSession(){var e=arguments,n=this;return B(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:void 0;if(!n.isJoined())return n.logger.info("Not joined to session in room ".concat(n.roomSubset.roomId,": ignoring leave call")),!1;n.logger.info("Leaving call session in room ".concat(n.roomSubset.roomId)),n.encryptionManager.leave();var i=n.membershipManager.leave(r);return n.emit(ei.JoinStateChanged,!1),yield i})()}getActiveFocus(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.getActiveFocus()}getOldestMembership(){return this.memberships[0]}getConsensusCallIntent(){var e,n=(e=this.memberships.find(r=>!!r.callIntent))===null||e===void 0?void 0:e.callIntent;if(n&&this.memberships.every(r=>!r.callIntent||r.callIntent===n))return n}updateCallIntent(e){var n=this;return B(function*(){var r,i,s=(r=n.membershipManager)===null||r===void 0?void 0:r.ownMembership;if(!s)throw Error("Not connected yet");yield(i=n.membershipManager)===null||i===void 0?void 0:i.updateCallIntent(e)})()}getFocusInUse(){var e=this.getOldestMembership();if(e?.getFocusSelection()==="oldest_membership")return e.getPreferredFoci()[0]}reemitEncryptionKeys(){var e;(e=this.encryptionManager)===null||e===void 0||e.getEncryptionKeys().forEach((n,r)=>{n.forEach(i=>{this.emit(ei.EncryptionKeyChanged,i.key,i.keyIndex,r)})})}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);var e;for(var n of this.memberships){var r=n.getMsUntilExpiry();r!==void 0&&(e===void 0||r<e)&&(e=r)}e!=null&&(this.expiryTimeout=setTimeout(this.onRTCSessionMemberUpdate,e))}sendCallNotify(e,n,r){var i=this,s=function(){var a=B(function*(){var c={application:"m.call","m.mentions":{user_ids:[],room:!0},notify_type:n==="notification"?"notify":n,call_id:i.callId},l=yield i.client.sendEvent(i.roomSubset.roomId,Z.CallNotify,c);return{response:l,content:c}});return function(){return a.apply(this,arguments)}}(),o=function(){var a=B(function*(){var c={"m.mentions":{user_ids:[],room:!0},notification_type:n,"m.relates_to":{event_id:e,rel_type:vn.Reference},sender_ts:Date.now(),lifetime:3e4};r&&(c["m.call.intent"]=r);var l=yield i.client.sendEvent(i.roomSubset.roomId,Z.RTCNotification,c);return{response:l,content:c}});return function(){return a.apply(this,arguments)}}();Promise.all([s(),o()]).then(a=>{var[c,l]=a,d=P2(P2({},c.response),c.content),h=P2(P2({},l.response),l.content);this.emit(ei.DidSendCallNotification,h,d)}).catch(a=>{var[c,l]=a;return this.logger.error("Failed to send call notification",c,l)})}}var hC=function(t){return t.SessionStarted="session_started",t.SessionEnded="session_ended",t}({});class cye extends On{constructor(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{id:"",application:"m.call"};super(),this.client=n,this.sessionDescription=r,L(this,"roomSessions",new Map),L(this,"logger",void 0),L(this,"onRoom",i=>{this.refreshRoom(i)}),L(this,"onRoomState",(i,s)=>{var o=this.client.getRoom(i.getRoomId());if(!o){this.logger.error("Got room state event for unknown room ".concat(i.getRoomId(),"!"));return}i.getType()==Z.GroupCallMemberPrefix&&this.refreshRoom(o)}),this.logger=e.getChild("[MatrixRTCSessionManager]")}start(){for(var e of(n=this.client.getRooms())!==null&&n!==void 0?n:[]){var n,r=Zl.sessionForRoom(this.client,e,this.sessionDescription);r.memberships.length>0&&this.roomSessions.set(e.roomId,r)}this.client.on(Le.Room,this.onRoom),this.client.on(pt.Events,this.onRoomState)}stop(){for(var e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(Le.Room,this.onRoom),this.client.off(pt.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,Zl.sessionForRoom(this.client,e,this.sessionDescription)),this.roomSessions.get(e.roomId)}refreshRoom(e){var n=!this.roomSessions.has(e.roomId),r=this.getRoomSession(e),i=r.memberships.length>0&&!n;r.onRTCSessionMemberUpdate();var s=r.memberships.length>0;i&&!s?(this.logger.trace("Session ended for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(hC.SessionEnded,e.roomId,this.roomSessions.get(e.roomId))):!i&&s&&(this.logger.trace("Session started for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(hC.SessionStarted,e.roomId,this.roomSessions.get(e.roomId)))}}function Nk(t){return e=>{var n,r;return((n=e.content)===null||n===void 0||(n=n["m.relates_to"])===null||n===void 0?void 0:n.event_id)!==t||((r=e.content)===null||r===void 0||(r=r["m.relates_to"])===null||r===void 0?void 0:r.rel_type)===wn.name}}function rQ(t){return _A.apply(this,arguments)}function _A(){return _A=B(function*(t){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");var e=new TextEncoder().encode(t),n=yield globalThis.crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}),_A.apply(this,arguments)}class dy extends Error{}dy.prototype.name="InvalidTokenError";function lye(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function uye(t){let e=t.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 lye(e)}catch{return atob(e)}}function iQ(t,e){if(typeof t!="string")throw new dy("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new dy(`Invalid token specified: missing part #${n+1}`);let i;try{i=uye(r)}catch(s){throw new dy(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new dy(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var dye={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Uc,jc,pb=(t=>(t[t.NONE=0]="NONE",t[t.ERROR=1]="ERROR",t[t.WARN=2]="WARN",t[t.INFO=3]="INFO",t[t.DEBUG=4]="DEBUG",t))(pb||{});(t=>{function e(){Uc=3,jc=dye}t.reset=e;function n(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");Uc=i}t.setLevel=n;function r(i){jc=i}t.setLogger=r})(pb||(pb={}));var kr=class Oc{constructor(e){this._name=e}debug(...e){Uc>=4&&jc.debug(Oc._format(this._name,this._method),...e)}info(...e){Uc>=3&&jc.info(Oc._format(this._name,this._method),...e)}warn(...e){Uc>=2&&jc.warn(Oc._format(this._name,this._method),...e)}error(...e){Uc>=1&&jc.error(Oc._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const n=Object.create(this);return n._method=e,n.debug("begin"),n}static createStatic(e,n){const r=new Oc(`${e}.${n}`);return r.debug("begin"),r}static _format(e,n){const r=`[${e}]`;return n?`${r} ${n}:`:r}static debug(e,...n){Uc>=4&&jc.debug(Oc._format(e),...n)}static info(e,...n){Uc>=3&&jc.info(Oc._format(e),...n)}static warn(e,...n){Uc>=2&&jc.warn(Oc._format(e),...n)}static error(e,...n){Uc>=1&&jc.error(Oc._format(e),...n)}};pb.reset();var pC=class{static decode(t){try{return iQ(t)}catch(e){throw kr.error("JwtUtils.decode",e),e}}static async generateSignedJwt(t,e,n){const r=nc.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t))),i=nc.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),s=`${r}.${i}`,o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,new TextEncoder().encode(s)),a=nc.encodeBase64Url(new Uint8Array(o));return`${s}.${a}`}},fye="10000000-1000-4000-8000-100000000000",SA=t=>btoa([...new Uint8Array(t)].map(e=>String.fromCharCode(e)).join("")),sQ=class Mc{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return fye.replace(/[018]/g,n=>(+n^Mc._randomWord()&15>>+n/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return Mc.generateUUIDv4()+Mc.generateUUIDv4()+Mc.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 SA(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(n){throw kr.error("CryptoUtils.generateCodeChallenge",n),n}}static generateBasicAuth(e,n){const i=new TextEncoder().encode([e,n].join(":"));return SA(i)}static async hash(e,n){const r=new TextEncoder().encode(n),i=await crypto.subtle.digest(e,r);return new Uint8Array(i)}static async customCalculateJwkThumbprint(e){let n;switch(e.kty){case"RSA":n={e:e.e,kty:e.kty,n:e.n};break;case"EC":n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":n={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":n={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const r=await Mc.hash("SHA-256",JSON.stringify(n));return Mc.encodeBase64Url(r)}static async generateDPoPProof({url:e,accessToken:n,httpMethod:r,keyPair:i,nonce:s}){let o,a;const c={jti:window.crypto.randomUUID(),htm:r??"GET",htu:e,iat:Math.floor(Date.now()/1e3)};n&&(o=await Mc.hash("SHA-256",n),a=Mc.encodeBase64Url(o),c.ath=a),s&&(c.nonce=s);try{const l=await crypto.subtle.exportKey("jwk",i.publicKey),d={alg:"ES256",typ:"dpop+jwt",jwk:{crv:l.crv,kty:l.kty,x:l.x,y:l.y}};return await pC.generateSignedJwt(d,c,i.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(e){try{const n=await crypto.subtle.exportKey("jwk",e.publicKey);return await Mc.customCalculateJwkThumbprint(n)}catch(n){throw n instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${n.message}`):n}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};sQ.encodeBase64Url=t=>SA(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var nc=sQ,hye=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new kr(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const n=this._callbacks.lastIndexOf(e);n>=0&&this._callbacks.splice(n,1)}async raise(...e){this._logger.debug("raise:",...e);for(const n of this._callbacks)await n(...e)}},mC=class YE extends hye{constructor(){super(...arguments),this._logger=new kr(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-YE.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=YE.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const n=this._logger.create("init");e=Math.max(Math.floor(e),1);const r=YE.getEpochTime()+e;if(this.expiration===r&&this._timerHandle){n.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),n.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)}},eB=class{static readParams(t,e="query"){if(!t)throw new TypeError("Invalid URL");const r=new URL(t,"http://127.0.0.1")[e==="fragment"?"hash":"search"];return new URLSearchParams(r.slice(1))}},EA=";",iv=class extends Error{constructor(t,e){var n,r,i;if(super(t.error_description||t.error||""),this.form=e,this.name="ErrorResponse",!t.error)throw kr.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=t.error,this.error_description=(n=t.error_description)!=null?n:null,this.error_uri=(r=t.error_uri)!=null?r:null,this.state=t.userState,this.session_state=(i=t.session_state)!=null?i:null,this.url_state=t.url_state}},pye=class extends Error{constructor(t){super(t),this.name="ErrorTimeout"}},mye=class{constructor(){this._logger=new kr("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(t){return this._logger.create(`getItem('${t}')`),this._data[t]}setItem(t,e){this._logger.create(`setItem('${t}')`),this._data[t]=e}removeItem(t){this._logger.create(`removeItem('${t}')`),delete this._data[t]}get length(){return Object.getOwnPropertyNames(this._data).length}key(t){return Object.getOwnPropertyNames(this._data)[t]}},wA=class extends Error{constructor(t,e){super(e),this.name="ErrorDPoPNonce",this.nonce=t}},r7=class{constructor(t=[],e=null,n={}){this._jwtHandler=e,this._extraHeaders=n,this._logger=new kr("JsonService"),this._contentTypes=[],this._contentTypes.push(...t,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(t,e={}){const{timeoutInSeconds:n,...r}=e;if(!n)return await fetch(t,r);const i=new AbortController,s=setTimeout(()=>i.abort(),n*1e3);try{return await fetch(t,{...e,signal:i.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new pye("Network timed out"):o}finally{clearTimeout(s)}}async getJson(t,{token:e,credentials:n,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:",t),o=await this.fetchWithTimeout(t,{method:"GET",headers:s,timeoutInSeconds:r,credentials:n})}catch(l){throw i.error("Network Error"),l}i.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(l=>a.startsWith(l))&&i.throw(new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${t}`)),o.ok&&this._jwtHandler&&a?.startsWith("application/jwt"))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(l){throw i.error("Error parsing JSON response",l),o.ok?l:new Error(`${o.statusText} (${o.status})`)}if(!o.ok)throw i.error("Error from server:",c),c.error?new iv(c):new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`);return c}async postForm(t,{body:e,basicAuth:n,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};n!==void 0&&(a.Authorization="Basic "+n),this.appendExtraHeaders(a);let c;try{o.debug("url:",t),c=await this.fetchWithTimeout(t,{method:"POST",headers:a,body:e,timeoutInSeconds:r,credentials:i})}catch(m){throw o.error("Network error"),m}o.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find(m=>l.startsWith(m)))throw new Error(`Invalid response Content-Type: ${l??"undefined"}, from URL: ${t}`);const d=await c.text();let h={};if(d)try{h=JSON.parse(d)}catch(m){throw o.error("Error parsing JSON response",m),c.ok?m:new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",h),c.headers.has("dpop-nonce")){const m=c.headers.get("dpop-nonce");throw new wA(m,`${JSON.stringify(h)}`)}throw h.error?new iv(h,e):new Error(`${c.statusText} (${c.status}): ${JSON.stringify(h)}`)}return h}appendExtraHeaders(t){const e=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["authorization","accept","content-type"];n.length!==0&&n.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!==""&&(t[i]=s)})}},oQ=class{constructor(t){this._settings=t,this._logger=new kr("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new r7(["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 t=this._logger.create("getMetadata");if(this._metadata)return t.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw t.throw(new Error("No authority or metadataUrl configured on settings")),null;t.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.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(t=!0){return this._getMetadataProperty("token_endpoint",t)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(t=!0){return this._getMetadataProperty("revocation_endpoint",t)}getKeysEndpoint(t=!0){return this._getMetadataProperty("jwks_uri",t)}async _getMetadataProperty(t,e=!1){const n=this._logger.create(`_getMetadataProperty('${t}')`),r=await this.getMetadata();if(n.debug("resolved"),r[t]===void 0){if(e===!0){n.warn("Metadata does not contain optional property");return}n.throw(new Error("Metadata does not contain property "+t))}return r[t]}async getSigningKeys(){const t=this._logger.create("getSigningKeys");if(this._signingKeys)return t.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);t.debug("got jwks_uri",e);const n=await this._jsonService.getJson(e,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(t.debug("got key set",n),!Array.isArray(n.keys))throw t.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},rT=class{constructor({prefix:t="oidc.",store:e=localStorage}={}){this._logger=new kr("WebStorageStateStore"),this._store=e,this._prefix=t}async set(t,e){this._logger.create(`set('${t}')`),t=this._prefix+t,await this._store.setItem(t,e)}async get(t){return this._logger.create(`get('${t}')`),t=this._prefix+t,await this._store.getItem(t)}async remove(t){this._logger.create(`remove('${t}')`),t=this._prefix+t;const e=await this._store.getItem(t);return await this._store.removeItem(t),e}async getAllKeys(){this._logger.create("getAllKeys");const t=await this._store.length,e=[];for(let n=0;n<t;n++){const r=await this._store.key(n);r&&r.indexOf(this._prefix)===0&&e.push(r.substr(this._prefix.length))}return e}},gye="code",vye="openid",yye="client_secret_post",bye=60*15,CA=class{constructor({authority:t,metadataUrl:e,metadata:n,signingKeys:r,metadataSeed:i,client_id:s,client_secret:o,response_type:a=gye,scope:c=vye,redirect_uri:l,post_logout_redirect_uri:d,client_authentication:h=yye,prompt:m,display:g,max_age:y,ui_locales:v,acr_values:w,resource:S,response_mode:R,filterProtocolClaims:x=!0,loadUserInfo:T=!1,requestTimeoutInSeconds:I,staleStateAgeInSeconds:k=bye,mergeClaimsStrategy:A={array:"replace"},disablePKCE:O=!1,stateStore:D,revokeTokenAdditionalContentTypes:N,fetchRequestCredentials:U,refreshTokenAllowedScope:$,extraQueryParams:K={},extraTokenParams:Y={},extraHeaders:G={},dpop:F,omitScopeWhenRequesting:q=!1}){var z;if(this.authority=t,e?this.metadataUrl=e:(this.metadataUrl=t,t&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=n,this.metadataSeed=i,this.signingKeys=r,this.client_id=s,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=d,this.client_authentication=h,this.prompt=m,this.display=g,this.max_age=y,this.ui_locales=v,this.acr_values=w,this.resource=S,this.response_mode=R,this.filterProtocolClaims=x??!0,this.loadUserInfo=!!T,this.staleStateAgeInSeconds=k,this.mergeClaimsStrategy=A,this.omitScopeWhenRequesting=q,this.disablePKCE=!!O,this.revokeTokenAdditionalContentTypes=N,this.fetchRequestCredentials=U||"same-origin",this.requestTimeoutInSeconds=I,D)this.stateStore=D;else{const W=typeof window<"u"?window.localStorage:new mye;this.stateStore=new rT({store:W})}if(this.refreshTokenAllowedScope=$,this.extraQueryParams=K,this.extraTokenParams=Y,this.extraHeaders=G,this.dpop=F,this.dpop&&!((z=this.dpop)!=null&&z.store))throw new Error("A DPoPStore is required when dpop is enabled")}},_ye=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new kr("UserInfoService"),this._getClaimsFromJwt=async n=>{const r=this._logger.create("_getClaimsFromJwt");try{const i=pC.decode(n);return r.debug("JWT decoding successful"),i}catch(i){throw r.error("Error parsing JWT response"),i}},this._jsonService=new r7(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(t){const e=this._logger.create("getClaims");t||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",n);const r=await this._jsonService.getJson(n,{token:t,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("got claims",r),r}},aQ=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new kr("TokenClient"),this._jsonService=new r7(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:t="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:i,...s}){const o=this._logger.create("exchangeCode");n||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:t,redirect_uri:e});for(const[h,m]of Object.entries(s))m!=null&&a.set(h,m);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw o.throw(new Error("A client_secret is required")),null;c=nc.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r);break}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),d}async exchangeCredentials({grant_type:t="password",client_id:e=this._settings.client_id,client_secret:n=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:t});this._settings.omitScopeWhenRequesting||o.set("scope",r);for(const[d,h]of Object.entries(i))h!=null&&o.set(d,h);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw s.throw(new Error("A client_secret is required")),null;a=nc.generateBasicAuth(e,n);break;case"client_secret_post":o.append("client_id",e),n&&o.append("client_secret",n);break}const c=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return s.debug("got response"),l}async exchangeRefreshToken({grant_type:t="refresh_token",client_id:e=this._settings.client_id,client_secret:n=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:t});for(const[h,m]of Object.entries(s))Array.isArray(m)?m.forEach(g=>a.append(h,g)):m!=null&&a.set(h,m);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw o.throw(new Error("A client_secret is required")),null;c=nc.generateBasicAuth(e,n);break;case"client_secret_post":a.append("client_id",e),n&&a.append("client_secret",n);break}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),d}async revoke(t){var e;const n=this._logger.create("revoke");t.token||n.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${(e=t.token_type_hint)!=null?e:"default token type"}`);const i=new URLSearchParams;for(const[s,o]of Object.entries(t))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}),n.debug("got response")}},Sye=class{constructor(t,e,n){this._settings=t,this._metadataService=e,this._claimsService=n,this._logger=new kr("ResponseValidator"),this._userInfoService=new _ye(this._settings,this._metadataService),this._tokenClient=new aQ(this._settings,this._metadataService)}async validateSigninResponse(t,e,n){const r=this._logger.create("validateSigninResponse");this._processSigninState(t,e),r.debug("state processed"),await this._processCode(t,e,n),r.debug("code processed"),t.isOpenId&&this._validateIdTokenAttributes(t),r.debug("tokens validated"),await this._processClaims(t,e?.skipUserInfo,t.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(t,e){const n=this._logger.create("validateCredentialsResponse");t.isOpenId&&t.id_token&&this._validateIdTokenAttributes(t),n.debug("tokens validated"),await this._processClaims(t,e,t.isOpenId),n.debug("claims processed")}async validateRefreshResponse(t,e){var n,r;const i=this._logger.create("validateRefreshResponse");t.userState=e.data,(n=t.session_state)!=null||(t.session_state=e.session_state),(r=t.scope)!=null||(t.scope=e.scope),t.isOpenId&&t.id_token&&(this._validateIdTokenAttributes(t,e.id_token),i.debug("ID Token validated")),t.id_token||(t.id_token=e.id_token,t.profile=e.profile);const s=t.isOpenId&&!!t.id_token;await this._processClaims(t,!1,s),i.debug("claims processed")}validateSignoutResponse(t,e){const n=this._logger.create("validateSignoutResponse");if(e.id!==t.state&&n.throw(new Error("State does not match")),n.debug("state validated"),t.userState=e.data,t.error)throw n.warn("Response was error",t.error),new iv(t)}_processSigninState(t,e){var n;const r=this._logger.create("_processSigninState");if(e.id!==t.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"),t.userState=e.data,t.url_state=e.url_state,(n=t.scope)!=null||(t.scope=e.scope),t.error)throw r.warn("Response was error",t.error),new iv(t);e.code_verifier&&!t.code&&r.throw(new Error("Expected code in response"))}async _processClaims(t,e=!1,n=!0){const r=this._logger.create("_processClaims");if(t.profile=this._claimsService.filterProtocolClaims(t.profile),e||!this._settings.loadUserInfo||!t.access_token){r.debug("not loading user info");return}r.debug("loading user info");const i=await this._userInfoService.getClaims(t.access_token);r.debug("user info claims received from user info endpoint"),n&&i.sub!==t.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),t.profile=this._claimsService.mergeClaims(t.profile,this._claimsService.filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",t.profile)}async _processCode(t,e,n){const r=this._logger.create("_processCode");if(t.code){r.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:t.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,extraHeaders:n,...e.extraTokenParams});Object.assign(t,i)}else r.debug("No code to process")}_validateIdTokenAttributes(t,e){var n;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=pC.decode((n=t.id_token)!=null?n:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),e){const s=pC.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"))}t.profile=i}},gC=class TA{constructor(e){this.id=e.id||nc.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=mC.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new kr("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 kr.createStatic("State","fromStorageString"),Promise.resolve(new TA(JSON.parse(e)))}static async clearStaleState(e,n){const r=kr.createStatic("State","clearStaleState"),i=mC.getEpochTime()-n,s=await e.getAllKeys();r.debug("got keys",s);for(let o=0;o<s.length;o++){const a=s[o],c=await e.get(a);let l=!1;if(c)try{const d=await TA.fromStorageString(c);r.debug("got item from key:",a,d.created),d.created<=i&&(l=!0)}catch(d){r.error("Error parsing state for key:",a,d),l=!0}else r.debug("no item in storage for key:",a),l=!0;l&&(r.debug("removed item for key:",a),e.remove(a))}}},i7=class RA extends gC{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 n=e.code_verifier===!0?nc.generateCodeVerifier():e.code_verifier||void 0,r=n?await nc.generateCodeChallenge(n):void 0;return new RA({...e,code_verifier:n,code_challenge:r})}toStorageString(){return new kr("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){kr.createStatic("SigninState","fromStorageString");const n=JSON.parse(e);return RA.create(n)}},cQ=class lQ{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:n,client_id:r,redirect_uri:i,response_type:s,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:d,nonce:h,url_state:m,resource:g,skipUserInfo:y,extraQueryParams:v,extraTokenParams:w,disablePKCE:S,dpopJkt:R,omitScopeWhenRequesting:x,...T}){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(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const I=await i7.create({data:a,request_type:l,url_state:m,code_verifier:!S,client_id:r,authority:n,redirect_uri:i,response_mode:c,client_secret:d,scope:o,extraTokenParams:w,skipUserInfo:y}),k=new URL(e);k.searchParams.append("client_id",r),k.searchParams.append("redirect_uri",i),k.searchParams.append("response_type",s),x||k.searchParams.append("scope",o),h&&k.searchParams.append("nonce",h),R&&k.searchParams.append("dpop_jkt",R);let A=I.id;m&&(A=`${A}${EA}${m}`),k.searchParams.append("state",A),I.code_challenge&&(k.searchParams.append("code_challenge",I.code_challenge),k.searchParams.append("code_challenge_method","S256")),g&&(Array.isArray(g)?g:[g]).forEach(D=>k.searchParams.append("resource",D));for(const[O,D]of Object.entries({response_mode:c,...T,...v}))D!=null&&k.searchParams.append(O,D.toString());return new lQ({url:k.href,state:I})}};cQ._logger=new kr("SigninRequest");var Eye=cQ,wye="openid",XE=class{constructor(t){if(this.access_token="",this.token_type="",this.profile={},this.state=t.get("state"),this.session_state=t.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(EA);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(EA))}this.error=t.get("error"),this.error_description=t.get("error_description"),this.error_uri=t.get("error_uri"),this.code=t.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-mC.getEpochTime()}set expires_in(t){typeof t=="string"&&(t=Number(t)),t!==void 0&&t>=0&&(this.expires_at=Math.floor(t)+mC.getEpochTime())}get isOpenId(){var t;return((t=this.scope)==null?void 0:t.split(" ").includes(wye))||!!this.id_token}},Cye=class{constructor({url:t,state_data:e,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:i,request_type:s,client_id:o}){if(this._logger=new kr("SignoutRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");const a=new URL(t);n&&a.searchParams.append("id_token_hint",n),o&&a.searchParams.append("client_id",o),r&&(a.searchParams.append("post_logout_redirect_uri",r),e&&(this.state=new gC({data:e,request_type:s}),a.searchParams.append("state",this.state.id)));for(const[c,l]of Object.entries({...i}))l!=null&&a.searchParams.append(c,l.toString());this.url=a.href}},Tye=class{constructor(t){this.state=t.get("state"),this.error=t.get("error"),this.error_description=t.get("error_description"),this.error_uri=t.get("error_uri")}},Rye=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Iye=["sub","iss","aud","exp","iat"],kye=class{constructor(t){this._settings=t,this._logger=new kr("ClaimsService")}filterProtocolClaims(t){const e={...t};if(this._settings.filterProtocolClaims){let n;Array.isArray(this._settings.filterProtocolClaims)?n=this._settings.filterProtocolClaims:n=Rye;for(const r of n)Iye.includes(r)||delete e[r]}return e}mergeClaims(t,e){const n={...t};for(const[r,i]of Object.entries(e))if(n[r]!==i)if(Array.isArray(n[r])||Array.isArray(i))if(this._settings.mergeClaimsStrategy.array=="replace")n[r]=i;else{const s=Array.isArray(n[r])?n[r]:[n[r]];for(const o of Array.isArray(i)?i:[i])s.includes(o)||s.push(o);n[r]=s}else typeof n[r]=="object"&&typeof i=="object"?n[r]=this.mergeClaims(n[r],i):n[r]=i;return n}},xye=class{constructor(t,e){this.keys=t,this.nonce=e}},s7=class{constructor(t,e){this._logger=new kr("OidcClient"),this.settings=t instanceof CA?t:new CA(t),this.metadataService=e??new oQ(this.settings),this._claimsService=new kye(this.settings),this._validator=new Sye(this.settings,this.metadataService,this._claimsService),this._tokenClient=new aQ(this.settings,this.metadataService)}async createSigninRequest({state:t,request:e,request_uri:n,request_type:r,id_token_hint:i,login_hint:s,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:d=this.settings.scope,redirect_uri:h=this.settings.redirect_uri,prompt:m=this.settings.prompt,display:g=this.settings.display,max_age:y=this.settings.max_age,ui_locales:v=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:S=this.settings.resource,response_mode:R=this.settings.response_mode,extraQueryParams:x=this.settings.extraQueryParams,extraTokenParams:T=this.settings.extraTokenParams,dpopJkt:I,omitScopeWhenRequesting:k=this.settings.omitScopeWhenRequesting}){const A=this._logger.create("createSigninRequest");if(l!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const O=await this.metadataService.getAuthorizationEndpoint();A.debug("Received authorization endpoint",O);const D=await Eye.create({url:O,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:h,response_type:l,scope:d,state_data:t,url_state:c,prompt:m,display:g,max_age:y,ui_locales:v,id_token_hint:i,login_hint:s,acr_values:w,dpopJkt:I,resource:S,request:e,request_uri:n,extraQueryParams:x,extraTokenParams:T,request_type:r,response_mode:R,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:k});await this.clearStaleState();const N=D.state;return await this.settings.stateStore.set(N.id,N.toStorageString()),D}async readSigninResponseState(t,e=!1){const n=this._logger.create("readSigninResponseState"),r=new XE(eB.readParams(t,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await i7.fromStorageString(i),response:r}}async processSigninResponse(t,e){const n=this._logger.create("processSigninResponse"),{state:r,response:i}=await this.readSigninResponseState(t,!0);if(n.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 wA&&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(t,e){let n,r;return(await t.getAllKeys()).includes(this.settings.client_id)?(r=await t.get(this.settings.client_id),r.nonce!==e&&e&&(r.nonce=e,await t.set(this.settings.client_id,r))):(n=await nc.generateDPoPKeys(),r=new xye(n,e),await t.set(this.settings.client_id,r)),await nc.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:t,password:e,skipUserInfo:n=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:t,password:e,...r}),s=new XE(new URLSearchParams);return Object.assign(s,i),await this._validator.validateCredentialsResponse(s,n),s}async useRefreshToken({state:t,redirect_uri:e,resource:n,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:s}){var o;const a=this._logger.create("useRefreshToken");let c;if(this.settings.refreshTokenAllowedScope===void 0)c=t.scope;else{const h=this.settings.refreshTokenAllowedScope.split(" ");c=(((o=t.scope)==null?void 0:o.split(" "))||[]).filter(g=>h.includes(g)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const h=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:h}}let l;try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:c,redirect_uri:e,resource:n,timeoutInSeconds:r,extraHeaders:i,...s})}catch(h){if(h instanceof wA&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,h.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:c,redirect_uri:e,resource:n,timeoutInSeconds:r,extraHeaders:i,...s});else throw h}const d=new XE(new URLSearchParams);return Object.assign(d,l),a.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...t,scope:c}),d}async createSignoutRequest({state:t,id_token_hint:e,client_id:n,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),!n&&i&&!e&&(n=this.settings.client_id);const c=new Cye({url:a,id_token_hint:e,client_id:n,post_logout_redirect_uri:i,state_data:t,extraQueryParams:s,request_type:r});await this.clearStaleState();const l=c.state;return l&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),c}async readSignoutResponseState(t,e=!1){const n=this._logger.create("readSignoutResponseState"),r=new Tye(eB.readParams(t,this.settings.response_mode));if(!r.state){if(n.debug("No state in response"),r.error)throw n.warn("Response was error:",r.error),new iv(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await gC.fromStorageString(i),response:r}}async processSignoutResponse(t){const e=this._logger.create("processSignoutResponse"),{state:n,response:r}=await this.readSignoutResponseState(t,!0);return n?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,n)):e.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),gC.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(t,e){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:t,token_type_hint:e})}},ts=function(t){return t.NotSupported="OIDC authentication not supported",t.Misconfigured="OIDC is misconfigured",t.General="Something went wrong with OIDC discovery",t.OpSupport="Configured OIDC OP does not support required functions",t.DynamicRegistrationNotSupported="Dynamic registration not supported",t.DynamicRegistrationFailed="Dynamic registration failed",t.DynamicRegistrationInvalid="Dynamic registration invalid response",t.CodeExchangeFailed="Failed to exchange code for token",t.InvalidBearerTokenResponse="Invalid bearer token response",t.InvalidIdToken="Invalid ID token",t.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",t}({}),o7=t=>!!t&&typeof t=="object"&&!Array.isArray(t),mu=(t,e)=>!t[e]||!ky(t,e)?(M.error("Missing or invalid property: ".concat(e)),!1):!0,ky=(t,e)=>t[e]&&typeof t[e]!="string"?(M.error("Invalid property: ".concat(e)),!1):!0,tB=(t,e)=>t[e]&&(!Array.isArray(t[e])||!t[e].every(n=>typeof n=="string"))?(M.error("Invalid property: ".concat(e)),!1):!0,Uk=(t,e,n)=>{var r=t[e];return!r||!Array.isArray(r)||!r.includes(n)?(M.error("Invalid property: ".concat(e,". ").concat(n," is required.")),!1):!0},uQ=t=>{if(!o7(t))throw M.error("Issuer configuration not found or malformed"),new Error(ts.OpSupport);var e=[mu(t,"issuer"),mu(t,"authorization_endpoint"),mu(t,"token_endpoint"),mu(t,"revocation_endpoint"),ky(t,"registration_endpoint"),ky(t,"account_management_uri"),ky(t,"device_authorization_endpoint"),tB(t,"account_management_actions_supported"),Uk(t,"response_types_supported","code"),Uk(t,"grant_types_supported","authorization_code"),Uk(t,"code_challenge_methods_supported","S256"),tB(t,"prompt_values_supported")].some(n=>!n);if(!e)return t;throw M.error("Issuer configuration not valid"),new Error(ts.OpSupport)},dQ=t=>{try{return iQ(t)}catch(e){throw M.error("Could not decode id_token",e),e}},fQ=(t,e,n,r)=>{try{if(!t)throw new Error("No ID token");var i=dQ(t);if(i.iss!==e)throw new Error("Invalid issuer");var s=typeof i.aud=="string"?[i.aud]:i.aud;if(!s.includes(n))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 M.error("Invalid ID token",o),new Error(ts.InvalidIdToken)}};function hQ(t){if(!o7(t))throw M.error("Stored user state not found"),new Error(ts.MissingOrInvalidStoredState);var e=[mu(t,"homeserverUrl"),mu(t,"nonce"),ky(t,"identityServerUrl")].some(n=>!n);if(e)throw new Error(ts.MissingOrInvalidStoredState)}var Aye=t=>o7(t)&&mu(t,"token_type")&&t.token_type.toLowerCase()==="bearer"&&mu(t,"access_token")&&mu(t,"refresh_token")&&(!("expires_in"in t)||typeof t.expires_in=="number");function pQ(t){if(!Aye(t))throw new Error(ts.InvalidBearerTokenResponse)}function nB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function vC(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?nB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):nB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var iT=t=>{var e=t??To(10);return"openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:".concat(e)},Pye=function(){var t=B(function*(e){if(!globalThis.crypto.subtle)return M.warn("A secure context is required to generate code challenge. Using plain text code challenge"),e;var n=yield rQ(e);return Z3(n)});return function(n){return t.apply(this,arguments)}}(),Lye=t=>{var{redirectUri:e}=t;return{scope:iT(),redirectUri:e,state:To(8),nonce:To(8),codeVerifier:To(64)}},Oye=function(){var t=B(function*(e,n,r){var{scope:i,redirectUri:s,state:o,nonce:a,codeVerifier:c}=r,l=new URL(e);return l.searchParams.append("response_mode","query"),l.searchParams.append("response_type","code"),l.searchParams.append("redirect_uri",s),l.searchParams.append("client_id",n),l.searchParams.append("state",o),l.searchParams.append("scope",i),l.searchParams.append("nonce",a),l.searchParams.append("code_challenge_method","S256"),l.searchParams.append("code_challenge",yield Pye(c)),l.toString()});return function(n,r,i){return t.apply(this,arguments)}}(),Mye=function(){var t=B(function*(e){var{metadata:n,redirectUri:r,clientId:i,homeserverUrl:s,identityServerUrl:o,nonce:a,prompt:c,urlState:l,loginHint:d}=e,h=iT(),m=new s7(vC(vC({},n),{},{client_id:i,redirect_uri:r,authority:n.issuer,response_mode:"query",response_type:"code",scope:h,stateStore:new rT({prefix:"mx_oidc_",store:window.sessionStorage})})),g={homeserverUrl:s,nonce:a,identityServerUrl:o},y=yield m.createSigninRequest({state:g,nonce:a,prompt:c,url_state:l,login_hint:d});return y.url});return function(n){return t.apply(this,arguments)}}(),Dye=t=>({id_token:t.id_token,scope:t.scope,expires_at:t.expires_at,refresh_token:t.refresh_token,access_token:t.access_token,token_type:"Bearer"}),Nye=function(){var t=B(function*(e,n){var r=new URL(window.location.origin);r.searchParams.append("code",e),r.searchParams.append("state",n),pb.setLogger(M);try{var i=new XE(r.searchParams),s=new rT({prefix:"mx_oidc_",store:window.sessionStorage}),o=yield s.get(i.state);if(!o)throw new Error(ts.MissingOrInvalidStoredState);var a=yield i7.fromStorageString(o),c=new s7(vC(vC({},a),{},{stateStore:s})),l=yield c.processSigninResponse(r.href),d=l.userState;hQ(d),pQ(l),fQ(l.id_token,c.settings.authority,c.settings.client_id,d.nonce);var h=Dye(l);return{oidcClientSettings:{clientId:c.settings.client_id,issuer:c.settings.authority},tokenResponse:h,homeserverUrl:d.homeserverUrl,identityServerUrl:d.identityServerUrl,idTokenClaims:l.profile}}catch(g){M.error("Oidc login failed",g);var m=g.message;throw Object.values(ts).includes(m)?g:new Error(ts.CodeExchangeFailed)}});return function(n,r){return t.apply(this,arguments)}}();function rB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function iB(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?rB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):rB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var a7=function(){var t=B(function*(e){var n=new URL(".well-known/openid-configuration",e),r=yield fetch(n,{method:de.Get,signal:J3(5e3)}),i=yield r.json();return c7(i)});return function(n){return t.apply(this,arguments)}}(),c7=function(){var t=B(function*(e){var n=uQ(e),r=new CA({authority:n.issuer,metadata:n,redirect_uri:"",client_id:""}),i=new oQ(r);return iB(iB({},n),{},{signingKeys:yield i.getSigningKeys()})});return function(n){return t.apply(this,arguments)}}(),Uye="urn:ietf:params:oauth:grant-type:device_code",jk=(t,e)=>{if(!e)return!1;var n=new URL(e);return!(n.protocol!==t.protocol||n.hostname!==t.hostname&&!n.hostname.endsWith(".".concat(t.hostname)))},jye=function(){var t=B(function*(e,n){if(!e.registration_endpoint)throw new Error(ts.DynamicRegistrationNotSupported);var r=["authorization_code","refresh_token"];if(r.some(d=>!e.grant_types_supported.includes(d)))throw new Error(ts.DynamicRegistrationNotSupported);var i=new URL(n.clientUri),s={client_name:n.clientName,client_uri:n.clientUri,response_types:["code"],grant_types:r,redirect_uris:n.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:n.applicationType,contacts:n.contacts,logo_uri:jk(i,n.logoUri)?n.logoUri:void 0,policy_uri:jk(i,n.policyUri)?n.policyUri:void 0,tos_uri:jk(i,n.tosUri)?n.tosUri:void 0},o={Accept:"application/json","Content-Type":"application/json"};try{var a=yield fetch(e.registration_endpoint,{method:de.Post,headers:o,body:JSON.stringify(s)});if(a.status>=400)throw new Error(ts.DynamicRegistrationFailed);var c=yield a.json(),l=c.client_id;if(!l||typeof l!="string")throw new Error(ts.DynamicRegistrationInvalid);return l}catch(d){throw Object.values(ts).includes(d.message)?d:(M.error("Dynamic registration request failed",d),new Error(ts.DynamicRegistrationFailed))}});return function(n,r){return t.apply(this,arguments)}}();class Fye{constructor(e,n,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,n,i,r)}initialiseOidcClient(e,n,r,i){var s=this;return B(function*(){try{var o,a=yield a7(e),c=iT(r);s.oidcClient=new s7({metadata:a,signingKeys:(o=a.signingKeys)!==null&&o!==void 0?o:void 0,client_id:n,scope:c,redirect_uri:i,authority:a.issuer,stateStore:new rT({prefix:"mx_oidc_",store:window.sessionStorage})})}catch(l){throw M.error("Failed to initialise OIDC client.",l),new Error("Failed to initialise OIDC client.")}})()}doRefreshAccessToken(e){var n=this;return B(function*(){n.inflightRefreshRequest||(n.inflightRefreshRequest=n.getNewTokens(e));try{var r=yield n.inflightRefreshRequest;return r}catch(i){throw i instanceof iv?new VO(i):i}finally{n.inflightRefreshRequest=void 0}})()}persistTokens(e){return B(function*(){})()}getNewTokens(e){var n=this;return B(function*(){if(!n.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:n.idTokenClaims},i=Date.now(),s=yield n.oidcClient.useRefreshToken({state:r,timeoutInSeconds:300}),o={accessToken:s.access_token,refreshToken:s.refresh_token,expiry:s.expires_in?new Date(i+s.expires_in*1e3):void 0};return yield n.persistTokens(o),o})()}}var $ye=["server","limit","since"];function sB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Yr(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?sB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):sB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var Bye=3e3,oB=10*60*1e3,Hye=new Ar("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent"),sv=function(t){return t.Chronological="chronological",t.Detached="detached",t}({}),Vye=new a_("m.get_login_token","org.matrix.msc3882.get_login_token"),mQ="uk.half-shot.msc2666",gQ="uk.half-shot.msc2666.mutual_rooms",vQ="uk.half-shot.msc2666.query_mutual_rooms",Vc="org.matrix.msc4140",yQ="uk.tcpip.msc4133",bQ="uk.tcpip.msc4133.stable",Cc="$",Le=function(t){return t.Sync="sync",t.Event="event",t.ToDeviceEvent="toDeviceEvent",t.ReceivedToDeviceMessage="receivedToDeviceMessage",t.AccountData="accountData",t.Room="Room",t.DeleteRoom="deleteRoom",t.SyncUnexpectedError="sync.unexpectedError",t.ClientWellKnown="WellKnown.client",t.ReceivedVoipEvent="received_voip_event",t.TurnServers="turnServers",t.TurnServersError="turnServers.error",t}({}),qye=new Ar("action","org.matrix.msc3824.action");class sT extends On{constructor(e){var n,r,i,s,o;super(),i=this,L(this,"logger",void 0),L(this,"reEmitter",new $v(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,"enableEncryptedStateEvents",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 qa(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 M1e(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()&&(dA()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off(Le.Sync,this.startCallEventHandler))}),L(this,"startMatrixRTC",()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off(Le.Sync,this.startMatrixRTC))}),L(this,"fixupRoomNotifications",()=>{if(this.isInitialSyncComplete()){var c,l=((c=this.getRooms())!==null&&c!==void 0?c:[]).filter(m=>m.getUnreadNotificationCount(Jt.Total)>0);for(var d of l){var h=this.getSafeUserId();d.fixupNotifications(h)}this.off(Le.Sync,this.fixupRoomNotifications)}}),this.logger=(n=e.logger)!==null&&n!==void 0?n:M,e.baseUrl=Ek(e.baseUrl),e.idBaseUrl=Ek(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 N0e,this.deviceId=e.deviceId||null,this.sessionId=To(10);var a=e.userId||null;this.credentials={userId:a},this.http=new PJ(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:Xr.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 c=B(function*(l){var d=i.getRoom(l.getRoomId());l.status!==rt.SENDING&&i.updatePendingEventStatus(d,l,rt.SENDING);var h=yield i.sendEventHttpRequest(l);return d&&d.updatePendingEvent(l,rt.SENT,h.event_id),h});return function(l){return c.apply(this,arguments)}}()),dA()&&(this.callEventHandler=new n1e(this),this.groupCallEventHandler=new r1e(this),this.canSupportVoip=!0,this.on(Le.Sync,this.startCallEventHandler)),this.matrixRTC=new cye(this.logger,this),this.serverCapabilitiesService=new OJ(this.logger,this.http),this.on(Le.Sync,this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.legacyCryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.enableEncryptedStateEvents=(s=e.enableEncryptedStateEvents)!==null&&s!==void 0?s:!1,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 H1e(this,this.logger),this.on(Kt.Decrypted,c=>{_Q(this,c)}),this.ignoredInvites=new V1e(this),this._secretStorage=new JJ(this,(o=e.cryptoCallbacks)!==null&&o!==void 0?o:{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(n=>yu.createUser(n,this))}get store(){return this._store}startClient(e){var n=this;return B(function*(){if(!n.clientRunning){n.clientRunning=!0,n.on(Le.Sync,n.startMatrixRTC);var r=n.getUserId();r&&n.store.storeUser(new yu(r)),n.canSupportVoip&&(n.checkTurnServersIntervalID=setInterval(()=>{n.checkTurnServers()},oB),n.checkTurnServers()),n.syncApi&&(n.logger.error("Still have sync object whilst not running: stopping old one"),n.syncApi.stop());try{yield n.getVersions();var{threads:i,list:s,fwdPagination:o}=yield n.doesServerSupportThread();Un.setServerSideSupport(i),Un.setServerSideListSupport(s),Un.setServerSideFwdPaginationSupport(o)}catch(a){n.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",a)}n.clientOpts=e??{},n.clientOpts.slidingSync?n.syncApi=new zJ(n.clientOpts.slidingSync,n,n.clientOpts,n.buildSyncApiOptions()):n.syncApi=new Vd(n,n.clientOpts,n.buildSyncApiOptions()),n.syncApi.sync().catch(a=>n.logger.info("Sync startup aborted with an error:",a)),n.clientOpts.clientWellKnownPollPeriod!==void 0&&(n.clientWellKnownIntervalID=setInterval(()=>{n.fetchClientWellKnown()},1e3*n.clientOpts.clientWellKnownPollPeriod),n.fetchClientWellKnown()),n.toDeviceMessageQueue.start(),n.serverCapabilitiesService.start()}})()}buildSyncApiOptions(){return{cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1,logger:this.logger.getChild("sync")}}stopClient(){var e,n,r,i,s;(e=this.cryptoBackend)===null||e===void 0||e.stop(),this.off(Le.Sync,this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(n=this.syncApi)===null||n===void 0||n.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,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.clientRunning)throw new Error("Cannot clear stores while client is running");var r=[];r.push(this.store.deleteAllData()),this.legacyCryptoStore&&r.push(this.legacyCryptoStore.deleteAllData());var i=function(){var s=B(function*(){var o;try{if(o=globalThis.indexedDB,!o)return}catch{return}var a=function*(m){var g=new Promise((y,v)=>{e.logger.info("Removing IndexedDB instance ".concat(m));var w=o.deleteDatabase(m);w.onsuccess=S=>{e.logger.info("Removed IndexedDB instance ".concat(m)),y(0)},w.onerror=S=>{e.logger.warn("Failed to remove IndexedDB instance ".concat(m,":"),S),y(0)},w.onblocked=S=>{e.logger.info("cannot yet remove IndexedDB instance ".concat(m))}});yield g};for(var c of["".concat((l=n.cryptoDatabasePrefix)!==null&&l!==void 0?l:Ok,"::matrix-sdk-crypto"),"".concat((d=n.cryptoDatabasePrefix)!==null&&d!==void 0?d:Ok,"::matrix-sdk-crypto-meta")]){var l,d;yield*a(c)}});return function(){return s.apply(this,arguments)}}();return r.push(i()),Promise.all(r).then()}getUserId(){var e,n;return(e=(n=this.credentials)===null||n===void 0?void 0:n.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,n;return(e=(n=this.credentials)===null||n===void 0||(n=n.userId)===null||n===void 0?void 0:n.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 fb(this,e)}createGroupCall(e,n,r,i,s,o){var a=this;return B(function*(){if(a.getGroupCallForRoom(e))throw new Error("".concat(e," already has an existing group call"));var c=a.getRoom(e);if(!c)throw new Error("Cannot find room ".concat(e));return new YO(a,c,n,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,n;return(e=(n=this.syncApi)===null||n===void 0?void 0:n.getSyncState())!==null&&e!==void 0?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){var e=this.getSyncState();return e?e===Gt.Prepared||e===Gt.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,n;return this.toDeviceMessageQueue.sendQueue(),(e=(n=this.syncApi)===null||n===void 0?void 0:n.retryImmediately())!==null&&e!==void 0?e:!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(){var e=this;return B(function*(){var n=e.serverCapabilitiesService.getCachedCapabilities();return n||e.serverCapabilitiesService.fetchCapabilities()})()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}initRustCrypto(){var e=arguments,n=this;return B(function*(){var r,i,s=e.length>0&&e[0]!==void 0?e[0]:{};if(n.cryptoBackend){n.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}var o=n.getUserId();if(o===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");var a=n.getDeviceId();if(a===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");n.logger.debug("Downloading Rust crypto library");var c=yield lb(()=>import("./index-jvuzG61C.js"),__vite__mapDeps([0,1]),import.meta.url),l=yield c.initRustCrypto({logger:n.logger,http:n.http,userId:o,deviceId:a,secretStorage:n.secretStorage,cryptoCallbacks:n.cryptoCallbacks,storePrefix:s.useIndexedDB===!1?null:(r=s.cryptoDatabasePrefix)!==null&&r!==void 0?r:Ok,storeKey:s.storageKey,storePassphrase:s.storagePassword,legacyCryptoStore:n.legacyCryptoStore,legacyPickleKey:(i=n.legacyPickleKey)!==null&&i!==void 0?i:"DEFAULT_KEY",legacyMigrationProgressListener:(d,h)=>{n.emit(gi.LegacyCryptoStoreMigrationProgress,d,h)},enableEncryptedStateEvents:n.enableEncryptedStateEvents});l.setSupportedVerificationMethods(n.verificationMethods),n.cryptoBackend=l,n.on(Vs.Membership,l.onRoomMembership.bind(l)),n.on(Le.Event,d=>{l.onLiveEventFromSync(d)}),n.reEmitter.reEmit(l,[gi.VerificationRequestReceived,gi.UserTrustStatusChanged,gi.KeyBackupStatus,gi.KeyBackupSessionsRemaining,gi.KeyBackupFailed,gi.KeyBackupDecryptionKeyCached,gi.KeysChanged,gi.DevicesUpdated,gi.WillUpdateDevices,gi.DehydratedDeviceCreated,gi.DehydratedDeviceUploaded,gi.RehydrationStarted,gi.RehydrationProgress,gi.RehydrationCompleted,gi.RehydrationError,gi.DehydrationKeyCached,gi.DehydratedDeviceRotationError])})()}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isRoomEncrypted(e){var n=this.getRoom(e);return n?n.hasEncryptionStateEvent():!1}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}makeKeyBackupPath(e,n,r){var i;n!==void 0?i=xe("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:n}):e!==void 0?i=xe("/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,n,r){var i=this;return B(function*(){var s=i.makeKeyBackupPath(e,n,r);yield i.http.authedRequest(de.Delete,s.path,s.queryData,void 0,{prefix:Xr.V3})})()}getMediaConfig(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=e?"/media/config":"/config";return this.http.authedRequest(de.Get,n,void 0,void 0,{prefix:e?Xr.V1:Cg.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,n=this.store.getRooms(),r=new Set(n);for(var i of r){var s=this.findPredecessorRooms(i,!0,e);for(var o of s)r.delete(o)}return Array.from(r)}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,n){var r=this;return B(function*(){if(!r.clientRunning)return r.logger.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results."),yield nA(5,()=>r.setAccountDataRaw(e,n));var i=r.store.getAccountData(e);if(i&&ff(i.event.content,n))return{};var s=Promise.withResolvers();function o(c){c.getType()===e&&s.resolve()}r.addListener(Le.AccountData,o);try{var a=yield nA(5,()=>r.setAccountDataRaw(e,n));return yield s.promise,a}finally{r.removeListener(Le.AccountData,o)}})()}setAccountDataRaw(e,n){var r=xe("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this.http.authedRequest(de.Put,r,void 0,n)}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var n=this;return B(function*(){if(n.isInitialSyncComplete()){var r=n.store.getAccountData(e);return r?r.getContent():null}var i=xe("/user/$userId/account_data/$type",{$userId:n.credentials.userId,$type:e});try{return yield n.http.authedRequest(de.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 n=this;return B(function*(){var r=n.canSupport.get(ti.AccountDataDeletion);if(r===Zr.Unsupported){yield n.setAccountData(e,{});return}var i=xe("/user/$userId/account_data/$type",{$userId:n.getSafeUserId(),$type:e}),s=r===Zr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield n.http.authedRequest(de.Delete,i,void 0,void 0,s)})()}getIgnoredUsers(){var e=this.getAccountData(Z.IgnoredUserList);return e!=null&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){var n={ignored_users:{}};return e.forEach(r=>{n.ignored_users[r]={}}),this.setAccountData(Z.IgnoredUserList,n)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e){var n=arguments,r=this;return B(function*(){var i,s,o=n.length>1&&n[1]!==void 0?n[1]:{},a=r.getRoom(e),c=a?.getMember(r.getSafeUserId()),l=c?.membership,d=l==Be.Invite&&(i=c==null||(s=c.events.member)===null||s===void 0?void 0:s.getSender())!==null&&i!==void 0?i:null;if(r.logger.debug("joinRoom[".concat(e,"]: preJoinMembership=").concat(l,", inviter=").concat(d,", opts=").concat(JSON.stringify(o))),l==Be.Join)return a;var h=Promise.resolve();if(o.inviteSignUrl){var m=new URL(o.inviteSignUrl);m.searchParams.set("mxid",r.credentials.userId),h=r.http.requestOtherUrl(de.Post,m)}var g={};o.viaServers&&(g.server_name=o.viaServers,g.via=o.viaServers);var y={},v=yield h;v&&(y.third_party_signed=v);var w=xe("/join/$roomid",{$roomid:e}),S=yield r.http.authedRequest(de.Post,w,g,y),R=S.room_id;o.acceptSharedHistory&&d&&r.cryptoBackend&&(yield r.cryptoBackend.maybeAcceptKeyBundle(R,d));var x=r.getRoom(R);if(x!=null&&x.hasMembershipState(r.credentials.userId,Be.Join))return x;var T=new Vd(r,r.clientOpts,r.buildSyncApiOptions());return T.createRoom(R)})()}knockRoom(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,Be.Knock))return Promise.resolve({room_id:r.roomId});var i=xe("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),s={};n.viaServers&&(s.server_name=n.viaServers,s.via=n.viaServers);var o={};return n.reason&&(o.reason=n.reason),this.http.authedRequest(de.Post,i,s,o)}resendEvent(e,n){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(n,e,rt.SENDING),this.encryptAndSendEvent(n,e)}cancelPendingEvent(e){if(![rt.QUEUED,rt.NOT_SENT,rt.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===rt.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===rt.QUEUED&&this.scheduler.removeEventFromQueue(e);var n=this.getRoom(e.getRoomId());this.updatePendingEventStatus(n,e,rt.CANCELLED)}setRoomName(e,n){return this.sendStateEvent(e,Z.RoomName,{name:n})}setRoomTopic(e,n,r){var i=_J(n,r);return this.sendStateEvent(e,Z.RoomTopic,i)}getRoomTags(e){var n=xe("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(de.Get,n)}setRoomTag(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=xe("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:n});return this.http.authedRequest(de.Put,i,void 0,r)}deleteRoomTag(e,n){var r=xe("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:n});return this.http.authedRequest(de.Delete,r)}setRoomAccountData(e,n,r){var i=xe("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:n});return this.http.authedRequest(de.Put,i,void 0,r)}setPowerLevel(e,n,r){var i=this;return B(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(Z.RoomPowerLevels,""))===null||a===void 0?void 0:a.getContent()}if(!o)try{o=yield i.getStateEvent(e,Z.RoomPowerLevels,"")}catch(d){if(d instanceof tr&&d.errcode==="M_NOT_FOUND")o={};else throw d}o=d_(o),(s=o)!==null&&s!==void 0&&s.users||(o.users={});var c=Array.isArray(n)?n:[n];for(var l of c)r==null?delete o.users[l]:o.users[l]=r;return i.sendStateEvent(e,Z.RoomPowerLevels,o,"")})()}unstable_createLiveBeacon(e,n){var r=this;return B(function*(){return r.unstable_setLiveBeacon(e,n)})()}unstable_setLiveBeacon(e,n){var r=this;return B(function*(){return r.sendStateEvent(e,ZO.name,n,r.getUserId())})()}sendEvent(e,n,r,i,s){var o,a,c,l;return!(n!=null&&n.startsWith(Cc))&&n!==null?(l=i,c=r,a=n,o=null):(l=s,c=i,a=r,o=n),this.addThreadRelationIfNeeded(c,o,e),this.sendCompleteEvent(e,o,{type:a,content:c},l)}addThreadRelationIfNeeded(e,n,r){var i;if(n&&!((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"]=Yr(Yr({},e["m.relates_to"]),{},{rel_type:wn.name,event_id:n,is_falling_back:!a});var c=(o=this.getRoom(r))===null||o===void 0?void 0:o.getThread(n);if(c&&!a){var l,d;e["m.relates_to"]["m.in_reply_to"]={event_id:(l=(d=c.lastReply(h=>h.isRelation(wn.name)&&!h.status))===null||d===void 0?void 0:d.getId())!==null&&l!==void 0?l:n}}}}sendCompleteEvent(e,n,r,i,s){var o,a;typeof i=="string"?a=i:(o=i,a=s),a||(a=this.makeTxnId());var c=new $i(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()})),l=this.getRoom(e),d=n?l?.getThread(n):void 0;d&&c.setThread(d),o||(this.reEmitter.reEmit(c,[Kt.Replaced,Kt.VisibilityChange]),l?.reEmitter.reEmit(c,[Kt.BeforeRedaction]));var h=c.getAssociatedId();if(h!=null&&h.startsWith("~")){var m=l?.getPendingEvents().find(y=>y.getId()===h);m?.once(Kt.LocalEventIdReplaced,()=>{c.updateAssociatedId(m.getId())})}var g=c.getType();return this.logger.debug("sendEvent of type ".concat(g," in ").concat(e," with txnId ").concat(a).concat(o?" (delayed event)":"")),c.setTxnId(a),c.setStatus(rt.SENDING),o?this.encryptAndSendEvent(l,c,o):(l?.addPendingEvent(c,a),c.status===rt.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(l,c))}encryptAndSendEvent(e,n,r){var i=this;return B(function*(){if(r)return i.sendEventHttpRequest(n,r);try{var s;i.eventsBeingEncrypted.add(n.getId());try{yield i.encryptEventIfNeeded(n,e??void 0)}finally{s=!i.eventsBeingEncrypted.delete(n.getId())}if(s)return{};n.status===rt.ENCRYPTING&&i.updatePendingEventStatus(e,n,rt.SENDING);var o=null;return i.scheduler&&(o=i.scheduler.queueEvent(n),o&&i.scheduler.getQueueForEvent(n).length>1&&i.updatePendingEventStatus(e,n,rt.QUEUED)),o||(o=i.sendEventHttpRequest(n),e&&(o=o.then(a=>(e.updatePendingEvent(n,rt.SENT,a.event_id),a)))),yield o}catch(a){i.logger.error("Error sending event",a);try{n.error=a,i.updatePendingEventStatus(e,n,rt.NOT_SENT)}catch(c){i.logger.error("Exception in error handler!",c)}throw a instanceof tr&&(a.event=n),a}})()}encryptEventIfNeeded(e,n){var r=this;return B(function*(){if(n&&(yield r.shouldEncryptEventForRoom(e,n))&&!(!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(n,e,rt.ENCRYPTING),yield r.cryptoBackend.encryptEvent(e,n)}})()}shouldEncryptEventForRoom(e,n){var r=this;return B(function*(){var i;return e.isEncrypted()||e.getType()===Z.Reaction||e.isRedaction()?!1:!!(n.hasEncryptionStateEvent()||(yield(i=r.cryptoBackend)===null||i===void 0?void 0:i.isEncryptionEnabledInRoom(n.roomId)))})()}getEncryptedIfNeededEventType(e,n){var r;return n===Z.Reaction?n:(r=this.getRoom(e))!==null&&r!==void 0&&r.hasEncryptionStateEvent()?Z.RoomMessageEncrypted:n}updatePendingEventStatus(e,n,r){e?e.updatePendingEvent(n,r):n.setStatus(r)}sendEventHttpRequest(e,n){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=xe(o,i)}else if(e.isRedaction()&&e.event.redacts){var a="/rooms/$roomId/redact/$redactsEventId/$txnId";s=xe(a,Yr({$redactsEventId:e.event.redacts},i))}else s=xe("/rooms/$roomId/send/$eventType/$txnId",i);var c=e.getWireContent();return n?this.http.authedRequest(de.Put,s,aB(n),c):this.http.authedRequest(de.Put,s,void 0,c).then(l=>(this.logger.debug("Event sent to ".concat(e.getRoomId()," with event id ").concat(l.event_id)),l))}redactEvent(e,n,r,i,s){var o,a,c;(o=r)!==null&&o!==void 0&&o.startsWith(Cc)||(s=i,i=r,r=n,n=null);var l=(a=s)===null||a===void 0?void 0:a.reason,d={reason:l};if(((c=s)===null||c===void 0?void 0:c.with_rel_types)!==void 0){if(this.canSupport.get(ti.RelationBasedRedactions)===Zr.Unsupported)throw new Error("Server does not support relation based redactions "+"roomId ".concat(e," eventId ").concat(r," txnId: ").concat(i," threadId ").concat(n));var h=this.canSupport.get(ti.RelationBasedRedactions)===Zr.Stable?X5.stable:X5.unstable;d[h]=s.with_rel_types}return this.sendCompleteEvent(e,n,{type:Z.RoomRedaction,content:d,redacts:r},i)}sendMessage(e,n,r,i){typeof n!="string"&&n!==null&&(i=r,r=n,n=null);var s=Z.RoomMessage,o=r;return this.sendEvent(e,n,s,o,i)}sendTextMessage(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=mJ(r);return this.sendMessage(e,n,o,i)}sendNotice(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=gJ(r);return this.sendMessage(e,n,o,i)}sendEmoteMessage(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=vJ(r);return this.sendMessage(e,n,o,i)}sendImageMessage(e,n,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Image";!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(o=i||"Image",i=r,r=n,n=null);var a={msgtype:ll.Image,url:r,info:i,body:o};return this.sendMessage(e,n,a)}sendStickerMessage(e,n,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Sticker";!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(o=i||"Sticker",i=r,r=n,n=null);var a={url:r,info:i,body:o};return this.sendEvent(e,n,Z.Sticker,a)}sendHtmlMessage(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=fJ(r,i);return this.sendMessage(e,n,o)}sendHtmlNotice(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=hJ(r,i);return this.sendMessage(e,n,o)}sendHtmlEmote(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=pJ(r,i);return this.sendMessage(e,n,o)}_unstable_sendDelayedEvent(e,n,r,i,s,o){var a=this;return B(function*(){if(!(yield a.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","sendDelayedEvent");return a.addThreadRelationIfNeeded(s,r,e),a.sendCompleteEvent(e,r,{type:i,content:s},n,o)})()}_unstable_sendDelayedStateEvent(e,n,r,i){var s=arguments,o=this;return B(function*(){var a=s.length>4&&s[4]!==void 0?s[4]:"",c=s.length>5&&s[5]!==void 0?s[5]:{};if(!(yield o.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","sendDelayedStateEvent");var l={$roomId:e,$eventType:r,$stateKey:a},d=xe("/rooms/$roomId/state/$eventType",l);return a!==void 0&&(d=xe(d+"/$stateKey",l)),o.http.authedRequest(de.Put,d,aB(n),i,c)})()}_unstable_getDelayedEvents(e){var n=this;return B(function*(){if(!(yield n.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","getDelayedEvents");var r=e?{from:e}:void 0;return yield n.http.authedRequest(de.Get,"/delayed_events",r,void 0,{prefix:"".concat(Xr.Unstable,"/").concat(Vc)})})()}_unstable_updateDelayedEvent(e,n){var r=arguments,i=this;return B(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:{};if(!(yield i.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","updateDelayedEvent");var o=xe("/delayed_events/$delayId",{$delayId:e}),a={action:n};return yield i.http.authedRequest(de.Post,o,void 0,a,Yr(Yr({},s),{},{prefix:"".concat(Xr.Unstable,"/").concat(Vc)}))})()}sendReceipt(e,n,r){var i=arguments,s=this;return B(function*(){var o=i.length>3&&i[3]!==void 0?i[3]:!1;if(s.isGuest())return Promise.resolve({});var a=xe("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:n,$eventId:e.getId()}),c=!o&&s.supportsThreads(),l=c?Yr(Yr({},r),{},{thread_id:ov(e)}):r,d=s.http.authedRequest(de.Post,a,void 0,l||{}),h=s.getRoom(e.getRoomId());return h&&s.credentials.userId&&h.addLocalEchoReceipt(s.credentials.userId,e,n,o),d})()}sendReadReceipt(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:ls.Read,s=n.length>2&&n[2]!==void 0?n[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,n,r,i){var s=this;return B(function*(){var o=s.getRoom(e);if(o!=null&&o.hasPendingEvent(n))throw new Error("Cannot set read marker to a pending event (".concat(n,")"));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?.addLocalEchoReceipt(s.credentials.userId,r,ls.Read)}var c;if(i){if(c=i.getId(),o!=null&&o.hasPendingEvent(c))throw new Error("Cannot set read receipt to a pending event (".concat(c,")"));o?.addLocalEchoReceipt(s.credentials.userId,i,ls.ReadPrivate)}return yield s.setRoomReadMarkersHttpRequest(e,n,a,c)})()}sendRtcDecline(e,n){return this.sendEvent(e,Z.RTCDecline,{"m.relates_to":{event_id:n,rel_type:vn.Reference}})}getUrlPreview(e,n){n=Math.floor(n/6e4)*6e4;var r=new URL(e);r.hash="",e=r.toString();var i=n+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];var s=this.http.authedRequest(de.Get,"/preview_url",{url:e,ts:n.toString()},void 0,{prefix:Cg.V3,priority:"low"});return this.urlPreviewCache[i]=s,s}sendTyping(e,n,r){if(this.isGuest())return Promise.resolve({});var i=xe("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),s={typing:n};return n&&(s.timeout=r||2e4),this.http.authedRequest(de.Put,i,void 0,s)}getRoomUpgradeHistory(e){var n=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,n,r),o=this.findSuccessorRooms(i,n,r);return[...s,i,...o]}findPredecessorRooms(e,n,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 c;if(a){if(o.has(a))break;o.add(a)}var l=this.getRoom(a);if(l===null)break;if(n){var d=l.currentState.getStateEvents(Z.RoomTombstone,"");if(!d||d.getContent().replacement_room!==e.roomId)break}s.splice(0,0,l),e=l,a=(c=e.findPredecessor(r))===null||c===void 0?void 0:c.roomId}return s}findSuccessorRooms(e,n,r){for(var i=[],s=e.currentState.getStateEvents(Z.RoomTombstone,"");s;){var o=this.getRoom(s.getContent().replacement_room);if(!o||o.roomId===e.roomId)break;if(n){var a,c=(a=o.findPredecessor(r))===null||a===void 0?void 0:a.roomId;if(!c||c!==e.roomId)break}i.push(o);var l=new Set(i.map(d=>d.roomId));if(l.size<i.length)return i.slice(0,i.length-1);e=o,s=e.currentState.getStateEvents(Z.RoomTombstone,"")}return i}invite(e,n){var r=arguments,i=this;return B(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:{};if(typeof s!="object"&&(s={reason:s}),s.shareEncryptedHistory){var o;yield(o=i.cryptoBackend)===null||o===void 0?void 0:o.shareRoomHistoryWithUser(e,n)}return yield i.membershipChange(e,n,Be.Invite,s.reason)})()}inviteByEmail(e,n){return this.inviteByThreePid(e,"email",n)}inviteByThreePid(e,n,r){var i=this;return B(function*(){var s,o=xe("/rooms/$roomId/invite",{$roomId:e}),a=i.getIdentityServerUrl(!0);if(!a)return Promise.reject(new tr({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));var c={id_server:a,medium:n,address:r};if((s=i.identityServer)!==null&&s!==void 0&&s.getAccessToken){var l=yield i.identityServer.getAccessToken();l&&(c.id_access_token=l)}return i.http.authedRequest(de.Post,o,void 0,c)})()}leave(e){return this.membershipChange(e,void 0,Be.Leave)}leaveRoomChain(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,r=this.getRoomUpgradeHistory(e,!0),i=r;if(!n){i=[];for(var s of r)if(i.push(s),s.roomId===e)break}var o={},a=[],c=d=>this.leave(d).then(()=>{delete o[d]}).catch(h=>{o[d]=h});for(var l of i)a.push(c(l.roomId));return Promise.all(a).then(()=>o)}ban(e,n,r){return this.membershipChange(e,n,Be.Ban,r)}forget(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:!0,s=xe("/rooms/$room_id/forget",{$room_id:e}),o=yield r.http.authedRequest(de.Post,s);return i&&(r.store.removeRoom(e),r.emit(Le.DeleteRoom,e)),o})()}unban(e,n){var r=xe("/rooms/$roomId/unban",{$roomId:e}),i={user_id:n};return this.http.authedRequest(de.Post,r,void 0,i)}kick(e,n,r){var i=xe("/rooms/$roomId/kick",{$roomId:e}),s={user_id:n,reason:r};return this.http.authedRequest(de.Post,i,void 0,s)}membershipChange(e,n,r,i){var s=xe("/rooms/$room_id/$membership",{$room_id:e,$membership:r});return this.http.authedRequest(de.Post,s,void 0,{user_id:n,reason:i})}getPushActionsForEvent(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushActions()||n){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushActions()}getPushDetailsForEvent(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushDetails()||n){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushDetails()}setProfileInfo(e,n){var r=xe("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(de.Put,r,void 0,n)}setDisplayName(e){var n=this;return B(function*(){var r=yield n.setProfileInfo("displayname",{displayname:e}),i=n.getUser(n.getUserId());return i&&(i.displayName=e,i.emit(Ui.DisplayName,i.events.presence,i)),r})()}setAvatarUrl(e){var n=this;return B(function*(){var r=yield n.setProfileInfo("avatar_url",{avatar_url:e}),i=n.getUser(n.getUserId());return i&&(i.avatarUrl=e,i.emit(Ui.AvatarUrl,i.events.presence,i)),r})()}mxcUrlToHttp(e,n,r,i,s,o,a){return W3(this.baseUrl,e,n,r,i,s,o,a)}setSyncPresence(e){var n=this;return B(function*(){var r;(r=n.syncApi)===null||r===void 0||r.setPresence(e)})()}setPresence(e){var n=this;return B(function*(){var r=xe("/presence/$userId/status",{$userId:n.credentials.userId}),i=["offline","online","unavailable"];if(i.indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);yield n.http.authedRequest(de.Put,r,void 0,e)})()}getPresence(e){var n=xe("/presence/$userId/status",{$userId:e});return this.http.authedRequest(de.Get,n)}scrollback(e){var n=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(Bye-s,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);var o=this.store.scrollback(e,n).length;if(o===n)return Promise.resolve(e);n=n-o;var a=new Promise((c,l)=>{_p(r).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,n,ht.Backward)).then(d=>{var h,m,g=d.chunk.map(this.getEventMapper());if(d.state){var y=d.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(y)}var[v,w,S]=e.partitionThreadedEvents(g);this.processAggregatedTimelineEvents(e,v),e.addEventsToTimeline(v,!0,!0,e.getLiveTimeline()),this.processThreadEvents(e,w,!0),S.forEach(R=>e.relations.aggregateChildEvent(R)),e.oldState.paginationToken=(h=d.end)!==null&&h!==void 0?h:null,d.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,g,(m=d.end)!==null&&m!==void 0?m:null,!0),delete this.ongoingScrollbacks[e.roomId],c(e)}).catch(d=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},l(d)})});return i={promise:a},this.ongoingScrollbacks[e.roomId]=i,a}getEventMapper(e){return L1e(this,e||{})}getEventTimeline(e,n){var r=this;return B(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(n))return e.getTimelineForEvent(n);if(e.thread&&r.supportsThreads())return r.getThreadTimeline(e,n);var c=xe("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:n}),l=void 0;(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(l={filter:JSON.stringify(Us.LAZY_LOADING_MESSAGES_FILTER)});var d=yield r.http.authedRequest(de.Get,c,l);if(!d.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(n))return e.getTimelineForEvent(n);var h=r.getEventMapper(),m=h(d.event);if(m.isRelation(wn.name)){r.logger.warn("Tried loading a regular timeline at the position of a thread event");return}var g=[...d.events_after.reverse().map(h),m,...d.events_before.map(h)],y=e.getTimelineForEvent(g[0].getId());y?y.getState(Me.BACKWARDS).setUnknownStateEvents(d.state.map(h)):(y=e.addTimeline(),y.initialiseState(d.state.map(h)),y.getState(Me.FORWARDS).paginationToken=d.end);var[v,w,S]=e.room.partitionThreadedEvents(g);return e.addEventsToTimeline(v,!0,!1,y,d.start),r.processThreadEvents(e.room,w,!0),r.processAggregatedTimelineEvents(e.room,v),S.forEach(R=>e.relations.aggregateChildEvent(R)),(s=(o=e.getTimelineForEvent(n))!==null&&o!==void 0?o:(a=e.room.findThreadForEvent(m))===null||a===void 0?void 0:a.liveTimeline)!==null&&s!==void 0?s:y})()}getThreadTimeline(e,n){var r=this;return B(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=xe("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:n}),o={limit:"0"};(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(o.filter=JSON.stringify(Us.LAZY_LOADING_MESSAGES_FILTER));var a=yield r.http.authedRequest(de.Get,s,o),c=r.getEventMapper(),l=c(a.event);if(e.canContain(l)){var d=r.canSupport.get(ti.RelationsRecursion)!==Zr.Unsupported;if(Un.hasServerSideSupport)if(Un.hasServerSideFwdPaginationSupport){var h,m,g;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var y=e.thread,v=yield r.fetchRelations(e.room.roomId,y.id,null,null,{dir:ht.Backward,from:a.start,recurse:d||void 0}),w=yield r.fetchRelations(e.room.roomId,y.id,null,null,{dir:ht.Forward,from:a.end,recurse:d||void 0}),S=[...w.chunk.reverse().filter(Nk(y.id)).map(c),l,...v.chunk.filter(Nk(y.id)).map(c)];for(var R of S){var x;yield(x=e.thread)===null||x===void 0?void 0:x.processEvent(R)}var T=e.getTimelineForEvent(l.getId());if(T?T.getState(Me.BACKWARDS).setUnknownStateEvents(a.state.map(c)):(T=e.addTimeline(),T.initialiseState(a.state.map(c))),e.addEventsToTimeline(S,!0,!1,T,w.next_batch),!v.next_batch){var I=yield r.fetchRoomEvent(e.room.roomId,y.id);e.addEventsToTimeline([c(I)],!0,!1,T,null)}return T.setPaginationToken((h=v.next_batch)!==null&&h!==void 0?h:null,ht.Backward),T.setPaginationToken((m=w.next_batch)!==null&&m!==void 0?m:null,ht.Forward),r.processAggregatedTimelineEvents(e.room,S),(g=e.getTimelineForEvent(n))!==null&&g!==void 0?g:T}else{for(var k,A=e.thread,O=yield r.fetchRelations(e.room.roomId,A.id,wn.name,null,{dir:ht.Backward,from:a.start,recurse:d||void 0}),D=[],N=a.end;N;){var U,$=yield r.fetchRelations(e.room.roomId,A.id,wn.name,null,{dir:ht.Forward,from:N,recurse:d||void 0});N=(U=$.next_batch)!==null&&U!==void 0?U:null,D.push(...$.chunk)}var K=[...D.reverse().map(c),l,...O.chunk.map(c)];for(var Y of K){var G;yield(G=e.thread)===null||G===void 0?void 0:G.processEvent(Y)}var F=e.getLiveTimeline();if(F.getState(Me.BACKWARDS).setUnknownStateEvents(a.state.map(c)),e.addEventsToTimeline(K,!0,!1,F,null),!O.next_batch){var q=yield r.fetchRoomEvent(e.room.roomId,A.id);e.addEventsToTimeline([c(q)],!0,!1,F,null)}return F.setPaginationToken((k=O.next_batch)!==null&&k!==void 0?k:null,ht.Backward),F.setPaginationToken(null,ht.Forward),r.processAggregatedTimelineEvents(e.room,K),F}}})()}getLatestTimeline(e){var n=this;return B(function*(){if(!n.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 n.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&&Un.hasServerSideSupport){var o,a=n.canSupport.get(ti.RelationsRecursion)!==Zr.Unsupported,c=yield n.fetchRelations(e.room.roomId,e.thread.id,wn.name,null,{dir:ht.Backward,limit:1,recurse:a||void 0});r=(o=c.chunk)===null||o===void 0?void 0:o[0]}else{var l,d,h=xe("/rooms/$roomId/messages",{$roomId:e.room.roomId}),m={dir:"b"};(l=n.clientOpts)!==null&&l!==void 0&&l.lazyLoadMembers&&(m.filter=JSON.stringify(Us.LAZY_LOADING_MESSAGES_FILTER));var g=yield n.http.authedRequest(de.Get,h,m);r=(d=g.chunk)===null||d===void 0?void 0:d[0]}if(!r)throw new Error("No message returned when trying to construct getLatestTimeline");return n.getEventTimeline(e,r.event_id)})()}createMessagesRequest(e,n){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=xe("/rooms/$roomId/messages",{$roomId:e}),c={limit:i.toString(),dir:s};n&&(c.from=n);var l=null;if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(l=Object.assign({},Us.LAZY_LOADING_MESSAGES_FILTER)),o){var d;l=l||{},Object.assign(l,(d=o.getRoomTimelineFilterComponent())===null||d===void 0?void 0:d.toJSON())}return l&&(c.filter=JSON.stringify(l)),this.http.authedRequest(de.Get,a,c)}createThreadListMessagesRequest(e,n){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]:Ba.All,a=arguments.length>5?arguments[5]:void 0,c=xe("/rooms/$roomId/threads",{$roomId:e}),l={limit:i.toString(),dir:s,include:SQ(o)};n&&(l.from=n);var d={};if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(d=Yr({},Us.LAZY_LOADING_MESSAGES_FILTER)),a){var h;d=Yr(Yr({},d),(h=a.getRoomTimelineFilterComponent())===null||h===void 0?void 0:h.toJSON())}Object.keys(d).length&&(l.filter=JSON.stringify(d));var m={prefix:Un.hasServerSideListSupport===Zi.Stable?Xr.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(de.Get,c,l,void 0,m).then(g=>{var y;return Yr(Yr({},g),{},{chunk:(y=g.chunk)===null||y===void 0?void 0:y.reverse(),start:g.prev_batch,end:g.next_batch})})}paginateEventTimeline(e,n){var r=this,i=e.getTimelineSet()===this.notifTimelineSet,s=this.getRoom(e.getRoomId()),o=e.getTimelineSet().threadListType,a=e.getTimelineSet().thread;n=n||{};var c=n.backwards||!1;if(i&&!c)throw new Error("paginateNotifTimeline can only paginate backwards");var l=c?Me.BACKWARDS:Me.FORWARDS,d=e.getPaginationToken(l),h=e.paginationRequests[l];if(h)return h;var m,g,y;if(i){var v;m="/notifications",g={limit:((v=n.limit)!==null&&v!==void 0?v:30).toString(),only:"highlight"},d&&d!=="end"&&(g.from=d),y=this.http.authedRequest(de.Get,m,g).then(function(){var T=B(function*(I){var k=I.next_token,A=[];I.notifications=I.notifications.filter(Ka);for(var O=0;O<I.notifications.length;O++){var D=I.notifications[O],N=r.getEventMapper()(D.event);r.getPushDetailsForEvent(N,!0),N.event.room_id=D.room_id,A[O]=N}var U=e.getTimelineSet();return U.addEventsToTimeline(A,c,!1,e,k),r.processAggregatedTimelineEvents(U.room,A),c&&!I.next_token&&e.setPaginationToken(null,l),!!I.next_token});return function(I){return T.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}else if(o!==null){if(!s)throw new Error("Unknown room "+e.getRoomId());if(!Un.hasServerSideFwdPaginationSupport&&l===ht.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");y=this.createThreadListMessagesRequest(e.getRoomId(),d,n.limit,l,o,e.getFilter()).then(T=>{if(T.state){var I=e.getState(l),k=T.state.filter(Ka).map(this.getEventMapper());I.setUnknownStateEvents(k)}var A=T.end,O=T.chunk.filter(Ka).map(this.getEventMapper()),D=e.getTimelineSet();return D.addEventsToTimeline(O,c,!1,e,A),this.processAggregatedTimelineEvents(s,O),this.processThreadRoots(s,O,c),c&&T.end==T.start&&e.setPaginationToken(null,l),T.end!==T.start}).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}else if(a){var w,S,R=this.getRoom((w=e.getRoomId())!==null&&w!==void 0?w:void 0);if(!R)throw new Error("Unknown room "+e.getRoomId());var x=this.canSupport.get(ti.RelationsRecursion)!==Zr.Unsupported;y=this.fetchRelations((S=e.getRoomId())!==null&&S!==void 0?S:"",a.id,null,null,{dir:l,limit:n.limit,from:d??void 0,recurse:x||void 0}).then(function(){var T=B(function*(I){var k=r.getEventMapper(),A=I.chunk.filter(Ka).filter(Nk(a.id)).map(k);for(var O of A.slice().reverse()){yield a?.processEvent(O);var D=O.getSender();(!c||a?.getEventReadUpTo(D)===null)&&R.addLocalEchoReceipt(D,O,ls.Read)}var N=I.next_batch,U=e.getTimelineSet();if(U.addEventsToTimeline(A,c,!1,e,N??null),!N&&c){var $,K,Y=($=a.rootEvent)!==null&&$!==void 0?$:k(yield r.fetchRoomEvent((K=e.getRoomId())!==null&&K!==void 0?K:"",a.id));U.addEventsToTimeline([Y],!0,!1,e,null)}return r.processAggregatedTimelineEvents(U.room,A),c&&!N&&e.setPaginationToken(null,l),!!N});return function(I){return T.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}else{if(!s)throw new Error("Unknown room "+e.getRoomId());y=this.createMessagesRequest(e.getRoomId(),d,n.limit,l,e.getFilter()).then(T=>{if(T.state){var I=e.getState(l),k=T.state.filter(Ka).map(this.getEventMapper());I.setUnknownStateEvents(k)}var A=T.end,O=T.chunk.filter(Ka).map(this.getEventMapper()),D=e.getTimelineSet(),[N,,U]=s.partitionThreadedEvents(O);D.addEventsToTimeline(N,c,!1,e,A),this.processAggregatedTimelineEvents(s,N),this.processThreadRoots(s,N.filter(K=>K.getServerAggregatedRelation(wn.name)),!1),U.forEach(K=>s.relations.aggregateChildEvent(K));var $=T.end===void 0||T.end===T.start;return c&&$&&e.setPaginationToken(null,l),!$}).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}return y}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var n,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;return(n=this.peekSync)===null||n===void 0||n.stopPeeking(),this.peekSync=new Vd(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,r)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,n){var r=this.sendStateEvent(e,Z.RoomGuestAccess,{guest_access:n.allowJoin?dC.CanJoin:dC.Forbidden},""),i=Promise.resolve();return n.allowRead&&(i=this.sendStateEvent(e,Z.RoomHistoryVisibility,{history_visibility:QO.WorldReadable},"")),Promise.all([i,r]).then()}requestRegisterEmailToken(e,n,r,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:n,send_attempt:r,next_link:i})}requestRegisterMsisdnToken(e,n,r,i,s){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:n,client_secret:r,send_attempt:i,next_link:s})}requestAdd3pidEmailToken(e,n,r,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:n,send_attempt:r,next_link:i})}requestAdd3pidMsisdnToken(e,n,r,i,s){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:n,client_secret:r,send_attempt:i,next_link:s})}requestPasswordEmailToken(e,n,r,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:n,send_attempt:r,next_link:i})}requestPasswordMsisdnToken(e,n,r,i,s){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:n,client_secret:r,send_attempt:i,next_link:s})}requestTokenFromEndpoint(e,n){var r=this;return B(function*(){var i=Object.assign({},n);return r.http.request(de.Post,e,void 0,i)})()}getRoomPushRule(e,n){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===n)}else throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,n,r){var i,s=!1,o=this.getRoomPushRule(e,n);if(o!=null&&o.actions.includes(Zd.DontNotify)&&(s=!0),!r)s&&(i=this.deletePushRule(e,wi.RoomSpecific,o.rule_id));else if(!o)i=this.addPushRule(e,wi.RoomSpecific,n,{actions:[Zd.DontNotify]});else if(!s){var a=Promise.withResolvers();this.deletePushRule(e,wi.RoomSpecific,o.rule_id).then(()=>{this.addPushRule(e,wi.RoomSpecific,n,{actions:[Zd.DontNotify]}).then(()=>{a.resolve()}).catch(c=>{a.reject(c)})}).catch(c=>{a.reject(c)}),i=a.promise}if(i)return new Promise((c,l)=>{i.then(()=>{this.getPushRules().then(d=>{this.pushRules=d,c()}).catch(d=>{l(d)})}).catch(d=>{this.getPushRules().then(h=>{this.pushRules=h,l(d)}).catch(h=>{l(d)})})})}searchMessageText(e){var n={search_term:e.query};return"keys"in e&&(n.keys=e.keys),this.search({body:{search_categories:{room_events:n}}})}searchRoomEvents(e){var n={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:KJ.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},r={_query:n,results:[],highlights:[]};return this.search({body:n}).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 n={body:e._query,next_batch:e.next_batch},r=this.search(n,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=r,r}processRoomEventsSearch(e,n){var r,i,s=n.search_categories.room_events;e.count=s.count,e.next_batch=s.next_batch;var o=new Set(s.highlights);e.highlights.forEach(g=>{o.add(g)}),e.highlights=Array.from(o);for(var a=this.getEventMapper(),c=(r=(i=s.results)===null||i===void 0?void 0:i.length)!==null&&r!==void 0?r:0,l=0;l<c;l++){var d=tT.fromJson(s.results[l],a),h=this.getRoom(d.context.getEvent().getRoomId());if(h)for(var m of d.context.getTimeline())m.setMetadata(h.currentState,!1);e.results.push(d)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;var e=new Vd(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 n=xe("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,n,void 0,e).then(r=>{var i=Us.fromJson(this.credentials.userId,r.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,n,r){if(r){var i=this.store.getFilter(e,n);if(i)return Promise.resolve(i)}var s=xe("/user/$userId/filter/$filterId",{$userId:e,$filterId:n});return this.http.authedRequest(de.Get,s).then(o=>{var a=Us.fromJson(e,n,o);return this.store.storeFilter(a),a})}getOrCreateFilter(e,n){var r=this;return B(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(),c=n.getDefinition();ff(a,c)&&(s=i)}}catch(d){if(d.errcode!=="M_UNKNOWN"&&d.errcode!=="M_NOT_FOUND")throw d}s||r.store.setFilterIdByName(e,void 0)}if(s)return s;var l=yield r.createFilter(n.getDefinition());return r.store.setFilterIdByName(e,l.filterId),l.filterId})()}getOpenIdToken(){var e=xe("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(de.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}checkTurnServers(){var e=this;return B(function*(){if(e.canSupportVoip){var n=!1,r=e.turnServersExpiry-Date.now();if(r>oB)e.logger.debug("TURN creds are valid for another "+r+" ms: not fetching new ones."),n=!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,n=!0,e.emit(Le.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(Le.TurnServersError,o,!0)):e.emit(Le.TurnServersError,o,!1)}}return n}})()}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){var e=xe("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(de.Get,e,void 0,void 0,{prefix:""}).then(n=>n.admin)}whoisSynapseUser(e){var n=xe("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(de.Get,n,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){var n=xe("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(de.Post,n,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e=this;return B(function*(){var n;e.clientWellKnownPromise=lt.getRawClientConfig((n=e.getDomain())!==null&&n!==void 0?n:void 0),e.clientWellKnown=yield e.clientWellKnownPromise,e.emit(Le.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"],n=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(n)}_unstable_getSharedRooms(e){var n=this;return B(function*(){var r=yield n.doesServerSupportUnstableFeature(mQ),i=yield n.doesServerSupportUnstableFeature(gQ),s=yield n.doesServerSupportUnstableFeature(vQ);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=xe("/uk.half-shot.msc2666/user/".concat(i?"mutual_rooms":"shared_rooms","/$userId"),{$userId:e}),a={});var c=[],l=null;do{var d={};l!=null&&s&&(d.batch_token=l);var h=yield n.http.authedRequest(de.Get,o,Yr(Yr({},a),d),void 0,{prefix:Xr.Unstable});c.push(...h.joined),h.next_batch_token!==void 0?l=h.next_batch_token:l=null}while(l!=null);return c})()}getVersions(){var e=this;return B(function*(){if(e.serverVersionsPromise)return e.serverVersionsPromise;e.serverVersionsPromise=e.http.authedRequest(de.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(r=>{throw e.serverVersionsPromise=void 0,r});var n=yield e.serverVersionsPromise;return e.canSupport=yield O0e(n),e.serverVersionsPromise})()}isVersionSupported(e){var n=this;return B(function*(){var{versions:r}=yield n.getVersions();return r&&r.includes(e)})()}doesServerSupportUnstableFeature(e){var n=this;return B(function*(){var r=yield n.getVersions();if(!r)return!1;var i=r.unstable_features;return i&&!!i[e]})()}doesServerForceEncryptionForPreset(e){var n=this;return B(function*(){var r=yield n.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 B(function*(){if(yield e.isVersionSupported("v1.4"))return{threads:Zi.Stable,list:Zi.Stable,fwdPagination:Zi.Stable};try{var[n,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:JE(r,n),list:JE(s,i),fwdPagination:JE(a,o)}}catch{return{threads:Zi.None,list:Zi.None,fwdPagination:Zi.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,n,r,i){var s=arguments,o=this;return B(function*(){var a,c,l=s.length>4&&s[4]!==void 0?s[4]:{dir:ht.Backward},d=i?o.getEncryptedIfNeededEventType(e,i):null,[h,m]=yield Promise.all([o.fetchRoomEvent(e,n),o.fetchRelations(e,n,r,d,l)]),g=o.getEventMapper(),y=h?g(h):void 0,v=m.chunk.map(g);if(d===Z.RoomMessageEncrypted){var w=y?v.concat(y):v;yield Promise.all(w.map(S=>o.decryptEventIfNeeded(S))),i!==null&&(v=v.filter(S=>S.getType()===i))}return y&&r===vn.Replace&&(v=v.filter(S=>S.getSender()===y.getSender())),{originalEvent:y??null,events:v,nextBatch:(a=m.next_batch)!==null&&a!==void 0?a:null,prevBatch:(c=m.prev_batch)!==null&&c!==void 0?c:null}})()}generateClientSecret(){return To(32)}decryptEventIfNeeded(e,n){return e.isState()&&!this.enableEncryptedStateEvents?Promise.resolve():(e.shouldAttemptDecryption()&&this.getCrypto()&&e.attemptDecryption(this.cryptoBackend,n),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve())}termsUrlForService(e,n){switch(e){case fA.IS:return this.http.getUrl("/terms",void 0,$l.V2,n);case fA.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",n);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(){var e,n,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return r&&((e=this.idBaseUrl)!==null&&e!==void 0&&e.startsWith("http://")||(n=this.idBaseUrl)!==null&&n!==void 0&&n.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=Ek(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(de.Get,"/register/available",{username:e}).then(n=>n.available).catch(n=>n.errcode==="M_USER_IN_USE"?!1:Promise.reject(n))}register(e,n,r,i,s,o,a){r&&(i.session=r);var c={auth:i,refresh_token:!0};return e!=null&&(c.username=e),n!=null&&(c.password=n),o!=null&&(c.guest_access_token=o),a!=null&&(c.inhibit_login=a),this.registerRequest(c)}registerGuest(){var{body:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.registerRequest(e||{},"guest")}registerRequest(e,n){var r={};return n&&(r.kind=n),this.http.request(de.Post,"/register",r,e)}refreshToken(e){var n=r=>this.http.authedRequest(de.Post,"/refresh",void 0,{refresh_token:e},{prefix:r,inhibitLogoutEmit:!0});return n(Xr.V3).catch(r=>{if(r.errcode==="M_UNRECOGNIZED")return n(Xr.V1);throw r})}loginFlows(){return this.http.request(de.Get,"/login")}login(e,n){return this.loginRequest(Yr(Yr({},n),{},{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,n){return this.login("m.login.password",{user:e,password:n})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e){var n=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/"+n+"/redirect";r&&(s+="/"+r);var o={redirectUrl:e,[qye.unstable]:i};return this.http.getUrl(s,o).href}loginWithToken(e){return this.login("m.login.token",{token:e})}loginRequest(e){var n=this;return B(function*(){return yield n.http.authedRequest(de.Post,"/login",void 0,e)})()}logout(){var e=arguments,n=this;return B(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:!1;return r&&(n.stopClient(),n.http.abort()),n.http.authedRequest(de.Post,"/logout")})()}deactivateAccount(e,n){var r={};return e&&(r.auth=e),n!==void 0&&(r.erase=n),this.http.authedRequest(de.Post,"/account/deactivate",void 0,r)}requestLoginToken(e){var n=this;return B(function*(){var r={auth:e};return n.http.authedRequest(de.Post,"/login/get_token",void 0,r,{prefix:Xr.V1})})()}getFallbackAuthUrl(e,n){var r=xe("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(r,{session:n}).href}createRoom(e){var n=this;return B(function*(){var r,i=(e.invite_3pid||[]).filter(a=>!a.id_access_token);if(i.length>0&&(r=n.identityServer)!==null&&r!==void 0&&r.getAccessToken){var s=yield n.identityServer.getAccessToken();if(s)for(var o of i)o.id_access_token=s}return n.http.authedRequest(de.Post,"/createRoom",void 0,e)})()}fetchRelations(e,n,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{dir:ht.Backward},o=s;Un.hasServerSideFwdPaginationSupport===Zi.Experimental&&(o=xF("dir","org.matrix.msc3715.dir",o)),this.canSupport.get(ti.RelationsRecursion)===Zr.Unstable&&(o=xF("recurse","org.matrix.msc3981.recurse",o));var a=B5(o),c="/rooms/$roomId/relations/$eventId";r!==null?(c+="/$relationType",i!==null&&(c+="/$eventType")):i!==null&&(this.logger.warn("eventType: ".concat(i,` ignored when fetching
25
+ Date.now: "`.concat(Date.now()));try{a=yield e.membershipLoopHandler(i.type)}catch(l){throw Error("The MembershipManager shut down because of the end condition: ".concat(l))}}e._actions.splice(0,1);var c=s??a;"replace"in c?e._actions=c.replace:"insert"in c&&e._actions.push(...c.insert)};e._actions.length>0;)yield*n()}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 Hh=function(t){return t.StatusChanged="StatusChanged",t.ProbablyLeft="ProbablyLeft",t}({});function J$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function nye(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?J$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):J$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var ot=function(t){return t.SendDelayedEvent="SendDelayedEvent",t.SendJoinEvent="SendJoinEvent",t.RestartDelayedEvent="RestartDelayedEvent",t.UpdateExpiry="UpdateExpiry",t.SendScheduledDelayedLeaveEvent="SendScheduledDelayedLeaveEvent",t.SendLeaveEvent="SendLeaveEvent",t}({});class fC extends On{isActivated(){return this.activated}isJoined(){return this.isActivated()}join(e,n,r){if(this.scheduler.running){this.logger.error("MembershipManager is already running. Ignoring join request.");return}this.fociPreferred=e,this.focusActive=n,this.leavePromiseResolvers=void 0,this.activated=!0,this.oldStatus=this.status,this.state=fC.defaultState,this.scheduler.startWithJoin().catch(i=>{this.logger.error("MembershipManager stopped because: ",i),r?.(i)}).finally(()=>{if(this.activated=!1,this.oldStatus&&this.oldStatus!==this.status&&this.emit(Hh.StatusChanged,this.oldStatus,this.status),!this.scheduler.running){var i;(i=this.leavePromiseResolvers)===null||i===void 0||i.resolve(!0),this.leavePromiseResolvers=void 0}})}leave(e){return this.scheduler.running?(this.leavePromiseResolvers||(this.leavePromiseResolvers=Promise.withResolvers(),this.activated=!1,this.scheduler.initiateLeave(),e&&setTimeout(()=>{var n;return(n=this.leavePromiseResolvers)===null||n===void 0?void 0:n.resolve(!1)},e)),this.leavePromiseResolvers.promise):(this.logger.warn("Called MembershipManager.leave() even though the MembershipManager is not running"),Promise.resolve(!0))}onRTCSessionMemberUpdate(e){if(!this.isActivated())return Promise.resolve();var n=this.client.getUserId(),r=this.client.getDeviceId();if(!n||!r)return this.logger.error("MembershipManager.onRTCSessionMemberUpdate called without user or device id"),Promise.resolve();if(this._ownMembership=e.find(s=>WE(s,n,r)),!this._ownMembership){var i=[ot.SendDelayedEvent,ot.SendJoinEvent];this.logger.warn("Missing own membership: force re-join"),this.state.hasMemberStateEvent=!1,this.scheduler.actions.some(s=>i.includes(s.type))?this.logger.error("tried adding another `SendDelayedEvent` actions even though we already have one in the Queue\nActionQueueOnMemberUpdate:",this.scheduler.actions):this.scheduler.initiateJoin()}return Promise.resolve()}getActiveFocus(){if(this.focusActive)if(eQ(this.focusActive)){if(this.focusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e?.getPreferredFoci()[0]}}else this.logger.warn("Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.");else{var n=this.getOldestMembership();return n?.getPreferredFoci()[0]}}updateCallIntent(e){var n=this;return B(function*(){if(!n.activated||!n.ownMembership)throw Error("You cannot update your intent before joining the call");n.ownMembership.callIntent!==e&&(n.callIntent=e,yield n.sendJoinEvent())})()}constructor(e,n,r,i,s,o){super(),this.joinConfig=e,this.room=n,this.client=r,this.getOldestMembership=i,this.sessionDescription=s,L(this,"activated",!1),L(this,"logger",void 0),L(this,"callIntent",void 0),L(this,"leavePromiseResolvers",void 0),L(this,"_ownMembership",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,"delayedLeaveEventDelayMsOverride",void 0),this.logger=(o??M).getChild("[MembershipManager]");var[a,c]=[this.client.getUserId(),this.client.getDeviceId()];if(a===null)throw Error("Missing userId in client");if(c===null)throw Error("Missing deviceId in client");this.deviceId=c,this.stateKey=this.makeMembershipStateKey(a,c),this.state=fC.defaultState,this.callIntent=e?.callIntent,this.scheduler=new tye(l=>(this.oldStatus&&(this.logger.debug("MembershipManager applied action changes. Status: ".concat(this.oldStatus," -> ").concat(this.status)),this.oldStatus!==this.status&&this.emit(Hh.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)}get ownMembership(){return this._ownMembership}static get defaultState(){return{hasMemberStateEvent:!1,delayId:void 0,startTime:0,rateLimitRetries:new Map,networkErrorRetries:new Map,expireUpdateIterations:1,probablyLeft:!1}}get networkErrorRetryMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.networkErrorRetryMs)!==null&&e!==void 0?e:3e3}get membershipEventExpiryMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.membershipEventExpiryMs)!==null&&e!==void 0?e:tQ}get membershipEventExpiryHeadroomMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.membershipEventExpiryHeadroomMs)!==null&&e!==void 0?e:5e3}computeNextExpiryActionTs(e){return this.state.startTime+this.membershipEventExpiryMs*e-this.membershipEventExpiryHeadroomMs}get delayedLeaveEventDelayMs(){var e,n,r;return(e=(n=this.delayedLeaveEventDelayMsOverride)!==null&&n!==void 0?n:(r=this.joinConfig)===null||r===void 0?void 0:r.delayedLeaveEventDelayMs)!==null&&e!==void 0?e:8e3}get delayedLeaveEventRestartMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.delayedLeaveEventRestartMs)!==null&&e!==void 0?e:5e3}get maximumRateLimitRetryCount(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.maximumRateLimitRetryCount)!==null&&e!==void 0?e:10}get maximumNetworkErrorRetryCount(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.maximumNetworkErrorRetryCount)!==null&&e!==void 0?e:10}get delayedLeaveEventRestartLocalTimeoutMs(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.delayedLeaveEventRestartLocalTimeoutMs)!==null&&e!==void 0?e:2e3}membershipLoopHandler(e){var n=this;return B(function*(){switch(e){case ot.SendDelayedEvent:return n.state.delayId?n.cancelKnownDelayIdBeforeSendDelayedEvent(n.state.delayId):n.sendOrResendDelayedLeaveEvent();case ot.RestartDelayedEvent:return n.state.delayId?n.restartDelayedEvent(n.state.delayId):Go(ot.SendDelayedEvent);case ot.SendScheduledDelayedLeaveEvent:return n.state.hasMemberStateEvent?n.state.delayId?n.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(n.state.delayId):Go(ot.SendLeaveEvent):{replace:[]};case ot.SendJoinEvent:return n.sendJoinEvent();case ot.UpdateExpiry:return n.updateExpiryOnJoinedEvent();case ot.SendLeaveEvent:return n.state.hasMemberStateEvent?n.sendFallbackLeaveEvent():{replace:[]}}})()}sendOrResendDelayedLeaveEvent(){var e=this;return B(function*(){return yield e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.delayedLeaveEventDelayMs},Z.GroupCallMemberPrefix,{},e.stateKey).then(n=>(e.state.expectedServerDelayLeaveTs=Date.now()+e.delayedLeaveEventDelayMs,e.setAndEmitProbablyLeft(!1),e.resetRateLimitCounter(ot.SendDelayedEvent),e.state.delayId=n.delay_id,e.state.hasMemberStateEvent?Go(ot.RestartDelayedEvent,e.delayedLeaveEventRestartMs):Go(ot.SendJoinEvent))).catch(n=>{var r=ot.SendDelayedEvent;if(e.manageMaxDelayExceededSituation(n))return Go(r);var i=e.actionUpdateFromErrors(n,r,"sendDelayedStateEvent");if(i)return i;if(e.state.hasMemberStateEvent){if(e.isUnsupportedDelayedEndpoint(n))return{};throw Error("Could not send delayed event, even though delayed events are supported. "+n)}else return e.isUnsupportedDelayedEndpoint(n)?e.logger.info("Not using delayed event because the endpoint is not supported"):e.logger.info("Not using delayed event because: "+n),Go(ot.SendJoinEvent)})})()}cancelKnownDelayIdBeforeSendDelayedEvent(e){var n=this;return B(function*(){return yield n.client._unstable_updateDelayedEvent(e,zE.Cancel).then(()=>(n.state.delayId=void 0,n.resetRateLimitCounter(ot.SendDelayedEvent),Mk(ot.SendDelayedEvent))).catch(r=>{var i=ot.SendDelayedEvent,s=n.actionUpdateFromErrors(r,i,"updateDelayedEvent");if(s)return s;if(n.isNotFoundError(r))return n.state.delayId=void 0,Mk(i);if(n.isUnsupportedDelayedEndpoint(r))return Mk(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")})})()}setAndEmitProbablyLeft(e){this.state.probablyLeft!==e&&(this.state.probablyLeft=e,this.emit(Hh.ProbablyLeft,this.state.probablyLeft))}restartDelayedEvent(e){var n=this;return B(function*(){var r=n.state.expectedServerDelayLeaveTs?n.state.expectedServerDelayLeaveTs-Date.now():void 0,i=new Promise((s,o)=>{setTimeout(()=>{o(new FX("Restart delayed event timed out before the HS responded"))},r!==void 0&&!n.state.probablyLeft?Math.min(n.delayedLeaveEventRestartLocalTimeoutMs,r):n.delayedLeaveEventRestartLocalTimeoutMs)});return yield Promise.race([n.client._unstable_updateDelayedEvent(e,zE.Restart),i]).then(()=>(n.state.expectedServerDelayLeaveTs=Date.now()+n.delayedLeaveEventDelayMs,n.resetRateLimitCounter(ot.RestartDelayedEvent),n.setAndEmitProbablyLeft(!1),Go(ot.RestartDelayedEvent,n.delayedLeaveEventRestartMs))).catch(s=>{n.state.expectedServerDelayLeaveTs&&n.state.expectedServerDelayLeaveTs<=Date.now()&&n.setAndEmitProbablyLeft(!0);var o=ot.RestartDelayedEvent;if(n.isNotFoundError(s))return n.state.delayId=void 0,Go(ot.SendDelayedEvent);if(n.isUnsupportedDelayedEndpoint(s))return{};var a=n.actionUpdateFromErrors(s,o,"updateDelayedEvent");if(a)return a;throw Error("Could not restart delayed event, even though delayed events are supported. "+s)})})()}sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(e){var n=this;return B(function*(){return yield n.client._unstable_updateDelayedEvent(e,zE.Send).then(()=>(n.state.hasMemberStateEvent=!1,n.resetRateLimitCounter(ot.SendScheduledDelayedLeaveEvent),{replace:[]})).catch(r=>{var i=ot.SendLeaveEvent;if(n.isUnsupportedDelayedEndpoint(r))return{};if(n.isNotFoundError(r))return n.state.delayId=void 0,Go(i);var s=n.actionUpdateFromErrors(r,i,"updateDelayedEvent");return s||(n.logger.warn("Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent",r),Go(i))})})()}sendJoinEvent(){var e=this;return B(function*(){return yield e.client.sendStateEvent(e.room.roomId,Z.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryMs),e.stateKey).then(()=>{e.setAndEmitProbablyLeft(!1),e.state.startTime=Date.now(),e.state.expireUpdateIterations=1,e.state.hasMemberStateEvent=!0,e.resetRateLimitCounter(ot.SendJoinEvent);var n=e.scheduler.actions.filter(r=>r.type!==ot.UpdateExpiry&&r.type!==ot.SendJoinEvent);return{replace:[...n,{ts:Date.now(),type:ot.RestartDelayedEvent},{ts:e.computeNextExpiryActionTs(e.state.expireUpdateIterations),type:ot.UpdateExpiry}]}}).catch(n=>{var r=e.actionUpdateFromErrors(n,ot.SendJoinEvent,"sendStateEvent");if(r)return r;throw n})})()}updateExpiryOnJoinedEvent(){var e=this;return B(function*(){var n=e.state.expireUpdateIterations+1;return yield e.client.sendStateEvent(e.room.roomId,Z.GroupCallMemberPrefix,e.makeMyMembership(e.membershipEventExpiryMs*n),e.stateKey).then(()=>(e.resetRateLimitCounter(ot.UpdateExpiry),e.state.expireUpdateIterations=n,{insert:[{ts:e.computeNextExpiryActionTs(n),type:ot.UpdateExpiry}]})).catch(r=>{var i=e.actionUpdateFromErrors(r,ot.UpdateExpiry,"sendStateEvent");if(i)return i;throw r})})()}sendFallbackLeaveEvent(){var e=this;return B(function*(){return yield e.client.sendStateEvent(e.room.roomId,Z.GroupCallMemberPrefix,{},e.stateKey).then(()=>(e.resetRateLimitCounter(ot.SendLeaveEvent),e.state.hasMemberStateEvent=!1,{replace:[]})).catch(n=>{var r=e.actionUpdateFromErrors(n,ot.SendLeaveEvent,"sendStateEvent");if(r)return r;throw n})})()}makeMembershipStateKey(e,n){var r="".concat(e,"_").concat(n,"_").concat(this.sessionDescription.application).concat(this.sessionDescription.id);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?r:"_".concat(r)}makeMyMembership(e){var n,r,i=!!this.ownMembership;return nye({application:this.sessionDescription.application,call_id:this.sessionDescription.id,scope:"m.room",device_id:this.deviceId,expires:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(n=this.fociPreferred)!==null&&n!==void 0?n:[],"m.call.intent":this.callIntent},i?{created_ts:(r=this.ownMembership)===null||r===void 0?void 0:r.createdTs()}:void 0)}isNotFoundError(e){return e instanceof tr&&e.errcode==="M_NOT_FOUND"}manageMaxDelayExceededSituation(e){if(e instanceof tr&&e.errcode==="M_UNKNOWN"&&e.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var n=e.data["org.matrix.msc4140.max_delay"];return typeof n=="number"&&this.delayedLeaveEventDelayMs>n&&(this.delayedLeaveEventDelayMsOverride=n),this.logger.warn("Retry sending delayed disconnection event due to server timeout limitations:",e),!0}return!1}actionUpdateFromErrors(e,n,r){var i=this.actionUpdateFromRateLimitError(e,r,n);if(i)return i;var s=this.actionUpdateFromNetworkErrorRetry(e,n);if(s)return s}actionUpdateFromRateLimitError(e,n,r){var i;if((e instanceof ep||e instanceof tr)&&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 c;o=(c=e.getRetryAfterMs())!==null&&c!==void 0?c:a,this.logger.info("Rate limited by server, retrying in ".concat(o,"ms"))}catch(l){this.logger.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(a),l),o=a}return this.state.rateLimitRetries.set(r,s+1),Go(r,o)}throw Error("Exceeded maximum retries for "+r+" attempts (client."+n+"): "+e)}}actionUpdateFromNetworkErrorRetry(e,n){var r,i=(r=this.state.networkErrorRetries.get(n))!==null&&r!==void 0?r:0,s=this.networkErrorRetryMs/1e3+"s",o="("+i+"/"+this.maximumNetworkErrorRetryCount+")",a=this.networkErrorRetryMs;if(e instanceof Error&&e.name==="AbortError")a=0,this.logger.warn("Network local timeout error while sending event, immediate retry ("+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 wp)this.logger.warn("Network connection error while sending event, retrying in "+s+" "+o,e);else if((e instanceof ep||e instanceof tr)&&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(n,i+1),Go(n,a);throw Error("Reached maximum ("+this.maximumNetworkErrorRetryCount+") retries cause by: "+e)}isUnsupportedDelayedEndpoint(e){return e instanceof Gd}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:n}=e[0];switch(n){case ot.SendDelayedEvent:case ot.SendJoinEvent:return Ad.Connecting;case ot.UpdateExpiry:return Ad.Connected;case ot.SendScheduledDelayedLeaveEvent:case ot.SendLeaveEvent:return Ad.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 Ad.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 Ad.Connected}return this.scheduler.running?(this.logger.error("MembershipManager has an unknown state. Actions: ",e),Ad.Unknown):Ad.Disconnected}get probablyLeft(){return this.state.probablyLeft}}function Go(t,e){return{insert:[{ts:Date.now()+(e??0),type:t}]}}function Mk(t,e){return{replace:[{ts:Date.now()+0,type:t}]}}var Wc=function(t){return t.ReceivedKeys="received_keys",t.NotSupportedError="not_supported_error",t}({});class rye{constructor(){L(this,"tsBuffer",new Map)}isOutdated(e,n){var r;this.tsBuffer.has(e)||this.tsBuffer.set(e,new Map);var i=(r=this.tsBuffer.get(e))===null||r===void 0?void 0:r.get(n.keyIndex);return i&&i>n.creationTS?!0:(this.tsBuffer.get(e).set(n.keyIndex,n.creationTS),!1)}}function Vh(t,e){return"".concat(t,":").concat(e)}class nQ extends Error{constructor(e){super(e)}get name(){return"NotSupportedError"}}class iye extends On{setParentLogger(e){this.logger=e.getChild("[ToDeviceKeyTransport]")}constructor(e,n,r,i,s,o){super(),this.userId=e,this.deviceId=n,this.roomId=r,this.client=i,this.statistics=s,L(this,"logger",M),L(this,"onToDeviceEvent",a=>{if(a.getType()===Z.CallEncryptionKeysPrefix){var c=this.getValidEventContent(a);c&&a.getSender()&&this.receiveCallKeyEvent(a.getSender(),c)}}),this.setParentLogger(o??M)}start(){this.client.on(Le.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.off(Le.ToDeviceEvent,this.onToDeviceEvent)}sendKey(e,n,r){var i=this;return B(function*(){var s={keys:{index:n,key:e},room_id:i.roomId,member:{claimed_device_id:i.deviceId},session:{call_id:"",application:"m.call",scope:"m.room"},sent_ts:Date.now()},o=r.map(a=>({userId:a.userId,deviceId:a.deviceId})).filter(a=>!(a.userId==i.userId&&a.deviceId==i.deviceId));o.length>0?(yield i.client.encryptAndSendToDevice(Z.CallEncryptionKeysPrefix,o,s).catch(a=>{var c=a.message;if(c.includes("unknown variant")&&c.includes("send_to_device")||c.includes("not supported"))throw new nQ("The widget driver does not support to-device encryption")}),i.statistics.counters.roomEventEncryptionKeysSent+=1):i.logger.warn("No targets found for sending key")})()}receiveCallKeyEvent(e,n){this.statistics.counters.roomEventEncryptionKeysReceived+=1;var r=Date.now(),i=r-(typeof n.sent_ts=="number"?n.sent_ts:r);this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=i,this.emit(Wc.ReceivedKeys,e,n.member.claimed_device_id,n.keys.key,n.keys.index,r)}getValidEventContent(e){var n=e.getContent(),r=n.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(!n.keys||!n.keys.key||typeof n.keys.index!="number"){this.logger.warn("Malformed Event: Missing keys field");return}if(!n.member||!n.member.claimed_device_id){this.logger.warn("Malformed Event: Missing claimed_device_id");return}return n}}var p_=function(t){return t.EnabledTransportsChanged="enabled_transports_changed",t}({});class n7 extends On{constructor(e,n,r){var i;super(),i=this,this.toDeviceTransport=e,this.roomKeyTransport=n,L(this,"logger",void 0),L(this,"_enabled",{toDevice:!0,room:!1}),this.logger=(r??M).getChild("[RoomAndToDeviceTransport]"),this.toDeviceTransport.setParentLogger(this.logger),this.roomKeyTransport.setParentLogger(this.logger),this.roomKeyTransport.on(Wc.ReceivedKeys,function(){i._enabled.room||(i.logger.debug("Received room key, enabling room key transport, disabling toDevice transport"),i.setEnabled({toDevice:!1,room:!0}));for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];i.emit(Wc.ReceivedKeys,...o)}),this.toDeviceTransport.on(Wc.ReceivedKeys,function(){if(i._enabled.toDevice){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];i.emit(Wc.ReceivedKeys,...o)}else i.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(p_.EnabledTransportsChanged,e))}get enabled(){return this._enabled}start(){this.roomKeyTransport.start(),this.toDeviceTransport.start()}stop(){this.roomKeyTransport.stop(),this.toDeviceTransport.stop()}sendKey(e,n,r){var i=this;return B(function*(){if(i.logger.debug("Sending key with index ".concat(n," 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,n,r)),i._enabled.toDevice)try{yield i.toDeviceTransport.sendKey(e,n,r)}catch(s){s instanceof nQ&&!i._enabled.room&&(i.logger.warn("To device is not supported enabling room key transport, disabling toDevice transport"),i.setEnabled({toDevice:!1,room:!0}),yield i.sendKey(e,n,r))}})()}}class sye{get updateEncryptionKeyThrottle(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.updateEncryptionKeyThrottle)!==null&&e!==void 0?e:3e3}get makeKeyDelay(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.makeKeyDelay)!==null&&e!==void 0?e:3e3}get useKeyDelay(){var e,n;return(e=(n=this.joinConfig)===null||n===void 0?void 0:n.useKeyDelay)!==null&&e!==void 0?e:5e3}constructor(e,n,r,i,s,o,a){var c=this;this.userId=e,this.deviceId=n,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 l=B(function*(d){if(c.keysEventUpdateTimeout!==void 0&&(clearTimeout(c.keysEventUpdateTimeout),c.keysEventUpdateTimeout=void 0),c.lastEncryptionKeyUpdateRequest=Date.now(),!!c.joined){var h=c.getKeysForParticipant(c.userId,c.deviceId);if(!h){c.logger.warn("Tried to send encryption keys event but no keys found!");return}if(typeof d!="number"&&c.latestGeneratedKeyIndex===-1){c.logger.warn("Tried to send encryption keys event but no current key index found!");return}var m=d??c.latestGeneratedKeyIndex;c.logger.info("Try sending encryption keys event. keyIndexToSend=".concat(m," (method parameter: ").concat(d,")"));var g=h[m];try{c.statistics.counters.roomEventEncryptionKeysSent+=1;var y=c.getMemberships().filter(w=>w.sender!=null).map(w=>({userId:w.sender,deviceId:w.deviceId,membershipTs:w.createdTs()}));yield c.transport.sendKey($J(g),m,y),c.logger.debug("sendEncryptionKeysEvent participantId=".concat(c.userId,":").concat(c.deviceId," numKeys=").concat(h.length," currentKeyIndex=").concat(c.latestGeneratedKeyIndex," keyIndexToSend=").concat(m))}catch(w){if(c.keysEventUpdateTimeout===void 0){var v=HO(w,5e3);c.logger.warn("Failed to send m.call.encryption_key, retrying in ".concat(v),w),c.keysEventUpdateTimeout=setTimeout(()=>void c.sendEncryptionKeysEvent(),v)}else c.logger.info("Not scheduling key resend as another re-send is already pending")}}});return function(d){return l.apply(this,arguments)}}()),L(this,"onTransportChanged",()=>{this.requestSendCurrentKey()}),L(this,"onNewKeyReceived",(l,d,h,m,g)=>{this.logger.debug("Received key over key transport ".concat(l,":").concat(d," at index ").concat(m)),this.setEncryptionKey(l,d,m,h,g)}),L(this,"onRotateKeyTimeout",()=>{if(this.manageMediaKeys){this.makeNewKeyTimeout=void 0,this.logger.info("Making new sender key for key rotation");var l=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(l)}}),this.logger=(a??M).getChild("[EncryptionManager]")}getEncryptionKeys(){var e=new Map;for(var[n,r]of this.encryptionKeys){var i=r.map((s,o)=>({key:s.key,keyIndex:o}));e.set(n,i)}return e}join(e){var n,r,i;this.joinConfig=e,this.joined=!0,this.manageMediaKeys=(n=(r=this.joinConfig)===null||r===void 0?void 0:r.manageMediaKeys)!==null&&n!==void 0?n:this.manageMediaKeys,this.transport.on(Wc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof n7&&this.transport.on(p_.EnabledTransportsChanged,this.onTransportChanged),this.transport.start(),(i=this.joinConfig)!==null&&i!==void 0&&i.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey())}leave(){this.encryptionKeys.set(Vh(this.userId,this.deviceId),[]),this.transport.off(Wc.ReceivedKeys,this.onNewKeyReceived),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 n=new Set(e.filter(l=>!WE(l,this.userId,this.deviceId)).map(Dk)),r=new Set(this.getMemberships().filter(l=>!WE(l,this.userId,this.deviceId)).map(Dk)),i=Array.from(n).some(l=>!r.has(l)),s=Array.from(r).some(l=>!n.has(l)),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,c=Array.from(o).some(l=>!a.has(l))||Array.from(a).some(l=>!o.has(l));c&&(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,n=BJ(16),r=this.getNewEncryptionKeyIndex();return this.logger.info("Generated new key at index "+r),this.setEncryptionKey(this.userId,this.deviceId,r,n,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,n){var r;return(r=this.encryptionKeys.get(Vh(e,n)))===null||r===void 0?void 0:r.map(i=>i.key)}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.getMemberships().filter(e=>!WE(e,this.userId,this.deviceId)).map(e=>"".concat(Dk(e),":").concat(e.createdTs())))}getNewEncryptionKeyIndex(){return this.latestGeneratedKeyIndex===-1?0:(this.latestGeneratedKeyIndex+1)%256}setEncryptionKey(e,n,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(n," at index ").concat(r));var a=Bh(i),c=Vh(e,n);this.encryptionKeys.has(c)||this.encryptionKeys.set(c,[]);var l=this.encryptionKeys.get(c),d=l[r];if(d){if(d.timestamp>s){this.logger.info("Ignoring new key at index ".concat(r," for ").concat(c," as it is older than existing known key"));return}if(oye(d.key,a)){d.timestamp=s;return}}if(e===this.userId&&n===this.deviceId&&(this.latestGeneratedKeyIndex=r),l[r]={key:a,timestamp:s},o){var h=setTimeout(()=>{this.setNewKeyTimeouts.delete(h),this.logger.info("Delayed-emitting key changed event for ".concat(c," index ").concat(r)),this.onEncryptionKeysChanged(a,r,c)},this.useKeyDelay);this.setNewKeyTimeouts.add(h)}else this.onEncryptionKeysChanged(a,r,c)}}function oye(t,e){return t===e?!0:!!t&&!!e&&t.length===e.length&&t.every((n,r)=>n===e[r])}var Dk=t=>Vh(t.sender,t.deviceId);class Q$ extends On{setParentLogger(e){this.logger=e.getChild("[RoomKeyTransport]")}constructor(e,n,r,i){super(),this.room=e,this.client=n,this.statistics=r,L(this,"logger",M),this.setParentLogger(i??M)}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 n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[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()!==Z.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,n,r){var i=this;return B(function*(){var s={keys:[{index:n,key:e}],device_id:i.client.getDeviceId(),call_id:"",sent_ts:Date.now()};try{yield i.client.sendEvent(i.room.roomId,Z.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 n=e.getSender(),r=e.getContent(),i=r.device_id,s=r.call_id;if(!n){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(n,", 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(n===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 c=a.key,l=a.index;!c||l===void 0||l===null||s===void 0||s===null||typeof i!="string"||typeof s!="string"||typeof c!="string"||typeof l!="number"?this.logger.warn("Malformed call encryption_key: userId=".concat(n,", deviceId=").concat(i,", encryptionKeyIndex=").concat(l," callId=").concat(s)):(this.logger.debug("onCallEncryption userId=".concat(n,":").concat(i," encryptionKeyIndex=").concat(l," age=").concat(o,"ms")),this.emit(Wc.ReceivedKeys,n,i,c,l,e.getTs()))}}}class aye{constructor(e,n,r,i,s,o,a){this.userId=e,this.deviceId=n,this.getMemberships=r,this.transport=i,this.statistics=s,this.onEncryptionKeysChanged=o,L(this,"manageMediaKeys",!1),L(this,"participantKeyRings",new Map),L(this,"outboundSession",null),L(this,"currentKeyDistributionPromise",null),L(this,"useKeyDelay",5e3),L(this,"keyRotationGracePeriodMs",1e4),L(this,"needToEnsureKeyAgain",!1),L(this,"keyBuffer",new rye),L(this,"logger",void 0),L(this,"onTransportChanged",()=>{var c;(c=this.logger)===null||c===void 0||c.info("Transport change detected, restarting key distribution"),this.currentKeyDistributionPromise?this.currentKeyDistributionPromise.then(()=>{this.outboundSession&&(this.outboundSession.sharedWith=[],this.ensureKeyDistribution())}).catch(l=>{var d;(d=this.logger)===null||d===void 0||d.error("Failed to restart key distribution",l)}):this.outboundSession&&(this.outboundSession.sharedWith=[],this.ensureKeyDistribution())}),L(this,"onNewKeyReceived",(c,l,d,h,m)=>{var g;if(!this.manageMediaKeys){var y;(y=this.logger)===null||y===void 0||y.warn("Received key over transport ".concat(c,":").concat(l," at index ").concat(h," but media keys are disabled"));return}(g=this.logger)===null||g===void 0||g.debug("Received key over transport ".concat(c,":").concat(l," at index ").concat(h));var v=Vh(c,l),w=Bh(d),S={key:w,participantId:v,keyIndex:h,creationTS:m},R=this.keyBuffer.isOutdated(v,S);if(!R)this.addKeyToParticipant(S.key,S.keyIndex,S.participantId),this.statistics.counters.roomEventEncryptionKeysReceived+=1;else{var x;(x=this.logger)===null||x===void 0||x.info("Received an out of order key for ".concat(c,":").concat(l,", dropping it"))}}),this.logger=a?.getChild("[EncryptionManager]")}getEncryptionKeys(){return new Map(this.participantKeyRings)}addKeyToParticipant(e,n,r){this.participantKeyRings.has(r)||this.participantKeyRings.set(r,[]),this.participantKeyRings.get(r).push({key:e,keyIndex:n}),this.onEncryptionKeysChanged(e,n,r)}join(e){var n,r,i,s;this.manageMediaKeys=(n=e?.manageMediaKeys)!==null&&n!==void 0?n:!0,(r=this.logger)===null||r===void 0||r.info("Joining room"),this.useKeyDelay=(i=e?.useKeyDelay)!==null&&i!==void 0?i:1e3,this.keyRotationGracePeriodMs=(s=e?.keyRotationGracePeriodMs)!==null&&s!==void 0?s:1e4,this.transport.on(Wc.ReceivedKeys,this.onNewKeyReceived),this.transport instanceof n7&&this.transport.on(p_.EnabledTransportsChanged,this.onTransportChanged),this.transport.start()}leave(){this.transport.off(Wc.ReceivedKeys,this.onNewKeyReceived),this.transport.stop(),this.participantKeyRings.clear()}ensureKeyDistribution(){if(this.manageMediaKeys)if(this.currentKeyDistributionPromise==null){var e;(e=this.logger)===null||e===void 0||e.debug("No active rollout, start a new one"),this.currentKeyDistributionPromise=this.rolloutOutboundKey().then(()=>{var r;if((r=this.logger)===null||r===void 0||r.debug("Rollout completed"),this.currentKeyDistributionPromise=null,this.needToEnsureKeyAgain){var i;(i=this.logger)===null||i===void 0||i.debug("New Rollout needed"),this.needToEnsureKeyAgain=!1,this.ensureKeyDistribution()}})}else{var n;(n=this.logger)===null||n===void 0||n.debug("Rollout in progress, a new rollout will be started after the current one"),this.needToEnsureKeyAgain=!0}}onMembershipsUpdate(){var e;(e=this.logger)===null||e===void 0||e.trace("onMembershipsUpdate"),this.ensureKeyDistribution()}rolloutOutboundKey(){var e=this;return B(function*(){var n,r,i=e.outboundSession==null;i&&(e.outboundSession={key:e.generateRandomKey(),creationTS:Date.now(),sharedWith:[],keyId:0},e.addKeyToParticipant(e.outboundSession.key,e.outboundSession.keyId,Vh(e.userId,e.deviceId)));var s=e.getMemberships().filter(A=>A.sender!=null).map(A=>({userId:A.sender,deviceId:A.deviceId,membershipTs:A.createdTs()})),o=(n=(r=e.outboundSession)===null||r===void 0?void 0:r.sharedWith)!==null&&n!==void 0?n:[];o=o.filter(A=>!s.some(O=>A.userId==O.userId&&A.deviceId==O.deviceId&&A.membershipTs!=O.membershipTs));var a=o.filter(A=>!s.some(O=>A.userId==O.userId&&A.deviceId==O.deviceId&&A.membershipTs==O.membershipTs)),c=s.filter(A=>!o.some(O=>A.userId==O.userId&&A.deviceId==O.deviceId&&A.membershipTs==O.membershipTs)),l=[],d,h=!1;if(a.length>0){var m=e.createNewOutboundSession();h=!0,l=s,d=m}else if(c.length>0){var g=Date.now(),y=g-e.outboundSession.creationTS;if(y<e.keyRotationGracePeriodMs){var v;(v=e.logger)===null||v===void 0||v.debug("New joiners detected, but the key is recent enough (age:".concat(y,"), keeping it")),l=c,d=e.outboundSession}else{var w;(w=e.logger)===null||w===void 0||w.debug("New joiners detected, rotating the key");var S=e.createNewOutboundSession();h=!0,l=s,d=S}}else return;try{var R,x;if((R=e.logger)===null||R===void 0||R.trace("Sending key..."),yield e.transport.sendKey(Cy(d.key),d.keyId,l),e.statistics.counters.roomEventEncryptionKeysSent+=1,d.sharedWith.push(...l),(x=e.logger)===null||x===void 0||x.trace("key index:".concat(d.keyId," sent to ").concat(d.sharedWith.map(A=>"".concat(A.userId,":").concat(A.deviceId)).join(","))),h){var T,I;(T=e.logger)===null||T===void 0||T.trace("Delay Rollout for key:".concat(d.keyId,"...")),yield _p(e.useKeyDelay),(I=e.logger)===null||I===void 0||I.trace("...Delayed rollout of index:".concat(d.keyId," ")),e.addKeyToParticipant(d.key,d.keyId,Vh(e.userId,e.deviceId))}}catch(A){var k;(k=e.logger)===null||k===void 0||k.error("Failed to rollout key",A)}})()}createNewOutboundSession(){var e,n={key:this.generateRandomKey(),creationTS:Date.now(),sharedWith:[],keyId:this.nextKeyIndex()};return(e=this.logger)===null||e===void 0||e.info("creating new outbound key index:".concat(n.keyId)),this.outboundSession=n,n}nextKeyIndex(){return this.outboundSession?(this.outboundSession.keyId+1)%256:0}generateRandomKey(){var e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),e}}function Z$(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function P2(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Z$(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Z$(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var ei=function(t){return t.MembershipsChanged="memberships_changed",t.JoinStateChanged="join_state_changed",t.EncryptionKeyChanged="encryption_key_changed",t.MembershipManagerError="membership_manager_error",t.DidSendCallNotification="did_send_call_notification",t}({});class Zl extends On{get membershipStatus(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.status}get probablyLeft(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.probablyLeft}get callId(){return this._callId}static callMembershipsForRoom(e){return Zl.sessionMembershipsForRoom(e,{id:"",application:"m.call"})}static sessionMembershipsForRoom(e,n){var r=M.getChild("[MatrixRTCSession ".concat(e.roomId,"]")),i=e.getLiveTimeline().getState(Me.FORWARDS);if(!i)throw r.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);var s=i.getStateEvents(Z.GroupCallMemberPrefix),o=[];for(var a of s){var c=a.getContent(),l=Object.keys(c).length;if(l!==0){var d=[];if(l>1&&"focus_active"in c?d.push(c):l===1&&"memberships"in c&&r.warn("Legacy event found. Those are ignored, they do not contribute to the MatrixRTC session"),d.length!==0)for(var h of d)try{var m,g=new X$(a,h);if(!ff(g.sessionDescription,n)){r.info("Ignoring membership of user ".concat(g.sender," for a different session: ").concat(JSON.stringify(g.sessionDescription)));continue}if(g.isExpired()){r.info("Ignoring expired device membership ".concat(g.sender,"/").concat(g.deviceId));continue}if(!e.hasMembershipState((m=g.sender)!==null&&m!==void 0?m:"",Be.Join)){r.info("Ignoring membership of user ".concat(g.sender," who is not in the room."));continue}o.push(g)}catch(y){r.warn("Couldn't construct call membership: ",y)}}}return o.sort((y,v)=>y.createdTs()-v.createdTs()),o.length>1&&r.debug("Call memberships in room ".concat(e.roomId,", in order: "),o.map(y=>[y.createdTs(),y.sender])),o}static roomSessionForRoom(e,n){var r=Zl.sessionMembershipsForRoom(n,{id:"",application:"m.call"});return new Zl(e,n,r,{id:"",application:"m.call"})}static sessionForRoom(e,n,r){var i=Zl.sessionMembershipsForRoom(n,r);return new Zl(e,n,i,r)}get room(){return this.roomSubset}constructor(e,n,r,i){var s;super(),this.client=e,this.roomSubset=n,this.memberships=r,this.sessionDescription=i,L(this,"membershipManager",void 0),L(this,"encryptionManager",void 0),L(this,"_callId",void 0),L(this,"joinConfig",void 0),L(this,"logger",void 0),L(this,"pendingNotificationToSend",void 0),L(this,"expiryTimeout",void 0),L(this,"statistics",{counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}}),L(this,"reEmitter",new $v(this)),L(this,"onRoomMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"onRTCSessionMemberUpdate",()=>{this.recalculateSessionMembers()}),L(this,"recalculateSessionMembers",()=>{var a,c,l,d=this.memberships;this.memberships=Zl.sessionMembershipsForRoom(this.room,this.sessionDescription),this._callId=(a=this._callId)!==null&&a!==void 0?a:(c=this.memberships[0])===null||c===void 0?void 0:c.sessionDescription.id;var h=d.length!=this.memberships.length||d.some((w,S)=>!X$.equal(w,this.memberships[S]));if(h){var m,g;this.logger.info("Memberships for call in room ".concat(this.roomSubset.roomId," have changed: emitting (").concat(this.memberships.length," members)")),gve(this.logger,"emit MatrixRTCSessionEvent.MembershipsChanged",()=>{this.emit(ei.MembershipsChanged,d,this.memberships)}),(m=this.membershipManager)===null||m===void 0||m.onRTCSessionMemberUpdate(this.memberships);var y=(g=this.membershipManager)===null||g===void 0?void 0:g.ownMembership;if(this.pendingNotificationToSend&&y&&d.length===0){var v;y.eventId&&(v=this.joinConfig)!==null&&v!==void 0&&v.notificationType?this.sendCallNotify(y.eventId,this.joinConfig.notificationType,y.callIntent):this.logger.warn("Own membership eventId is undefined, cannot send call notification")}this.memberships.length>0&&(this.pendingNotificationToSend=void 0)}(l=this.encryptionManager)===null||l===void 0||l.onMembershipsUpdate(d),this.setExpiryTimer()}),this.logger=M.getChild("[MatrixRTCSession ".concat(n.roomId,"]")),this._callId=(s=r[0])===null||s===void 0?void 0:s.sessionDescription.id;var o=this.roomSubset.getLiveTimeline().getState(Me.FORWARDS);o?.on(pt.Members,this.onRoomMemberUpdate),this.setExpiryTimer()}isJoined(){var e,n;return(e=(n=this.membershipManager)===null||n===void 0?void 0:n.isJoined())!==null&&e!==void 0?e:!1}stop(){var e=this;return B(function*(){var n;yield(n=e.membershipManager)===null||n===void 0?void 0:n.leave(1e3),e.expiryTimeout&&(clearTimeout(e.expiryTimeout),e.expiryTimeout=void 0);var r=e.roomSubset.getLiveTimeline().getState(Me.FORWARDS);r?.off(pt.Members,e.onRoomMemberUpdate)})()}joinRoomSession(e,n,r){var i;if(this.isJoined()){this.logger.info("Already joined to session in room ".concat(this.roomSubset.roomId,": ignoring join call"));return}else{this.membershipManager=new fC(r,this.roomSubset,this.client,()=>this.getOldestMembership(),this.sessionDescription,this.logger),this.reEmitter.reEmit(this.membershipManager,[Hh.ProbablyLeft,Hh.StatusChanged]);var s;if(r!=null&&r.useExperimentalToDeviceTransport){this.logger.info("Using experimental to-device transport for encryption keys"),this.logger.info("Using to-device with room fallback transport for encryption keys");var[o,a]=[this.client.getUserId(),this.client.getDeviceId()],[c,l,d]=[this.roomSubset,this.client,this.statistics],h=new Q$(c,l,d),m=new iye(o,a,c.roomId,l,d);s=new n7(m,h,this.logger),this.reEmitter.reEmit(s,[p_.EnabledTransportsChanged]),this.encryptionManager=new aye(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,s,this.statistics,(g,y,v)=>{this.emit(ei.EncryptionKeyChanged,g,y,v)},this.logger)}else s=new Q$(this.roomSubset,this.client,this.statistics),this.encryptionManager=new sye(this.client.getUserId(),this.client.getDeviceId(),()=>this.memberships,s,this.statistics,(g,y,v)=>{this.emit(ei.EncryptionKeyChanged,g,y,v)})}this.joinConfig=r,this.pendingNotificationToSend=(i=this.joinConfig)===null||i===void 0?void 0:i.notificationType,this.membershipManager.join(e,n,g=>{this.logger.error("MembershipManager encountered an unrecoverable error: ",g),this.emit(ei.MembershipManagerError,g),this.emit(ei.JoinStateChanged,this.isJoined())}),this.encryptionManager.join(r),this.emit(ei.JoinStateChanged,!0)}leaveRoomSession(){var e=arguments,n=this;return B(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:void 0;if(!n.isJoined())return n.logger.info("Not joined to session in room ".concat(n.roomSubset.roomId,": ignoring leave call")),!1;n.logger.info("Leaving call session in room ".concat(n.roomSubset.roomId)),n.encryptionManager.leave();var i=n.membershipManager.leave(r);return n.emit(ei.JoinStateChanged,!1),yield i})()}getActiveFocus(){var e;return(e=this.membershipManager)===null||e===void 0?void 0:e.getActiveFocus()}getOldestMembership(){return this.memberships[0]}getConsensusCallIntent(){var e,n=(e=this.memberships.find(r=>!!r.callIntent))===null||e===void 0?void 0:e.callIntent;if(n&&this.memberships.every(r=>!r.callIntent||r.callIntent===n))return n}updateCallIntent(e){var n=this;return B(function*(){var r,i,s=(r=n.membershipManager)===null||r===void 0?void 0:r.ownMembership;if(!s)throw Error("Not connected yet");yield(i=n.membershipManager)===null||i===void 0?void 0:i.updateCallIntent(e)})()}getFocusInUse(){var e=this.getOldestMembership();if(e?.getFocusSelection()==="oldest_membership")return e.getPreferredFoci()[0]}reemitEncryptionKeys(){var e;(e=this.encryptionManager)===null||e===void 0||e.getEncryptionKeys().forEach((n,r)=>{n.forEach(i=>{this.emit(ei.EncryptionKeyChanged,i.key,i.keyIndex,r)})})}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);var e;for(var n of this.memberships){var r=n.getMsUntilExpiry();r!==void 0&&(e===void 0||r<e)&&(e=r)}e!=null&&(this.expiryTimeout=setTimeout(this.onRTCSessionMemberUpdate,e))}sendCallNotify(e,n,r){var i=this,s=function(){var a=B(function*(){var c={application:"m.call","m.mentions":{user_ids:[],room:!0},notify_type:n==="notification"?"notify":n,call_id:i.callId},l=yield i.client.sendEvent(i.roomSubset.roomId,Z.CallNotify,c);return{response:l,content:c}});return function(){return a.apply(this,arguments)}}(),o=function(){var a=B(function*(){var c={"m.mentions":{user_ids:[],room:!0},notification_type:n,"m.relates_to":{event_id:e,rel_type:vn.Reference},sender_ts:Date.now(),lifetime:3e4};r&&(c["m.call.intent"]=r);var l=yield i.client.sendEvent(i.roomSubset.roomId,Z.RTCNotification,c);return{response:l,content:c}});return function(){return a.apply(this,arguments)}}();Promise.all([s(),o()]).then(a=>{var[c,l]=a,d=P2(P2({},c.response),c.content),h=P2(P2({},l.response),l.content);this.emit(ei.DidSendCallNotification,h,d)}).catch(a=>{var[c,l]=a;return this.logger.error("Failed to send call notification",c,l)})}}var hC=function(t){return t.SessionStarted="session_started",t.SessionEnded="session_ended",t}({});class cye extends On{constructor(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{id:"",application:"m.call"};super(),this.client=n,this.sessionDescription=r,L(this,"roomSessions",new Map),L(this,"logger",void 0),L(this,"onRoom",i=>{this.refreshRoom(i)}),L(this,"onRoomState",(i,s)=>{var o=this.client.getRoom(i.getRoomId());if(!o){this.logger.error("Got room state event for unknown room ".concat(i.getRoomId(),"!"));return}i.getType()==Z.GroupCallMemberPrefix&&this.refreshRoom(o)}),this.logger=e.getChild("[MatrixRTCSessionManager]")}start(){for(var e of(n=this.client.getRooms())!==null&&n!==void 0?n:[]){var n,r=Zl.sessionForRoom(this.client,e,this.sessionDescription);r.memberships.length>0&&this.roomSessions.set(e.roomId,r)}this.client.on(Le.Room,this.onRoom),this.client.on(pt.Events,this.onRoomState)}stop(){for(var e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(Le.Room,this.onRoom),this.client.off(pt.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,Zl.sessionForRoom(this.client,e,this.sessionDescription)),this.roomSessions.get(e.roomId)}refreshRoom(e){var n=!this.roomSessions.has(e.roomId),r=this.getRoomSession(e),i=r.memberships.length>0&&!n;r.onRTCSessionMemberUpdate();var s=r.memberships.length>0;i&&!s?(this.logger.trace("Session ended for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(hC.SessionEnded,e.roomId,this.roomSessions.get(e.roomId))):!i&&s&&(this.logger.trace("Session started for ".concat(e.roomId," (").concat(r.memberships.length," members)")),this.emit(hC.SessionStarted,e.roomId,this.roomSessions.get(e.roomId)))}}function Nk(t){return e=>{var n,r;return((n=e.content)===null||n===void 0||(n=n["m.relates_to"])===null||n===void 0?void 0:n.event_id)!==t||((r=e.content)===null||r===void 0||(r=r["m.relates_to"])===null||r===void 0?void 0:r.rel_type)===wn.name}}function rQ(t){return _A.apply(this,arguments)}function _A(){return _A=B(function*(t){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");var e=new TextEncoder().encode(t),n=yield globalThis.crypto.subtle.digest("SHA-256",e);return new Uint8Array(n)}),_A.apply(this,arguments)}class dy extends Error{}dy.prototype.name="InvalidTokenError";function lye(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function uye(t){let e=t.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 lye(e)}catch{return atob(e)}}function iQ(t,e){if(typeof t!="string")throw new dy("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new dy(`Invalid token specified: missing part #${n+1}`);let i;try{i=uye(r)}catch(s){throw new dy(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new dy(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var dye={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Uc,jc,pb=(t=>(t[t.NONE=0]="NONE",t[t.ERROR=1]="ERROR",t[t.WARN=2]="WARN",t[t.INFO=3]="INFO",t[t.DEBUG=4]="DEBUG",t))(pb||{});(t=>{function e(){Uc=3,jc=dye}t.reset=e;function n(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");Uc=i}t.setLevel=n;function r(i){jc=i}t.setLogger=r})(pb||(pb={}));var kr=class Oc{constructor(e){this._name=e}debug(...e){Uc>=4&&jc.debug(Oc._format(this._name,this._method),...e)}info(...e){Uc>=3&&jc.info(Oc._format(this._name,this._method),...e)}warn(...e){Uc>=2&&jc.warn(Oc._format(this._name,this._method),...e)}error(...e){Uc>=1&&jc.error(Oc._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const n=Object.create(this);return n._method=e,n.debug("begin"),n}static createStatic(e,n){const r=new Oc(`${e}.${n}`);return r.debug("begin"),r}static _format(e,n){const r=`[${e}]`;return n?`${r} ${n}:`:r}static debug(e,...n){Uc>=4&&jc.debug(Oc._format(e),...n)}static info(e,...n){Uc>=3&&jc.info(Oc._format(e),...n)}static warn(e,...n){Uc>=2&&jc.warn(Oc._format(e),...n)}static error(e,...n){Uc>=1&&jc.error(Oc._format(e),...n)}};pb.reset();var pC=class{static decode(t){try{return iQ(t)}catch(e){throw kr.error("JwtUtils.decode",e),e}}static async generateSignedJwt(t,e,n){const r=nc.encodeBase64Url(new TextEncoder().encode(JSON.stringify(t))),i=nc.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),s=`${r}.${i}`,o=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,new TextEncoder().encode(s)),a=nc.encodeBase64Url(new Uint8Array(o));return`${s}.${a}`}},fye="10000000-1000-4000-8000-100000000000",SA=t=>btoa([...new Uint8Array(t)].map(e=>String.fromCharCode(e)).join("")),sQ=class Mc{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return fye.replace(/[018]/g,n=>(+n^Mc._randomWord()&15>>+n/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return Mc.generateUUIDv4()+Mc.generateUUIDv4()+Mc.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 SA(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(n){throw kr.error("CryptoUtils.generateCodeChallenge",n),n}}static generateBasicAuth(e,n){const i=new TextEncoder().encode([e,n].join(":"));return SA(i)}static async hash(e,n){const r=new TextEncoder().encode(n),i=await crypto.subtle.digest(e,r);return new Uint8Array(i)}static async customCalculateJwkThumbprint(e){let n;switch(e.kty){case"RSA":n={e:e.e,kty:e.kty,n:e.n};break;case"EC":n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":n={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":n={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const r=await Mc.hash("SHA-256",JSON.stringify(n));return Mc.encodeBase64Url(r)}static async generateDPoPProof({url:e,accessToken:n,httpMethod:r,keyPair:i,nonce:s}){let o,a;const c={jti:window.crypto.randomUUID(),htm:r??"GET",htu:e,iat:Math.floor(Date.now()/1e3)};n&&(o=await Mc.hash("SHA-256",n),a=Mc.encodeBase64Url(o),c.ath=a),s&&(c.nonce=s);try{const l=await crypto.subtle.exportKey("jwk",i.publicKey),d={alg:"ES256",typ:"dpop+jwt",jwk:{crv:l.crv,kty:l.kty,x:l.x,y:l.y}};return await pC.generateSignedJwt(d,c,i.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(e){try{const n=await crypto.subtle.exportKey("jwk",e.publicKey);return await Mc.customCalculateJwkThumbprint(n)}catch(n){throw n instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${n.message}`):n}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};sQ.encodeBase64Url=t=>SA(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var nc=sQ,hye=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new kr(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const n=this._callbacks.lastIndexOf(e);n>=0&&this._callbacks.splice(n,1)}async raise(...e){this._logger.debug("raise:",...e);for(const n of this._callbacks)await n(...e)}},mC=class YE extends hye{constructor(){super(...arguments),this._logger=new kr(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-YE.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=YE.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const n=this._logger.create("init");e=Math.max(Math.floor(e),1);const r=YE.getEpochTime()+e;if(this.expiration===r&&this._timerHandle){n.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),n.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)}},eB=class{static readParams(t,e="query"){if(!t)throw new TypeError("Invalid URL");const r=new URL(t,"http://127.0.0.1")[e==="fragment"?"hash":"search"];return new URLSearchParams(r.slice(1))}},EA=";",iv=class extends Error{constructor(t,e){var n,r,i;if(super(t.error_description||t.error||""),this.form=e,this.name="ErrorResponse",!t.error)throw kr.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=t.error,this.error_description=(n=t.error_description)!=null?n:null,this.error_uri=(r=t.error_uri)!=null?r:null,this.state=t.userState,this.session_state=(i=t.session_state)!=null?i:null,this.url_state=t.url_state}},pye=class extends Error{constructor(t){super(t),this.name="ErrorTimeout"}},mye=class{constructor(){this._logger=new kr("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(t){return this._logger.create(`getItem('${t}')`),this._data[t]}setItem(t,e){this._logger.create(`setItem('${t}')`),this._data[t]=e}removeItem(t){this._logger.create(`removeItem('${t}')`),delete this._data[t]}get length(){return Object.getOwnPropertyNames(this._data).length}key(t){return Object.getOwnPropertyNames(this._data)[t]}},wA=class extends Error{constructor(t,e){super(e),this.name="ErrorDPoPNonce",this.nonce=t}},r7=class{constructor(t=[],e=null,n={}){this._jwtHandler=e,this._extraHeaders=n,this._logger=new kr("JsonService"),this._contentTypes=[],this._contentTypes.push(...t,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(t,e={}){const{timeoutInSeconds:n,...r}=e;if(!n)return await fetch(t,r);const i=new AbortController,s=setTimeout(()=>i.abort(),n*1e3);try{return await fetch(t,{...e,signal:i.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new pye("Network timed out"):o}finally{clearTimeout(s)}}async getJson(t,{token:e,credentials:n,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:",t),o=await this.fetchWithTimeout(t,{method:"GET",headers:s,timeoutInSeconds:r,credentials:n})}catch(l){throw i.error("Network Error"),l}i.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find(l=>a.startsWith(l))&&i.throw(new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${t}`)),o.ok&&this._jwtHandler&&a?.startsWith("application/jwt"))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(l){throw i.error("Error parsing JSON response",l),o.ok?l:new Error(`${o.statusText} (${o.status})`)}if(!o.ok)throw i.error("Error from server:",c),c.error?new iv(c):new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`);return c}async postForm(t,{body:e,basicAuth:n,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};n!==void 0&&(a.Authorization="Basic "+n),this.appendExtraHeaders(a);let c;try{o.debug("url:",t),c=await this.fetchWithTimeout(t,{method:"POST",headers:a,body:e,timeoutInSeconds:r,credentials:i})}catch(m){throw o.error("Network error"),m}o.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find(m=>l.startsWith(m)))throw new Error(`Invalid response Content-Type: ${l??"undefined"}, from URL: ${t}`);const d=await c.text();let h={};if(d)try{h=JSON.parse(d)}catch(m){throw o.error("Error parsing JSON response",m),c.ok?m:new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",h),c.headers.has("dpop-nonce")){const m=c.headers.get("dpop-nonce");throw new wA(m,`${JSON.stringify(h)}`)}throw h.error?new iv(h,e):new Error(`${c.statusText} (${c.status}): ${JSON.stringify(h)}`)}return h}appendExtraHeaders(t){const e=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),r=["authorization","accept","content-type"];n.length!==0&&n.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!==""&&(t[i]=s)})}},oQ=class{constructor(t){this._settings=t,this._logger=new kr("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new r7(["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 t=this._logger.create("getMetadata");if(this._metadata)return t.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw t.throw(new Error("No authority or metadataUrl configured on settings")),null;t.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.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(t=!0){return this._getMetadataProperty("token_endpoint",t)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(t=!0){return this._getMetadataProperty("revocation_endpoint",t)}getKeysEndpoint(t=!0){return this._getMetadataProperty("jwks_uri",t)}async _getMetadataProperty(t,e=!1){const n=this._logger.create(`_getMetadataProperty('${t}')`),r=await this.getMetadata();if(n.debug("resolved"),r[t]===void 0){if(e===!0){n.warn("Metadata does not contain optional property");return}n.throw(new Error("Metadata does not contain property "+t))}return r[t]}async getSigningKeys(){const t=this._logger.create("getSigningKeys");if(this._signingKeys)return t.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);t.debug("got jwks_uri",e);const n=await this._jsonService.getJson(e,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(t.debug("got key set",n),!Array.isArray(n.keys))throw t.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},rT=class{constructor({prefix:t="oidc.",store:e=localStorage}={}){this._logger=new kr("WebStorageStateStore"),this._store=e,this._prefix=t}async set(t,e){this._logger.create(`set('${t}')`),t=this._prefix+t,await this._store.setItem(t,e)}async get(t){return this._logger.create(`get('${t}')`),t=this._prefix+t,await this._store.getItem(t)}async remove(t){this._logger.create(`remove('${t}')`),t=this._prefix+t;const e=await this._store.getItem(t);return await this._store.removeItem(t),e}async getAllKeys(){this._logger.create("getAllKeys");const t=await this._store.length,e=[];for(let n=0;n<t;n++){const r=await this._store.key(n);r&&r.indexOf(this._prefix)===0&&e.push(r.substr(this._prefix.length))}return e}},gye="code",vye="openid",yye="client_secret_post",bye=60*15,CA=class{constructor({authority:t,metadataUrl:e,metadata:n,signingKeys:r,metadataSeed:i,client_id:s,client_secret:o,response_type:a=gye,scope:c=vye,redirect_uri:l,post_logout_redirect_uri:d,client_authentication:h=yye,prompt:m,display:g,max_age:y,ui_locales:v,acr_values:w,resource:S,response_mode:R,filterProtocolClaims:x=!0,loadUserInfo:T=!1,requestTimeoutInSeconds:I,staleStateAgeInSeconds:k=bye,mergeClaimsStrategy:A={array:"replace"},disablePKCE:O=!1,stateStore:D,revokeTokenAdditionalContentTypes:N,fetchRequestCredentials:U,refreshTokenAllowedScope:$,extraQueryParams:K={},extraTokenParams:Y={},extraHeaders:G={},dpop:F,omitScopeWhenRequesting:q=!1}){var z;if(this.authority=t,e?this.metadataUrl=e:(this.metadataUrl=t,t&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=n,this.metadataSeed=i,this.signingKeys=r,this.client_id=s,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=d,this.client_authentication=h,this.prompt=m,this.display=g,this.max_age=y,this.ui_locales=v,this.acr_values=w,this.resource=S,this.response_mode=R,this.filterProtocolClaims=x??!0,this.loadUserInfo=!!T,this.staleStateAgeInSeconds=k,this.mergeClaimsStrategy=A,this.omitScopeWhenRequesting=q,this.disablePKCE=!!O,this.revokeTokenAdditionalContentTypes=N,this.fetchRequestCredentials=U||"same-origin",this.requestTimeoutInSeconds=I,D)this.stateStore=D;else{const W=typeof window<"u"?window.localStorage:new mye;this.stateStore=new rT({store:W})}if(this.refreshTokenAllowedScope=$,this.extraQueryParams=K,this.extraTokenParams=Y,this.extraHeaders=G,this.dpop=F,this.dpop&&!((z=this.dpop)!=null&&z.store))throw new Error("A DPoPStore is required when dpop is enabled")}},_ye=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new kr("UserInfoService"),this._getClaimsFromJwt=async n=>{const r=this._logger.create("_getClaimsFromJwt");try{const i=pC.decode(n);return r.debug("JWT decoding successful"),i}catch(i){throw r.error("Error parsing JWT response"),i}},this._jsonService=new r7(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(t){const e=this._logger.create("getClaims");t||this._logger.throw(new Error("No token passed"));const n=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",n);const r=await this._jsonService.getJson(n,{token:t,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("got claims",r),r}},aQ=class{constructor(t,e){this._settings=t,this._metadataService=e,this._logger=new kr("TokenClient"),this._jsonService=new r7(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:t="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:i,...s}){const o=this._logger.create("exchangeCode");n||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:t,redirect_uri:e});for(const[h,m]of Object.entries(s))m!=null&&a.set(h,m);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw o.throw(new Error("A client_secret is required")),null;c=nc.generateBasicAuth(n,r);break;case"client_secret_post":a.append("client_id",n),r&&a.append("client_secret",r);break}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),d}async exchangeCredentials({grant_type:t="password",client_id:e=this._settings.client_id,client_secret:n=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:t});this._settings.omitScopeWhenRequesting||o.set("scope",r);for(const[d,h]of Object.entries(i))h!=null&&o.set(d,h);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw s.throw(new Error("A client_secret is required")),null;a=nc.generateBasicAuth(e,n);break;case"client_secret_post":o.append("client_id",e),n&&o.append("client_secret",n);break}const c=await this._metadataService.getTokenEndpoint(!1);s.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return s.debug("got response"),l}async exchangeRefreshToken({grant_type:t="refresh_token",client_id:e=this._settings.client_id,client_secret:n=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:t});for(const[h,m]of Object.entries(s))Array.isArray(m)?m.forEach(g=>a.append(h,g)):m!=null&&a.set(h,m);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw o.throw(new Error("A client_secret is required")),null;c=nc.generateBasicAuth(e,n);break;case"client_secret_post":a.append("client_id",e),n&&a.append("client_secret",n);break}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return o.debug("got response"),d}async revoke(t){var e;const n=this._logger.create("revoke");t.token||n.throw(new Error("A token is required"));const r=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${(e=t.token_type_hint)!=null?e:"default token type"}`);const i=new URLSearchParams;for(const[s,o]of Object.entries(t))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}),n.debug("got response")}},Sye=class{constructor(t,e,n){this._settings=t,this._metadataService=e,this._claimsService=n,this._logger=new kr("ResponseValidator"),this._userInfoService=new _ye(this._settings,this._metadataService),this._tokenClient=new aQ(this._settings,this._metadataService)}async validateSigninResponse(t,e,n){const r=this._logger.create("validateSigninResponse");this._processSigninState(t,e),r.debug("state processed"),await this._processCode(t,e,n),r.debug("code processed"),t.isOpenId&&this._validateIdTokenAttributes(t),r.debug("tokens validated"),await this._processClaims(t,e?.skipUserInfo,t.isOpenId),r.debug("claims processed")}async validateCredentialsResponse(t,e){const n=this._logger.create("validateCredentialsResponse");t.isOpenId&&t.id_token&&this._validateIdTokenAttributes(t),n.debug("tokens validated"),await this._processClaims(t,e,t.isOpenId),n.debug("claims processed")}async validateRefreshResponse(t,e){var n,r;const i=this._logger.create("validateRefreshResponse");t.userState=e.data,(n=t.session_state)!=null||(t.session_state=e.session_state),(r=t.scope)!=null||(t.scope=e.scope),t.isOpenId&&t.id_token&&(this._validateIdTokenAttributes(t,e.id_token),i.debug("ID Token validated")),t.id_token||(t.id_token=e.id_token,t.profile=e.profile);const s=t.isOpenId&&!!t.id_token;await this._processClaims(t,!1,s),i.debug("claims processed")}validateSignoutResponse(t,e){const n=this._logger.create("validateSignoutResponse");if(e.id!==t.state&&n.throw(new Error("State does not match")),n.debug("state validated"),t.userState=e.data,t.error)throw n.warn("Response was error",t.error),new iv(t)}_processSigninState(t,e){var n;const r=this._logger.create("_processSigninState");if(e.id!==t.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"),t.userState=e.data,t.url_state=e.url_state,(n=t.scope)!=null||(t.scope=e.scope),t.error)throw r.warn("Response was error",t.error),new iv(t);e.code_verifier&&!t.code&&r.throw(new Error("Expected code in response"))}async _processClaims(t,e=!1,n=!0){const r=this._logger.create("_processClaims");if(t.profile=this._claimsService.filterProtocolClaims(t.profile),e||!this._settings.loadUserInfo||!t.access_token){r.debug("not loading user info");return}r.debug("loading user info");const i=await this._userInfoService.getClaims(t.access_token);r.debug("user info claims received from user info endpoint"),n&&i.sub!==t.profile.sub&&r.throw(new Error("subject from UserInfo response does not match subject in ID Token")),t.profile=this._claimsService.mergeClaims(t.profile,this._claimsService.filterProtocolClaims(i)),r.debug("user info claims received, updated profile:",t.profile)}async _processCode(t,e,n){const r=this._logger.create("_processCode");if(t.code){r.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:t.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,extraHeaders:n,...e.extraTokenParams});Object.assign(t,i)}else r.debug("No code to process")}_validateIdTokenAttributes(t,e){var n;const r=this._logger.create("_validateIdTokenAttributes");r.debug("decoding ID Token JWT");const i=pC.decode((n=t.id_token)!=null?n:"");if(i.sub||r.throw(new Error("ID Token is missing a subject claim")),e){const s=pC.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"))}t.profile=i}},gC=class TA{constructor(e){this.id=e.id||nc.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=mC.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new kr("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 kr.createStatic("State","fromStorageString"),Promise.resolve(new TA(JSON.parse(e)))}static async clearStaleState(e,n){const r=kr.createStatic("State","clearStaleState"),i=mC.getEpochTime()-n,s=await e.getAllKeys();r.debug("got keys",s);for(let o=0;o<s.length;o++){const a=s[o],c=await e.get(a);let l=!1;if(c)try{const d=await TA.fromStorageString(c);r.debug("got item from key:",a,d.created),d.created<=i&&(l=!0)}catch(d){r.error("Error parsing state for key:",a,d),l=!0}else r.debug("no item in storage for key:",a),l=!0;l&&(r.debug("removed item for key:",a),e.remove(a))}}},i7=class RA extends gC{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 n=e.code_verifier===!0?nc.generateCodeVerifier():e.code_verifier||void 0,r=n?await nc.generateCodeChallenge(n):void 0;return new RA({...e,code_verifier:n,code_challenge:r})}toStorageString(){return new kr("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){kr.createStatic("SigninState","fromStorageString");const n=JSON.parse(e);return RA.create(n)}},cQ=class lQ{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:n,client_id:r,redirect_uri:i,response_type:s,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:d,nonce:h,url_state:m,resource:g,skipUserInfo:y,extraQueryParams:v,extraTokenParams:w,disablePKCE:S,dpopJkt:R,omitScopeWhenRequesting:x,...T}){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(!n)throw this._logger.error("create: No authority passed"),new Error("authority");const I=await i7.create({data:a,request_type:l,url_state:m,code_verifier:!S,client_id:r,authority:n,redirect_uri:i,response_mode:c,client_secret:d,scope:o,extraTokenParams:w,skipUserInfo:y}),k=new URL(e);k.searchParams.append("client_id",r),k.searchParams.append("redirect_uri",i),k.searchParams.append("response_type",s),x||k.searchParams.append("scope",o),h&&k.searchParams.append("nonce",h),R&&k.searchParams.append("dpop_jkt",R);let A=I.id;m&&(A=`${A}${EA}${m}`),k.searchParams.append("state",A),I.code_challenge&&(k.searchParams.append("code_challenge",I.code_challenge),k.searchParams.append("code_challenge_method","S256")),g&&(Array.isArray(g)?g:[g]).forEach(D=>k.searchParams.append("resource",D));for(const[O,D]of Object.entries({response_mode:c,...T,...v}))D!=null&&k.searchParams.append(O,D.toString());return new lQ({url:k.href,state:I})}};cQ._logger=new kr("SigninRequest");var Eye=cQ,wye="openid",XE=class{constructor(t){if(this.access_token="",this.token_type="",this.profile={},this.state=t.get("state"),this.session_state=t.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(EA);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(EA))}this.error=t.get("error"),this.error_description=t.get("error_description"),this.error_uri=t.get("error_uri"),this.code=t.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-mC.getEpochTime()}set expires_in(t){typeof t=="string"&&(t=Number(t)),t!==void 0&&t>=0&&(this.expires_at=Math.floor(t)+mC.getEpochTime())}get isOpenId(){var t;return((t=this.scope)==null?void 0:t.split(" ").includes(wye))||!!this.id_token}},Cye=class{constructor({url:t,state_data:e,id_token_hint:n,post_logout_redirect_uri:r,extraQueryParams:i,request_type:s,client_id:o}){if(this._logger=new kr("SignoutRequest"),!t)throw this._logger.error("ctor: No url passed"),new Error("url");const a=new URL(t);n&&a.searchParams.append("id_token_hint",n),o&&a.searchParams.append("client_id",o),r&&(a.searchParams.append("post_logout_redirect_uri",r),e&&(this.state=new gC({data:e,request_type:s}),a.searchParams.append("state",this.state.id)));for(const[c,l]of Object.entries({...i}))l!=null&&a.searchParams.append(c,l.toString());this.url=a.href}},Tye=class{constructor(t){this.state=t.get("state"),this.error=t.get("error"),this.error_description=t.get("error_description"),this.error_uri=t.get("error_uri")}},Rye=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Iye=["sub","iss","aud","exp","iat"],kye=class{constructor(t){this._settings=t,this._logger=new kr("ClaimsService")}filterProtocolClaims(t){const e={...t};if(this._settings.filterProtocolClaims){let n;Array.isArray(this._settings.filterProtocolClaims)?n=this._settings.filterProtocolClaims:n=Rye;for(const r of n)Iye.includes(r)||delete e[r]}return e}mergeClaims(t,e){const n={...t};for(const[r,i]of Object.entries(e))if(n[r]!==i)if(Array.isArray(n[r])||Array.isArray(i))if(this._settings.mergeClaimsStrategy.array=="replace")n[r]=i;else{const s=Array.isArray(n[r])?n[r]:[n[r]];for(const o of Array.isArray(i)?i:[i])s.includes(o)||s.push(o);n[r]=s}else typeof n[r]=="object"&&typeof i=="object"?n[r]=this.mergeClaims(n[r],i):n[r]=i;return n}},xye=class{constructor(t,e){this.keys=t,this.nonce=e}},s7=class{constructor(t,e){this._logger=new kr("OidcClient"),this.settings=t instanceof CA?t:new CA(t),this.metadataService=e??new oQ(this.settings),this._claimsService=new kye(this.settings),this._validator=new Sye(this.settings,this.metadataService,this._claimsService),this._tokenClient=new aQ(this.settings,this.metadataService)}async createSigninRequest({state:t,request:e,request_uri:n,request_type:r,id_token_hint:i,login_hint:s,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:d=this.settings.scope,redirect_uri:h=this.settings.redirect_uri,prompt:m=this.settings.prompt,display:g=this.settings.display,max_age:y=this.settings.max_age,ui_locales:v=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:S=this.settings.resource,response_mode:R=this.settings.response_mode,extraQueryParams:x=this.settings.extraQueryParams,extraTokenParams:T=this.settings.extraTokenParams,dpopJkt:I,omitScopeWhenRequesting:k=this.settings.omitScopeWhenRequesting}){const A=this._logger.create("createSigninRequest");if(l!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const O=await this.metadataService.getAuthorizationEndpoint();A.debug("Received authorization endpoint",O);const D=await Eye.create({url:O,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:h,response_type:l,scope:d,state_data:t,url_state:c,prompt:m,display:g,max_age:y,ui_locales:v,id_token_hint:i,login_hint:s,acr_values:w,dpopJkt:I,resource:S,request:e,request_uri:n,extraQueryParams:x,extraTokenParams:T,request_type:r,response_mode:R,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:k});await this.clearStaleState();const N=D.state;return await this.settings.stateStore.set(N.id,N.toStorageString()),D}async readSigninResponseState(t,e=!1){const n=this._logger.create("readSigninResponseState"),r=new XE(eB.readParams(t,this.settings.response_mode));if(!r.state)throw n.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await i7.fromStorageString(i),response:r}}async processSigninResponse(t,e){const n=this._logger.create("processSigninResponse"),{state:r,response:i}=await this.readSigninResponseState(t,!0);if(n.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 wA&&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(t,e){let n,r;return(await t.getAllKeys()).includes(this.settings.client_id)?(r=await t.get(this.settings.client_id),r.nonce!==e&&e&&(r.nonce=e,await t.set(this.settings.client_id,r))):(n=await nc.generateDPoPKeys(),r=new xye(n,e),await t.set(this.settings.client_id,r)),await nc.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:r.keys,nonce:r.nonce})}async processResourceOwnerPasswordCredentials({username:t,password:e,skipUserInfo:n=!1,extraTokenParams:r={}}){const i=await this._tokenClient.exchangeCredentials({username:t,password:e,...r}),s=new XE(new URLSearchParams);return Object.assign(s,i),await this._validator.validateCredentialsResponse(s,n),s}async useRefreshToken({state:t,redirect_uri:e,resource:n,timeoutInSeconds:r,extraHeaders:i,extraTokenParams:s}){var o;const a=this._logger.create("useRefreshToken");let c;if(this.settings.refreshTokenAllowedScope===void 0)c=t.scope;else{const h=this.settings.refreshTokenAllowedScope.split(" ");c=(((o=t.scope)==null?void 0:o.split(" "))||[]).filter(g=>h.includes(g)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const h=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:h}}let l;try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:c,redirect_uri:e,resource:n,timeoutInSeconds:r,extraHeaders:i,...s})}catch(h){if(h instanceof wA&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,h.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:t.refresh_token,scope:c,redirect_uri:e,resource:n,timeoutInSeconds:r,extraHeaders:i,...s});else throw h}const d=new XE(new URLSearchParams);return Object.assign(d,l),a.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...t,scope:c}),d}async createSignoutRequest({state:t,id_token_hint:e,client_id:n,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),!n&&i&&!e&&(n=this.settings.client_id);const c=new Cye({url:a,id_token_hint:e,client_id:n,post_logout_redirect_uri:i,state_data:t,extraQueryParams:s,request_type:r});await this.clearStaleState();const l=c.state;return l&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),c}async readSignoutResponseState(t,e=!1){const n=this._logger.create("readSignoutResponseState"),r=new Tye(eB.readParams(t,this.settings.response_mode));if(!r.state){if(n.debug("No state in response"),r.error)throw n.warn("Response was error:",r.error),new iv(r);return{state:void 0,response:r}}const i=await this.settings.stateStore[e?"remove":"get"](r.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:await gC.fromStorageString(i),response:r}}async processSignoutResponse(t){const e=this._logger.create("processSignoutResponse"),{state:n,response:r}=await this.readSignoutResponseState(t,!0);return n?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(r,n)):e.debug("No state from storage; skipping response validation"),r}clearStaleState(){return this._logger.create("clearStaleState"),gC.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(t,e){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:t,token_type_hint:e})}},ts=function(t){return t.NotSupported="OIDC authentication not supported",t.Misconfigured="OIDC is misconfigured",t.General="Something went wrong with OIDC discovery",t.OpSupport="Configured OIDC OP does not support required functions",t.DynamicRegistrationNotSupported="Dynamic registration not supported",t.DynamicRegistrationFailed="Dynamic registration failed",t.DynamicRegistrationInvalid="Dynamic registration invalid response",t.CodeExchangeFailed="Failed to exchange code for token",t.InvalidBearerTokenResponse="Invalid bearer token response",t.InvalidIdToken="Invalid ID token",t.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",t}({}),o7=t=>!!t&&typeof t=="object"&&!Array.isArray(t),mu=(t,e)=>!t[e]||!ky(t,e)?(M.error("Missing or invalid property: ".concat(e)),!1):!0,ky=(t,e)=>t[e]&&typeof t[e]!="string"?(M.error("Invalid property: ".concat(e)),!1):!0,tB=(t,e)=>t[e]&&(!Array.isArray(t[e])||!t[e].every(n=>typeof n=="string"))?(M.error("Invalid property: ".concat(e)),!1):!0,Uk=(t,e,n)=>{var r=t[e];return!r||!Array.isArray(r)||!r.includes(n)?(M.error("Invalid property: ".concat(e,". ").concat(n," is required.")),!1):!0},uQ=t=>{if(!o7(t))throw M.error("Issuer configuration not found or malformed"),new Error(ts.OpSupport);var e=[mu(t,"issuer"),mu(t,"authorization_endpoint"),mu(t,"token_endpoint"),mu(t,"revocation_endpoint"),ky(t,"registration_endpoint"),ky(t,"account_management_uri"),ky(t,"device_authorization_endpoint"),tB(t,"account_management_actions_supported"),Uk(t,"response_types_supported","code"),Uk(t,"grant_types_supported","authorization_code"),Uk(t,"code_challenge_methods_supported","S256"),tB(t,"prompt_values_supported")].some(n=>!n);if(!e)return t;throw M.error("Issuer configuration not valid"),new Error(ts.OpSupport)},dQ=t=>{try{return iQ(t)}catch(e){throw M.error("Could not decode id_token",e),e}},fQ=(t,e,n,r)=>{try{if(!t)throw new Error("No ID token");var i=dQ(t);if(i.iss!==e)throw new Error("Invalid issuer");var s=typeof i.aud=="string"?[i.aud]:i.aud;if(!s.includes(n))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 M.error("Invalid ID token",o),new Error(ts.InvalidIdToken)}};function hQ(t){if(!o7(t))throw M.error("Stored user state not found"),new Error(ts.MissingOrInvalidStoredState);var e=[mu(t,"homeserverUrl"),mu(t,"nonce"),ky(t,"identityServerUrl")].some(n=>!n);if(e)throw new Error(ts.MissingOrInvalidStoredState)}var Aye=t=>o7(t)&&mu(t,"token_type")&&t.token_type.toLowerCase()==="bearer"&&mu(t,"access_token")&&mu(t,"refresh_token")&&(!("expires_in"in t)||typeof t.expires_in=="number");function pQ(t){if(!Aye(t))throw new Error(ts.InvalidBearerTokenResponse)}function nB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function vC(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?nB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):nB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var iT=t=>{var e=t??To(10);return"openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:".concat(e)},Pye=function(){var t=B(function*(e){if(!globalThis.crypto.subtle)return M.warn("A secure context is required to generate code challenge. Using plain text code challenge"),e;var n=yield rQ(e);return Z3(n)});return function(n){return t.apply(this,arguments)}}(),Lye=t=>{var{redirectUri:e}=t;return{scope:iT(),redirectUri:e,state:To(8),nonce:To(8),codeVerifier:To(64)}},Oye=function(){var t=B(function*(e,n,r){var{scope:i,redirectUri:s,state:o,nonce:a,codeVerifier:c}=r,l=new URL(e);return l.searchParams.append("response_mode","query"),l.searchParams.append("response_type","code"),l.searchParams.append("redirect_uri",s),l.searchParams.append("client_id",n),l.searchParams.append("state",o),l.searchParams.append("scope",i),l.searchParams.append("nonce",a),l.searchParams.append("code_challenge_method","S256"),l.searchParams.append("code_challenge",yield Pye(c)),l.toString()});return function(n,r,i){return t.apply(this,arguments)}}(),Mye=function(){var t=B(function*(e){var{metadata:n,redirectUri:r,clientId:i,homeserverUrl:s,identityServerUrl:o,nonce:a,prompt:c,urlState:l,loginHint:d}=e,h=iT(),m=new s7(vC(vC({},n),{},{client_id:i,redirect_uri:r,authority:n.issuer,response_mode:"query",response_type:"code",scope:h,stateStore:new rT({prefix:"mx_oidc_",store:window.sessionStorage})})),g={homeserverUrl:s,nonce:a,identityServerUrl:o},y=yield m.createSigninRequest({state:g,nonce:a,prompt:c,url_state:l,login_hint:d});return y.url});return function(n){return t.apply(this,arguments)}}(),Dye=t=>({id_token:t.id_token,scope:t.scope,expires_at:t.expires_at,refresh_token:t.refresh_token,access_token:t.access_token,token_type:"Bearer"}),Nye=function(){var t=B(function*(e,n){var r=new URL(window.location.origin);r.searchParams.append("code",e),r.searchParams.append("state",n),pb.setLogger(M);try{var i=new XE(r.searchParams),s=new rT({prefix:"mx_oidc_",store:window.sessionStorage}),o=yield s.get(i.state);if(!o)throw new Error(ts.MissingOrInvalidStoredState);var a=yield i7.fromStorageString(o),c=new s7(vC(vC({},a),{},{stateStore:s})),l=yield c.processSigninResponse(r.href),d=l.userState;hQ(d),pQ(l),fQ(l.id_token,c.settings.authority,c.settings.client_id,d.nonce);var h=Dye(l);return{oidcClientSettings:{clientId:c.settings.client_id,issuer:c.settings.authority},tokenResponse:h,homeserverUrl:d.homeserverUrl,identityServerUrl:d.identityServerUrl,idTokenClaims:l.profile}}catch(g){M.error("Oidc login failed",g);var m=g.message;throw Object.values(ts).includes(m)?g:new Error(ts.CodeExchangeFailed)}});return function(n,r){return t.apply(this,arguments)}}();function rB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function iB(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?rB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):rB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var a7=function(){var t=B(function*(e){var n=new URL(".well-known/openid-configuration",e),r=yield fetch(n,{method:de.Get,signal:J3(5e3)}),i=yield r.json();return c7(i)});return function(n){return t.apply(this,arguments)}}(),c7=function(){var t=B(function*(e){var n=uQ(e),r=new CA({authority:n.issuer,metadata:n,redirect_uri:"",client_id:""}),i=new oQ(r);return iB(iB({},n),{},{signingKeys:yield i.getSigningKeys()})});return function(n){return t.apply(this,arguments)}}(),Uye="urn:ietf:params:oauth:grant-type:device_code",jk=(t,e)=>{if(!e)return!1;var n=new URL(e);return!(n.protocol!==t.protocol||n.hostname!==t.hostname&&!n.hostname.endsWith(".".concat(t.hostname)))},jye=function(){var t=B(function*(e,n){if(!e.registration_endpoint)throw new Error(ts.DynamicRegistrationNotSupported);var r=["authorization_code","refresh_token"];if(r.some(d=>!e.grant_types_supported.includes(d)))throw new Error(ts.DynamicRegistrationNotSupported);var i=new URL(n.clientUri),s={client_name:n.clientName,client_uri:n.clientUri,response_types:["code"],grant_types:r,redirect_uris:n.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:n.applicationType,contacts:n.contacts,logo_uri:jk(i,n.logoUri)?n.logoUri:void 0,policy_uri:jk(i,n.policyUri)?n.policyUri:void 0,tos_uri:jk(i,n.tosUri)?n.tosUri:void 0},o={Accept:"application/json","Content-Type":"application/json"};try{var a=yield fetch(e.registration_endpoint,{method:de.Post,headers:o,body:JSON.stringify(s)});if(a.status>=400)throw new Error(ts.DynamicRegistrationFailed);var c=yield a.json(),l=c.client_id;if(!l||typeof l!="string")throw new Error(ts.DynamicRegistrationInvalid);return l}catch(d){throw Object.values(ts).includes(d.message)?d:(M.error("Dynamic registration request failed",d),new Error(ts.DynamicRegistrationFailed))}});return function(n,r){return t.apply(this,arguments)}}();class Fye{constructor(e,n,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,n,i,r)}initialiseOidcClient(e,n,r,i){var s=this;return B(function*(){try{var o,a=yield a7(e),c=iT(r);s.oidcClient=new s7({metadata:a,signingKeys:(o=a.signingKeys)!==null&&o!==void 0?o:void 0,client_id:n,scope:c,redirect_uri:i,authority:a.issuer,stateStore:new rT({prefix:"mx_oidc_",store:window.sessionStorage})})}catch(l){throw M.error("Failed to initialise OIDC client.",l),new Error("Failed to initialise OIDC client.")}})()}doRefreshAccessToken(e){var n=this;return B(function*(){n.inflightRefreshRequest||(n.inflightRefreshRequest=n.getNewTokens(e));try{var r=yield n.inflightRefreshRequest;return r}catch(i){throw i instanceof iv?new VO(i):i}finally{n.inflightRefreshRequest=void 0}})()}persistTokens(e){return B(function*(){})()}getNewTokens(e){var n=this;return B(function*(){if(!n.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:n.idTokenClaims},i=Date.now(),s=yield n.oidcClient.useRefreshToken({state:r,timeoutInSeconds:300}),o={accessToken:s.access_token,refreshToken:s.refresh_token,expiry:s.expires_in?new Date(i+s.expires_in*1e3):void 0};return yield n.persistTokens(o),o})()}}var $ye=["server","limit","since"];function sB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Yr(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?sB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):sB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var Bye=3e3,oB=10*60*1e3,Hye=new Ar("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent"),sv=function(t){return t.Chronological="chronological",t.Detached="detached",t}({}),Vye=new a_("m.get_login_token","org.matrix.msc3882.get_login_token"),mQ="uk.half-shot.msc2666",gQ="uk.half-shot.msc2666.mutual_rooms",vQ="uk.half-shot.msc2666.query_mutual_rooms",Vc="org.matrix.msc4140",yQ="uk.tcpip.msc4133",bQ="uk.tcpip.msc4133.stable",Cc="$",Le=function(t){return t.Sync="sync",t.Event="event",t.ToDeviceEvent="toDeviceEvent",t.ReceivedToDeviceMessage="receivedToDeviceMessage",t.AccountData="accountData",t.Room="Room",t.DeleteRoom="deleteRoom",t.SyncUnexpectedError="sync.unexpectedError",t.ClientWellKnown="WellKnown.client",t.ReceivedVoipEvent="received_voip_event",t.TurnServers="turnServers",t.TurnServersError="turnServers.error",t}({}),qye=new Ar("action","org.matrix.msc3824.action");class sT extends On{constructor(e){var n,r,i,s,o;super(),i=this,L(this,"logger",void 0),L(this,"reEmitter",new $v(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,"enableEncryptedStateEvents",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 qa(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 M1e(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()&&(dA()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off(Le.Sync,this.startCallEventHandler))}),L(this,"startMatrixRTC",()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off(Le.Sync,this.startMatrixRTC))}),L(this,"fixupRoomNotifications",()=>{if(this.isInitialSyncComplete()){var c,l=((c=this.getRooms())!==null&&c!==void 0?c:[]).filter(m=>m.getUnreadNotificationCount(Jt.Total)>0);for(var d of l){var h=this.getSafeUserId();d.fixupNotifications(h)}this.off(Le.Sync,this.fixupRoomNotifications)}}),this.logger=(n=e.logger)!==null&&n!==void 0?n:M,e.baseUrl=Ek(e.baseUrl),e.idBaseUrl=Ek(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 N0e,this.deviceId=e.deviceId||null,this.sessionId=To(10);var a=e.userId||null;this.credentials={userId:a},this.http=new PJ(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:Xr.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 c=B(function*(l){var d=i.getRoom(l.getRoomId());l.status!==rt.SENDING&&i.updatePendingEventStatus(d,l,rt.SENDING);var h=yield i.sendEventHttpRequest(l);return d&&d.updatePendingEvent(l,rt.SENT,h.event_id),h});return function(l){return c.apply(this,arguments)}}()),dA()&&(this.callEventHandler=new n1e(this),this.groupCallEventHandler=new r1e(this),this.canSupportVoip=!0,this.on(Le.Sync,this.startCallEventHandler)),this.matrixRTC=new cye(this.logger,this),this.serverCapabilitiesService=new OJ(this.logger,this.http),this.on(Le.Sync,this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.legacyCryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.enableEncryptedStateEvents=(s=e.enableEncryptedStateEvents)!==null&&s!==void 0?s:!1,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 H1e(this,this.logger),this.on(Kt.Decrypted,c=>{_Q(this,c)}),this.ignoredInvites=new V1e(this),this._secretStorage=new JJ(this,(o=e.cryptoCallbacks)!==null&&o!==void 0?o:{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(n=>yu.createUser(n,this))}get store(){return this._store}startClient(e){var n=this;return B(function*(){if(!n.clientRunning){n.clientRunning=!0,n.on(Le.Sync,n.startMatrixRTC);var r=n.getUserId();r&&n.store.storeUser(new yu(r)),n.canSupportVoip&&(n.checkTurnServersIntervalID=setInterval(()=>{n.checkTurnServers()},oB),n.checkTurnServers()),n.syncApi&&(n.logger.error("Still have sync object whilst not running: stopping old one"),n.syncApi.stop());try{yield n.getVersions();var{threads:i,list:s,fwdPagination:o}=yield n.doesServerSupportThread();Un.setServerSideSupport(i),Un.setServerSideListSupport(s),Un.setServerSideFwdPaginationSupport(o)}catch(a){n.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",a)}n.clientOpts=e??{},n.clientOpts.slidingSync?n.syncApi=new zJ(n.clientOpts.slidingSync,n,n.clientOpts,n.buildSyncApiOptions()):n.syncApi=new Vd(n,n.clientOpts,n.buildSyncApiOptions()),n.syncApi.sync().catch(a=>n.logger.info("Sync startup aborted with an error:",a)),n.clientOpts.clientWellKnownPollPeriod!==void 0&&(n.clientWellKnownIntervalID=setInterval(()=>{n.fetchClientWellKnown()},1e3*n.clientOpts.clientWellKnownPollPeriod),n.fetchClientWellKnown()),n.toDeviceMessageQueue.start(),n.serverCapabilitiesService.start()}})()}buildSyncApiOptions(){return{cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1,logger:this.logger.getChild("sync")}}stopClient(){var e,n,r,i,s;(e=this.cryptoBackend)===null||e===void 0||e.stop(),this.off(Le.Sync,this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(n=this.syncApi)===null||n===void 0||n.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,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.clientRunning)throw new Error("Cannot clear stores while client is running");var r=[];r.push(this.store.deleteAllData()),this.legacyCryptoStore&&r.push(this.legacyCryptoStore.deleteAllData());var i=function(){var s=B(function*(){var o;try{if(o=globalThis.indexedDB,!o)return}catch{return}var a=function*(m){var g=new Promise((y,v)=>{e.logger.info("Removing IndexedDB instance ".concat(m));var w=o.deleteDatabase(m);w.onsuccess=S=>{e.logger.info("Removed IndexedDB instance ".concat(m)),y(0)},w.onerror=S=>{e.logger.warn("Failed to remove IndexedDB instance ".concat(m,":"),S),y(0)},w.onblocked=S=>{e.logger.info("cannot yet remove IndexedDB instance ".concat(m))}});yield g};for(var c of["".concat((l=n.cryptoDatabasePrefix)!==null&&l!==void 0?l:Ok,"::matrix-sdk-crypto"),"".concat((d=n.cryptoDatabasePrefix)!==null&&d!==void 0?d:Ok,"::matrix-sdk-crypto-meta")]){var l,d;yield*a(c)}});return function(){return s.apply(this,arguments)}}();return r.push(i()),Promise.all(r).then()}getUserId(){var e,n;return(e=(n=this.credentials)===null||n===void 0?void 0:n.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,n;return(e=(n=this.credentials)===null||n===void 0||(n=n.userId)===null||n===void 0?void 0:n.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 fb(this,e)}createGroupCall(e,n,r,i,s,o){var a=this;return B(function*(){if(a.getGroupCallForRoom(e))throw new Error("".concat(e," already has an existing group call"));var c=a.getRoom(e);if(!c)throw new Error("Cannot find room ".concat(e));return new YO(a,c,n,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,n;return(e=(n=this.syncApi)===null||n===void 0?void 0:n.getSyncState())!==null&&e!==void 0?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){var e=this.getSyncState();return e?e===Gt.Prepared||e===Gt.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,n;return this.toDeviceMessageQueue.sendQueue(),(e=(n=this.syncApi)===null||n===void 0?void 0:n.retryImmediately())!==null&&e!==void 0?e:!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(){var e=this;return B(function*(){var n=e.serverCapabilitiesService.getCachedCapabilities();return n||e.serverCapabilitiesService.fetchCapabilities()})()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}initRustCrypto(){var e=arguments,n=this;return B(function*(){var r,i,s=e.length>0&&e[0]!==void 0?e[0]:{};if(n.cryptoBackend){n.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}var o=n.getUserId();if(o===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");var a=n.getDeviceId();if(a===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");n.logger.debug("Downloading Rust crypto library");var c=yield lb(()=>import("./index-DG_IYqWk.js"),__vite__mapDeps([0,1]),import.meta.url),l=yield c.initRustCrypto({logger:n.logger,http:n.http,userId:o,deviceId:a,secretStorage:n.secretStorage,cryptoCallbacks:n.cryptoCallbacks,storePrefix:s.useIndexedDB===!1?null:(r=s.cryptoDatabasePrefix)!==null&&r!==void 0?r:Ok,storeKey:s.storageKey,storePassphrase:s.storagePassword,legacyCryptoStore:n.legacyCryptoStore,legacyPickleKey:(i=n.legacyPickleKey)!==null&&i!==void 0?i:"DEFAULT_KEY",legacyMigrationProgressListener:(d,h)=>{n.emit(gi.LegacyCryptoStoreMigrationProgress,d,h)},enableEncryptedStateEvents:n.enableEncryptedStateEvents});l.setSupportedVerificationMethods(n.verificationMethods),n.cryptoBackend=l,n.on(Vs.Membership,l.onRoomMembership.bind(l)),n.on(Le.Event,d=>{l.onLiveEventFromSync(d)}),n.reEmitter.reEmit(l,[gi.VerificationRequestReceived,gi.UserTrustStatusChanged,gi.KeyBackupStatus,gi.KeyBackupSessionsRemaining,gi.KeyBackupFailed,gi.KeyBackupDecryptionKeyCached,gi.KeysChanged,gi.DevicesUpdated,gi.WillUpdateDevices,gi.DehydratedDeviceCreated,gi.DehydratedDeviceUploaded,gi.RehydrationStarted,gi.RehydrationProgress,gi.RehydrationCompleted,gi.RehydrationError,gi.DehydrationKeyCached,gi.DehydratedDeviceRotationError])})()}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isRoomEncrypted(e){var n=this.getRoom(e);return n?n.hasEncryptionStateEvent():!1}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}makeKeyBackupPath(e,n,r){var i;n!==void 0?i=xe("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:n}):e!==void 0?i=xe("/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,n,r){var i=this;return B(function*(){var s=i.makeKeyBackupPath(e,n,r);yield i.http.authedRequest(de.Delete,s.path,s.queryData,void 0,{prefix:Xr.V3})})()}getMediaConfig(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n=e?"/media/config":"/config";return this.http.authedRequest(de.Get,n,void 0,void 0,{prefix:e?Xr.V1:Cg.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,n=this.store.getRooms(),r=new Set(n);for(var i of r){var s=this.findPredecessorRooms(i,!0,e);for(var o of s)r.delete(o)}return Array.from(r)}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,n){var r=this;return B(function*(){if(!r.clientRunning)return r.logger.warn("Calling `setAccountData` before the client is started: `getAccountData` may return inconsistent results."),yield nA(5,()=>r.setAccountDataRaw(e,n));var i=r.store.getAccountData(e);if(i&&ff(i.event.content,n))return{};var s=Promise.withResolvers();function o(c){c.getType()===e&&s.resolve()}r.addListener(Le.AccountData,o);try{var a=yield nA(5,()=>r.setAccountDataRaw(e,n));return yield s.promise,a}finally{r.removeListener(Le.AccountData,o)}})()}setAccountDataRaw(e,n){var r=xe("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return this.http.authedRequest(de.Put,r,void 0,n)}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var n=this;return B(function*(){if(n.isInitialSyncComplete()){var r=n.store.getAccountData(e);return r?r.getContent():null}var i=xe("/user/$userId/account_data/$type",{$userId:n.credentials.userId,$type:e});try{return yield n.http.authedRequest(de.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 n=this;return B(function*(){var r=n.canSupport.get(ti.AccountDataDeletion);if(r===Zr.Unsupported){yield n.setAccountData(e,{});return}var i=xe("/user/$userId/account_data/$type",{$userId:n.getSafeUserId(),$type:e}),s=r===Zr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield n.http.authedRequest(de.Delete,i,void 0,void 0,s)})()}getIgnoredUsers(){var e=this.getAccountData(Z.IgnoredUserList);return e!=null&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){var n={ignored_users:{}};return e.forEach(r=>{n.ignored_users[r]={}}),this.setAccountData(Z.IgnoredUserList,n)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e){var n=arguments,r=this;return B(function*(){var i,s,o=n.length>1&&n[1]!==void 0?n[1]:{},a=r.getRoom(e),c=a?.getMember(r.getSafeUserId()),l=c?.membership,d=l==Be.Invite&&(i=c==null||(s=c.events.member)===null||s===void 0?void 0:s.getSender())!==null&&i!==void 0?i:null;if(r.logger.debug("joinRoom[".concat(e,"]: preJoinMembership=").concat(l,", inviter=").concat(d,", opts=").concat(JSON.stringify(o))),l==Be.Join)return a;var h=Promise.resolve();if(o.inviteSignUrl){var m=new URL(o.inviteSignUrl);m.searchParams.set("mxid",r.credentials.userId),h=r.http.requestOtherUrl(de.Post,m)}var g={};o.viaServers&&(g.server_name=o.viaServers,g.via=o.viaServers);var y={},v=yield h;v&&(y.third_party_signed=v);var w=xe("/join/$roomid",{$roomid:e}),S=yield r.http.authedRequest(de.Post,w,g,y),R=S.room_id;o.acceptSharedHistory&&d&&r.cryptoBackend&&(yield r.cryptoBackend.maybeAcceptKeyBundle(R,d));var x=r.getRoom(R);if(x!=null&&x.hasMembershipState(r.credentials.userId,Be.Join))return x;var T=new Vd(r,r.clientOpts,r.buildSyncApiOptions());return T.createRoom(R)})()}knockRoom(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=this.getRoom(e);if(r!=null&&r.hasMembershipState(this.credentials.userId,Be.Knock))return Promise.resolve({room_id:r.roomId});var i=xe("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),s={};n.viaServers&&(s.server_name=n.viaServers,s.via=n.viaServers);var o={};return n.reason&&(o.reason=n.reason),this.http.authedRequest(de.Post,i,s,o)}resendEvent(e,n){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(n,e,rt.SENDING),this.encryptAndSendEvent(n,e)}cancelPendingEvent(e){if(![rt.QUEUED,rt.NOT_SENT,rt.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===rt.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===rt.QUEUED&&this.scheduler.removeEventFromQueue(e);var n=this.getRoom(e.getRoomId());this.updatePendingEventStatus(n,e,rt.CANCELLED)}setRoomName(e,n){return this.sendStateEvent(e,Z.RoomName,{name:n})}setRoomTopic(e,n,r){var i=_J(n,r);return this.sendStateEvent(e,Z.RoomTopic,i)}getRoomTags(e){var n=xe("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(de.Get,n)}setRoomTag(e,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=xe("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:n});return this.http.authedRequest(de.Put,i,void 0,r)}deleteRoomTag(e,n){var r=xe("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:n});return this.http.authedRequest(de.Delete,r)}setRoomAccountData(e,n,r){var i=xe("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:n});return this.http.authedRequest(de.Put,i,void 0,r)}setPowerLevel(e,n,r){var i=this;return B(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(Z.RoomPowerLevels,""))===null||a===void 0?void 0:a.getContent()}if(!o)try{o=yield i.getStateEvent(e,Z.RoomPowerLevels,"")}catch(d){if(d instanceof tr&&d.errcode==="M_NOT_FOUND")o={};else throw d}o=d_(o),(s=o)!==null&&s!==void 0&&s.users||(o.users={});var c=Array.isArray(n)?n:[n];for(var l of c)r==null?delete o.users[l]:o.users[l]=r;return i.sendStateEvent(e,Z.RoomPowerLevels,o,"")})()}unstable_createLiveBeacon(e,n){var r=this;return B(function*(){return r.unstable_setLiveBeacon(e,n)})()}unstable_setLiveBeacon(e,n){var r=this;return B(function*(){return r.sendStateEvent(e,ZO.name,n,r.getUserId())})()}sendEvent(e,n,r,i,s){var o,a,c,l;return!(n!=null&&n.startsWith(Cc))&&n!==null?(l=i,c=r,a=n,o=null):(l=s,c=i,a=r,o=n),this.addThreadRelationIfNeeded(c,o,e),this.sendCompleteEvent(e,o,{type:a,content:c},l)}addThreadRelationIfNeeded(e,n,r){var i;if(n&&!((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"]=Yr(Yr({},e["m.relates_to"]),{},{rel_type:wn.name,event_id:n,is_falling_back:!a});var c=(o=this.getRoom(r))===null||o===void 0?void 0:o.getThread(n);if(c&&!a){var l,d;e["m.relates_to"]["m.in_reply_to"]={event_id:(l=(d=c.lastReply(h=>h.isRelation(wn.name)&&!h.status))===null||d===void 0?void 0:d.getId())!==null&&l!==void 0?l:n}}}}sendCompleteEvent(e,n,r,i,s){var o,a;typeof i=="string"?a=i:(o=i,a=s),a||(a=this.makeTxnId());var c=new $i(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()})),l=this.getRoom(e),d=n?l?.getThread(n):void 0;d&&c.setThread(d),o||(this.reEmitter.reEmit(c,[Kt.Replaced,Kt.VisibilityChange]),l?.reEmitter.reEmit(c,[Kt.BeforeRedaction]));var h=c.getAssociatedId();if(h!=null&&h.startsWith("~")){var m=l?.getPendingEvents().find(y=>y.getId()===h);m?.once(Kt.LocalEventIdReplaced,()=>{c.updateAssociatedId(m.getId())})}var g=c.getType();return this.logger.debug("sendEvent of type ".concat(g," in ").concat(e," with txnId ").concat(a).concat(o?" (delayed event)":"")),c.setTxnId(a),c.setStatus(rt.SENDING),o?this.encryptAndSendEvent(l,c,o):(l?.addPendingEvent(c,a),c.status===rt.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(l,c))}encryptAndSendEvent(e,n,r){var i=this;return B(function*(){if(r)return i.sendEventHttpRequest(n,r);try{var s;i.eventsBeingEncrypted.add(n.getId());try{yield i.encryptEventIfNeeded(n,e??void 0)}finally{s=!i.eventsBeingEncrypted.delete(n.getId())}if(s)return{};n.status===rt.ENCRYPTING&&i.updatePendingEventStatus(e,n,rt.SENDING);var o=null;return i.scheduler&&(o=i.scheduler.queueEvent(n),o&&i.scheduler.getQueueForEvent(n).length>1&&i.updatePendingEventStatus(e,n,rt.QUEUED)),o||(o=i.sendEventHttpRequest(n),e&&(o=o.then(a=>(e.updatePendingEvent(n,rt.SENT,a.event_id),a)))),yield o}catch(a){i.logger.error("Error sending event",a);try{n.error=a,i.updatePendingEventStatus(e,n,rt.NOT_SENT)}catch(c){i.logger.error("Exception in error handler!",c)}throw a instanceof tr&&(a.event=n),a}})()}encryptEventIfNeeded(e,n){var r=this;return B(function*(){if(n&&(yield r.shouldEncryptEventForRoom(e,n))&&!(!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(n,e,rt.ENCRYPTING),yield r.cryptoBackend.encryptEvent(e,n)}})()}shouldEncryptEventForRoom(e,n){var r=this;return B(function*(){var i;return e.isEncrypted()||e.getType()===Z.Reaction||e.isRedaction()?!1:!!(n.hasEncryptionStateEvent()||(yield(i=r.cryptoBackend)===null||i===void 0?void 0:i.isEncryptionEnabledInRoom(n.roomId)))})()}getEncryptedIfNeededEventType(e,n){var r;return n===Z.Reaction?n:(r=this.getRoom(e))!==null&&r!==void 0&&r.hasEncryptionStateEvent()?Z.RoomMessageEncrypted:n}updatePendingEventStatus(e,n,r){e?e.updatePendingEvent(n,r):n.setStatus(r)}sendEventHttpRequest(e,n){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=xe(o,i)}else if(e.isRedaction()&&e.event.redacts){var a="/rooms/$roomId/redact/$redactsEventId/$txnId";s=xe(a,Yr({$redactsEventId:e.event.redacts},i))}else s=xe("/rooms/$roomId/send/$eventType/$txnId",i);var c=e.getWireContent();return n?this.http.authedRequest(de.Put,s,aB(n),c):this.http.authedRequest(de.Put,s,void 0,c).then(l=>(this.logger.debug("Event sent to ".concat(e.getRoomId()," with event id ").concat(l.event_id)),l))}redactEvent(e,n,r,i,s){var o,a,c;(o=r)!==null&&o!==void 0&&o.startsWith(Cc)||(s=i,i=r,r=n,n=null);var l=(a=s)===null||a===void 0?void 0:a.reason,d={reason:l};if(((c=s)===null||c===void 0?void 0:c.with_rel_types)!==void 0){if(this.canSupport.get(ti.RelationBasedRedactions)===Zr.Unsupported)throw new Error("Server does not support relation based redactions "+"roomId ".concat(e," eventId ").concat(r," txnId: ").concat(i," threadId ").concat(n));var h=this.canSupport.get(ti.RelationBasedRedactions)===Zr.Stable?X5.stable:X5.unstable;d[h]=s.with_rel_types}return this.sendCompleteEvent(e,n,{type:Z.RoomRedaction,content:d,redacts:r},i)}sendMessage(e,n,r,i){typeof n!="string"&&n!==null&&(i=r,r=n,n=null);var s=Z.RoomMessage,o=r;return this.sendEvent(e,n,s,o,i)}sendTextMessage(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=mJ(r);return this.sendMessage(e,n,o,i)}sendNotice(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=gJ(r);return this.sendMessage(e,n,o,i)}sendEmoteMessage(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=vJ(r);return this.sendMessage(e,n,o,i)}sendImageMessage(e,n,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Image";!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(o=i||"Image",i=r,r=n,n=null);var a={msgtype:ll.Image,url:r,info:i,body:o};return this.sendMessage(e,n,a)}sendStickerMessage(e,n,r,i){var s,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Sticker";!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(o=i||"Sticker",i=r,r=n,n=null);var a={url:r,info:i,body:o};return this.sendEvent(e,n,Z.Sticker,a)}sendHtmlMessage(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=fJ(r,i);return this.sendMessage(e,n,o)}sendHtmlNotice(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=hJ(r,i);return this.sendMessage(e,n,o)}sendHtmlEmote(e,n,r,i){var s;!((s=n)!==null&&s!==void 0&&s.startsWith(Cc))&&n!==null&&(i=r,r=n,n=null);var o=pJ(r,i);return this.sendMessage(e,n,o)}_unstable_sendDelayedEvent(e,n,r,i,s,o){var a=this;return B(function*(){if(!(yield a.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","sendDelayedEvent");return a.addThreadRelationIfNeeded(s,r,e),a.sendCompleteEvent(e,r,{type:i,content:s},n,o)})()}_unstable_sendDelayedStateEvent(e,n,r,i){var s=arguments,o=this;return B(function*(){var a=s.length>4&&s[4]!==void 0?s[4]:"",c=s.length>5&&s[5]!==void 0?s[5]:{};if(!(yield o.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","sendDelayedStateEvent");var l={$roomId:e,$eventType:r,$stateKey:a},d=xe("/rooms/$roomId/state/$eventType",l);return a!==void 0&&(d=xe(d+"/$stateKey",l)),o.http.authedRequest(de.Put,d,aB(n),i,c)})()}_unstable_getDelayedEvents(e){var n=this;return B(function*(){if(!(yield n.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","getDelayedEvents");var r=e?{from:e}:void 0;return yield n.http.authedRequest(de.Get,"/delayed_events",r,void 0,{prefix:"".concat(Xr.Unstable,"/").concat(Vc)})})()}_unstable_updateDelayedEvent(e,n){var r=arguments,i=this;return B(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:{};if(!(yield i.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","updateDelayedEvent");var o=xe("/delayed_events/$delayId",{$delayId:e}),a={action:n};return yield i.http.authedRequest(de.Post,o,void 0,a,Yr(Yr({},s),{},{prefix:"".concat(Xr.Unstable,"/").concat(Vc)}))})()}sendReceipt(e,n,r){var i=arguments,s=this;return B(function*(){var o=i.length>3&&i[3]!==void 0?i[3]:!1;if(s.isGuest())return Promise.resolve({});var a=xe("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:n,$eventId:e.getId()}),c=!o&&s.supportsThreads(),l=c?Yr(Yr({},r),{},{thread_id:ov(e)}):r,d=s.http.authedRequest(de.Post,a,void 0,l||{}),h=s.getRoom(e.getRoomId());return h&&s.credentials.userId&&h.addLocalEchoReceipt(s.credentials.userId,e,n,o),d})()}sendReadReceipt(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:ls.Read,s=n.length>2&&n[2]!==void 0?n[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,n,r,i){var s=this;return B(function*(){var o=s.getRoom(e);if(o!=null&&o.hasPendingEvent(n))throw new Error("Cannot set read marker to a pending event (".concat(n,")"));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?.addLocalEchoReceipt(s.credentials.userId,r,ls.Read)}var c;if(i){if(c=i.getId(),o!=null&&o.hasPendingEvent(c))throw new Error("Cannot set read receipt to a pending event (".concat(c,")"));o?.addLocalEchoReceipt(s.credentials.userId,i,ls.ReadPrivate)}return yield s.setRoomReadMarkersHttpRequest(e,n,a,c)})()}sendRtcDecline(e,n){return this.sendEvent(e,Z.RTCDecline,{"m.relates_to":{event_id:n,rel_type:vn.Reference}})}getUrlPreview(e,n){n=Math.floor(n/6e4)*6e4;var r=new URL(e);r.hash="",e=r.toString();var i=n+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];var s=this.http.authedRequest(de.Get,"/preview_url",{url:e,ts:n.toString()},void 0,{prefix:Cg.V3,priority:"low"});return this.urlPreviewCache[i]=s,s}sendTyping(e,n,r){if(this.isGuest())return Promise.resolve({});var i=xe("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),s={typing:n};return n&&(s.timeout=r||2e4),this.http.authedRequest(de.Put,i,void 0,s)}getRoomUpgradeHistory(e){var n=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,n,r),o=this.findSuccessorRooms(i,n,r);return[...s,i,...o]}findPredecessorRooms(e,n,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 c;if(a){if(o.has(a))break;o.add(a)}var l=this.getRoom(a);if(l===null)break;if(n){var d=l.currentState.getStateEvents(Z.RoomTombstone,"");if(!d||d.getContent().replacement_room!==e.roomId)break}s.splice(0,0,l),e=l,a=(c=e.findPredecessor(r))===null||c===void 0?void 0:c.roomId}return s}findSuccessorRooms(e,n,r){for(var i=[],s=e.currentState.getStateEvents(Z.RoomTombstone,"");s;){var o=this.getRoom(s.getContent().replacement_room);if(!o||o.roomId===e.roomId)break;if(n){var a,c=(a=o.findPredecessor(r))===null||a===void 0?void 0:a.roomId;if(!c||c!==e.roomId)break}i.push(o);var l=new Set(i.map(d=>d.roomId));if(l.size<i.length)return i.slice(0,i.length-1);e=o,s=e.currentState.getStateEvents(Z.RoomTombstone,"")}return i}invite(e,n){var r=arguments,i=this;return B(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:{};if(typeof s!="object"&&(s={reason:s}),s.shareEncryptedHistory){var o;yield(o=i.cryptoBackend)===null||o===void 0?void 0:o.shareRoomHistoryWithUser(e,n)}return yield i.membershipChange(e,n,Be.Invite,s.reason)})()}inviteByEmail(e,n){return this.inviteByThreePid(e,"email",n)}inviteByThreePid(e,n,r){var i=this;return B(function*(){var s,o=xe("/rooms/$roomId/invite",{$roomId:e}),a=i.getIdentityServerUrl(!0);if(!a)return Promise.reject(new tr({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));var c={id_server:a,medium:n,address:r};if((s=i.identityServer)!==null&&s!==void 0&&s.getAccessToken){var l=yield i.identityServer.getAccessToken();l&&(c.id_access_token=l)}return i.http.authedRequest(de.Post,o,void 0,c)})()}leave(e){return this.membershipChange(e,void 0,Be.Leave)}leaveRoomChain(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,r=this.getRoomUpgradeHistory(e,!0),i=r;if(!n){i=[];for(var s of r)if(i.push(s),s.roomId===e)break}var o={},a=[],c=d=>this.leave(d).then(()=>{delete o[d]}).catch(h=>{o[d]=h});for(var l of i)a.push(c(l.roomId));return Promise.all(a).then(()=>o)}ban(e,n,r){return this.membershipChange(e,n,Be.Ban,r)}forget(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:!0,s=xe("/rooms/$room_id/forget",{$room_id:e}),o=yield r.http.authedRequest(de.Post,s);return i&&(r.store.removeRoom(e),r.emit(Le.DeleteRoom,e)),o})()}unban(e,n){var r=xe("/rooms/$roomId/unban",{$roomId:e}),i={user_id:n};return this.http.authedRequest(de.Post,r,void 0,i)}kick(e,n,r){var i=xe("/rooms/$roomId/kick",{$roomId:e}),s={user_id:n,reason:r};return this.http.authedRequest(de.Post,i,void 0,s)}membershipChange(e,n,r,i){var s=xe("/rooms/$room_id/$membership",{$room_id:e,$membership:r});return this.http.authedRequest(de.Post,s,void 0,{user_id:n,reason:i})}getPushActionsForEvent(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushActions()||n){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushActions()}getPushDetailsForEvent(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushDetails()||n){var{actions:r,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(r,i)}return e.getPushDetails()}setProfileInfo(e,n){var r=xe("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(de.Put,r,void 0,n)}setDisplayName(e){var n=this;return B(function*(){var r=yield n.setProfileInfo("displayname",{displayname:e}),i=n.getUser(n.getUserId());return i&&(i.displayName=e,i.emit(Ui.DisplayName,i.events.presence,i)),r})()}setAvatarUrl(e){var n=this;return B(function*(){var r=yield n.setProfileInfo("avatar_url",{avatar_url:e}),i=n.getUser(n.getUserId());return i&&(i.avatarUrl=e,i.emit(Ui.AvatarUrl,i.events.presence,i)),r})()}mxcUrlToHttp(e,n,r,i,s,o,a){return W3(this.baseUrl,e,n,r,i,s,o,a)}setSyncPresence(e){var n=this;return B(function*(){var r;(r=n.syncApi)===null||r===void 0||r.setPresence(e)})()}setPresence(e){var n=this;return B(function*(){var r=xe("/presence/$userId/status",{$userId:n.credentials.userId}),i=["offline","online","unavailable"];if(i.indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);yield n.http.authedRequest(de.Put,r,void 0,e)})()}getPresence(e){var n=xe("/presence/$userId/status",{$userId:e});return this.http.authedRequest(de.Get,n)}scrollback(e){var n=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(Bye-s,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);var o=this.store.scrollback(e,n).length;if(o===n)return Promise.resolve(e);n=n-o;var a=new Promise((c,l)=>{_p(r).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,n,ht.Backward)).then(d=>{var h,m,g=d.chunk.map(this.getEventMapper());if(d.state){var y=d.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(y)}var[v,w,S]=e.partitionThreadedEvents(g);this.processAggregatedTimelineEvents(e,v),e.addEventsToTimeline(v,!0,!0,e.getLiveTimeline()),this.processThreadEvents(e,w,!0),S.forEach(R=>e.relations.aggregateChildEvent(R)),e.oldState.paginationToken=(h=d.end)!==null&&h!==void 0?h:null,d.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,g,(m=d.end)!==null&&m!==void 0?m:null,!0),delete this.ongoingScrollbacks[e.roomId],c(e)}).catch(d=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},l(d)})});return i={promise:a},this.ongoingScrollbacks[e.roomId]=i,a}getEventMapper(e){return L1e(this,e||{})}getEventTimeline(e,n){var r=this;return B(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(n))return e.getTimelineForEvent(n);if(e.thread&&r.supportsThreads())return r.getThreadTimeline(e,n);var c=xe("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:n}),l=void 0;(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(l={filter:JSON.stringify(Us.LAZY_LOADING_MESSAGES_FILTER)});var d=yield r.http.authedRequest(de.Get,c,l);if(!d.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(n))return e.getTimelineForEvent(n);var h=r.getEventMapper(),m=h(d.event);if(m.isRelation(wn.name)){r.logger.warn("Tried loading a regular timeline at the position of a thread event");return}var g=[...d.events_after.reverse().map(h),m,...d.events_before.map(h)],y=e.getTimelineForEvent(g[0].getId());y?y.getState(Me.BACKWARDS).setUnknownStateEvents(d.state.map(h)):(y=e.addTimeline(),y.initialiseState(d.state.map(h)),y.getState(Me.FORWARDS).paginationToken=d.end);var[v,w,S]=e.room.partitionThreadedEvents(g);return e.addEventsToTimeline(v,!0,!1,y,d.start),r.processThreadEvents(e.room,w,!0),r.processAggregatedTimelineEvents(e.room,v),S.forEach(R=>e.relations.aggregateChildEvent(R)),(s=(o=e.getTimelineForEvent(n))!==null&&o!==void 0?o:(a=e.room.findThreadForEvent(m))===null||a===void 0?void 0:a.liveTimeline)!==null&&s!==void 0?s:y})()}getThreadTimeline(e,n){var r=this;return B(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=xe("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:n}),o={limit:"0"};(i=r.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(o.filter=JSON.stringify(Us.LAZY_LOADING_MESSAGES_FILTER));var a=yield r.http.authedRequest(de.Get,s,o),c=r.getEventMapper(),l=c(a.event);if(e.canContain(l)){var d=r.canSupport.get(ti.RelationsRecursion)!==Zr.Unsupported;if(Un.hasServerSideSupport)if(Un.hasServerSideFwdPaginationSupport){var h,m,g;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var y=e.thread,v=yield r.fetchRelations(e.room.roomId,y.id,null,null,{dir:ht.Backward,from:a.start,recurse:d||void 0}),w=yield r.fetchRelations(e.room.roomId,y.id,null,null,{dir:ht.Forward,from:a.end,recurse:d||void 0}),S=[...w.chunk.reverse().filter(Nk(y.id)).map(c),l,...v.chunk.filter(Nk(y.id)).map(c)];for(var R of S){var x;yield(x=e.thread)===null||x===void 0?void 0:x.processEvent(R)}var T=e.getTimelineForEvent(l.getId());if(T?T.getState(Me.BACKWARDS).setUnknownStateEvents(a.state.map(c)):(T=e.addTimeline(),T.initialiseState(a.state.map(c))),e.addEventsToTimeline(S,!0,!1,T,w.next_batch),!v.next_batch){var I=yield r.fetchRoomEvent(e.room.roomId,y.id);e.addEventsToTimeline([c(I)],!0,!1,T,null)}return T.setPaginationToken((h=v.next_batch)!==null&&h!==void 0?h:null,ht.Backward),T.setPaginationToken((m=w.next_batch)!==null&&m!==void 0?m:null,ht.Forward),r.processAggregatedTimelineEvents(e.room,S),(g=e.getTimelineForEvent(n))!==null&&g!==void 0?g:T}else{for(var k,A=e.thread,O=yield r.fetchRelations(e.room.roomId,A.id,wn.name,null,{dir:ht.Backward,from:a.start,recurse:d||void 0}),D=[],N=a.end;N;){var U,$=yield r.fetchRelations(e.room.roomId,A.id,wn.name,null,{dir:ht.Forward,from:N,recurse:d||void 0});N=(U=$.next_batch)!==null&&U!==void 0?U:null,D.push(...$.chunk)}var K=[...D.reverse().map(c),l,...O.chunk.map(c)];for(var Y of K){var G;yield(G=e.thread)===null||G===void 0?void 0:G.processEvent(Y)}var F=e.getLiveTimeline();if(F.getState(Me.BACKWARDS).setUnknownStateEvents(a.state.map(c)),e.addEventsToTimeline(K,!0,!1,F,null),!O.next_batch){var q=yield r.fetchRoomEvent(e.room.roomId,A.id);e.addEventsToTimeline([c(q)],!0,!1,F,null)}return F.setPaginationToken((k=O.next_batch)!==null&&k!==void 0?k:null,ht.Backward),F.setPaginationToken(null,ht.Forward),r.processAggregatedTimelineEvents(e.room,K),F}}})()}getLatestTimeline(e){var n=this;return B(function*(){if(!n.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 n.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&&Un.hasServerSideSupport){var o,a=n.canSupport.get(ti.RelationsRecursion)!==Zr.Unsupported,c=yield n.fetchRelations(e.room.roomId,e.thread.id,wn.name,null,{dir:ht.Backward,limit:1,recurse:a||void 0});r=(o=c.chunk)===null||o===void 0?void 0:o[0]}else{var l,d,h=xe("/rooms/$roomId/messages",{$roomId:e.room.roomId}),m={dir:"b"};(l=n.clientOpts)!==null&&l!==void 0&&l.lazyLoadMembers&&(m.filter=JSON.stringify(Us.LAZY_LOADING_MESSAGES_FILTER));var g=yield n.http.authedRequest(de.Get,h,m);r=(d=g.chunk)===null||d===void 0?void 0:d[0]}if(!r)throw new Error("No message returned when trying to construct getLatestTimeline");return n.getEventTimeline(e,r.event_id)})()}createMessagesRequest(e,n){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=xe("/rooms/$roomId/messages",{$roomId:e}),c={limit:i.toString(),dir:s};n&&(c.from=n);var l=null;if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(l=Object.assign({},Us.LAZY_LOADING_MESSAGES_FILTER)),o){var d;l=l||{},Object.assign(l,(d=o.getRoomTimelineFilterComponent())===null||d===void 0?void 0:d.toJSON())}return l&&(c.filter=JSON.stringify(l)),this.http.authedRequest(de.Get,a,c)}createThreadListMessagesRequest(e,n){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]:Ba.All,a=arguments.length>5?arguments[5]:void 0,c=xe("/rooms/$roomId/threads",{$roomId:e}),l={limit:i.toString(),dir:s,include:SQ(o)};n&&(l.from=n);var d={};if((r=this.clientOpts)!==null&&r!==void 0&&r.lazyLoadMembers&&(d=Yr({},Us.LAZY_LOADING_MESSAGES_FILTER)),a){var h;d=Yr(Yr({},d),(h=a.getRoomTimelineFilterComponent())===null||h===void 0?void 0:h.toJSON())}Object.keys(d).length&&(l.filter=JSON.stringify(d));var m={prefix:Un.hasServerSideListSupport===Zi.Stable?Xr.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(de.Get,c,l,void 0,m).then(g=>{var y;return Yr(Yr({},g),{},{chunk:(y=g.chunk)===null||y===void 0?void 0:y.reverse(),start:g.prev_batch,end:g.next_batch})})}paginateEventTimeline(e,n){var r=this,i=e.getTimelineSet()===this.notifTimelineSet,s=this.getRoom(e.getRoomId()),o=e.getTimelineSet().threadListType,a=e.getTimelineSet().thread;n=n||{};var c=n.backwards||!1;if(i&&!c)throw new Error("paginateNotifTimeline can only paginate backwards");var l=c?Me.BACKWARDS:Me.FORWARDS,d=e.getPaginationToken(l),h=e.paginationRequests[l];if(h)return h;var m,g,y;if(i){var v;m="/notifications",g={limit:((v=n.limit)!==null&&v!==void 0?v:30).toString(),only:"highlight"},d&&d!=="end"&&(g.from=d),y=this.http.authedRequest(de.Get,m,g).then(function(){var T=B(function*(I){var k=I.next_token,A=[];I.notifications=I.notifications.filter(Ka);for(var O=0;O<I.notifications.length;O++){var D=I.notifications[O],N=r.getEventMapper()(D.event);r.getPushDetailsForEvent(N,!0),N.event.room_id=D.room_id,A[O]=N}var U=e.getTimelineSet();return U.addEventsToTimeline(A,c,!1,e,k),r.processAggregatedTimelineEvents(U.room,A),c&&!I.next_token&&e.setPaginationToken(null,l),!!I.next_token});return function(I){return T.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}else if(o!==null){if(!s)throw new Error("Unknown room "+e.getRoomId());if(!Un.hasServerSideFwdPaginationSupport&&l===ht.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");y=this.createThreadListMessagesRequest(e.getRoomId(),d,n.limit,l,o,e.getFilter()).then(T=>{if(T.state){var I=e.getState(l),k=T.state.filter(Ka).map(this.getEventMapper());I.setUnknownStateEvents(k)}var A=T.end,O=T.chunk.filter(Ka).map(this.getEventMapper()),D=e.getTimelineSet();return D.addEventsToTimeline(O,c,!1,e,A),this.processAggregatedTimelineEvents(s,O),this.processThreadRoots(s,O,c),c&&T.end==T.start&&e.setPaginationToken(null,l),T.end!==T.start}).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}else if(a){var w,S,R=this.getRoom((w=e.getRoomId())!==null&&w!==void 0?w:void 0);if(!R)throw new Error("Unknown room "+e.getRoomId());var x=this.canSupport.get(ti.RelationsRecursion)!==Zr.Unsupported;y=this.fetchRelations((S=e.getRoomId())!==null&&S!==void 0?S:"",a.id,null,null,{dir:l,limit:n.limit,from:d??void 0,recurse:x||void 0}).then(function(){var T=B(function*(I){var k=r.getEventMapper(),A=I.chunk.filter(Ka).filter(Nk(a.id)).map(k);for(var O of A.slice().reverse()){yield a?.processEvent(O);var D=O.getSender();(!c||a?.getEventReadUpTo(D)===null)&&R.addLocalEchoReceipt(D,O,ls.Read)}var N=I.next_batch,U=e.getTimelineSet();if(U.addEventsToTimeline(A,c,!1,e,N??null),!N&&c){var $,K,Y=($=a.rootEvent)!==null&&$!==void 0?$:k(yield r.fetchRoomEvent((K=e.getRoomId())!==null&&K!==void 0?K:"",a.id));U.addEventsToTimeline([Y],!0,!1,e,null)}return r.processAggregatedTimelineEvents(U.room,A),c&&!N&&e.setPaginationToken(null,l),!!N});return function(I){return T.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}else{if(!s)throw new Error("Unknown room "+e.getRoomId());y=this.createMessagesRequest(e.getRoomId(),d,n.limit,l,e.getFilter()).then(T=>{if(T.state){var I=e.getState(l),k=T.state.filter(Ka).map(this.getEventMapper());I.setUnknownStateEvents(k)}var A=T.end,O=T.chunk.filter(Ka).map(this.getEventMapper()),D=e.getTimelineSet(),[N,,U]=s.partitionThreadedEvents(O);D.addEventsToTimeline(N,c,!1,e,A),this.processAggregatedTimelineEvents(s,N),this.processThreadRoots(s,N.filter(K=>K.getServerAggregatedRelation(wn.name)),!1),U.forEach(K=>s.relations.aggregateChildEvent(K));var $=T.end===void 0||T.end===T.start;return c&&$&&e.setPaginationToken(null,l),!$}).finally(()=>{e.paginationRequests[l]=null}),e.paginationRequests[l]=y}return y}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var n,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;return(n=this.peekSync)===null||n===void 0||n.stopPeeking(),this.peekSync=new Vd(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,r)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,n){var r=this.sendStateEvent(e,Z.RoomGuestAccess,{guest_access:n.allowJoin?dC.CanJoin:dC.Forbidden},""),i=Promise.resolve();return n.allowRead&&(i=this.sendStateEvent(e,Z.RoomHistoryVisibility,{history_visibility:QO.WorldReadable},"")),Promise.all([i,r]).then()}requestRegisterEmailToken(e,n,r,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:n,send_attempt:r,next_link:i})}requestRegisterMsisdnToken(e,n,r,i,s){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:n,client_secret:r,send_attempt:i,next_link:s})}requestAdd3pidEmailToken(e,n,r,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:n,send_attempt:r,next_link:i})}requestAdd3pidMsisdnToken(e,n,r,i,s){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:n,client_secret:r,send_attempt:i,next_link:s})}requestPasswordEmailToken(e,n,r,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:n,send_attempt:r,next_link:i})}requestPasswordMsisdnToken(e,n,r,i,s){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:n,client_secret:r,send_attempt:i,next_link:s})}requestTokenFromEndpoint(e,n){var r=this;return B(function*(){var i=Object.assign({},n);return r.http.request(de.Post,e,void 0,i)})()}getRoomPushRule(e,n){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===n)}else throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,n,r){var i,s=!1,o=this.getRoomPushRule(e,n);if(o!=null&&o.actions.includes(Zd.DontNotify)&&(s=!0),!r)s&&(i=this.deletePushRule(e,wi.RoomSpecific,o.rule_id));else if(!o)i=this.addPushRule(e,wi.RoomSpecific,n,{actions:[Zd.DontNotify]});else if(!s){var a=Promise.withResolvers();this.deletePushRule(e,wi.RoomSpecific,o.rule_id).then(()=>{this.addPushRule(e,wi.RoomSpecific,n,{actions:[Zd.DontNotify]}).then(()=>{a.resolve()}).catch(c=>{a.reject(c)})}).catch(c=>{a.reject(c)}),i=a.promise}if(i)return new Promise((c,l)=>{i.then(()=>{this.getPushRules().then(d=>{this.pushRules=d,c()}).catch(d=>{l(d)})}).catch(d=>{this.getPushRules().then(h=>{this.pushRules=h,l(d)}).catch(h=>{l(d)})})})}searchMessageText(e){var n={search_term:e.query};return"keys"in e&&(n.keys=e.keys),this.search({body:{search_categories:{room_events:n}}})}searchRoomEvents(e){var n={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:KJ.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},r={_query:n,results:[],highlights:[]};return this.search({body:n}).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 n={body:e._query,next_batch:e.next_batch},r=this.search(n,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=r,r}processRoomEventsSearch(e,n){var r,i,s=n.search_categories.room_events;e.count=s.count,e.next_batch=s.next_batch;var o=new Set(s.highlights);e.highlights.forEach(g=>{o.add(g)}),e.highlights=Array.from(o);for(var a=this.getEventMapper(),c=(r=(i=s.results)===null||i===void 0?void 0:i.length)!==null&&r!==void 0?r:0,l=0;l<c;l++){var d=tT.fromJson(s.results[l],a),h=this.getRoom(d.context.getEvent().getRoomId());if(h)for(var m of d.context.getTimeline())m.setMetadata(h.currentState,!1);e.results.push(d)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;var e=new Vd(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 n=xe("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,n,void 0,e).then(r=>{var i=Us.fromJson(this.credentials.userId,r.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,n,r){if(r){var i=this.store.getFilter(e,n);if(i)return Promise.resolve(i)}var s=xe("/user/$userId/filter/$filterId",{$userId:e,$filterId:n});return this.http.authedRequest(de.Get,s).then(o=>{var a=Us.fromJson(e,n,o);return this.store.storeFilter(a),a})}getOrCreateFilter(e,n){var r=this;return B(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(),c=n.getDefinition();ff(a,c)&&(s=i)}}catch(d){if(d.errcode!=="M_UNKNOWN"&&d.errcode!=="M_NOT_FOUND")throw d}s||r.store.setFilterIdByName(e,void 0)}if(s)return s;var l=yield r.createFilter(n.getDefinition());return r.store.setFilterIdByName(e,l.filterId),l.filterId})()}getOpenIdToken(){var e=xe("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(de.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(de.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}checkTurnServers(){var e=this;return B(function*(){if(e.canSupportVoip){var n=!1,r=e.turnServersExpiry-Date.now();if(r>oB)e.logger.debug("TURN creds are valid for another "+r+" ms: not fetching new ones."),n=!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,n=!0,e.emit(Le.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(Le.TurnServersError,o,!0)):e.emit(Le.TurnServersError,o,!1)}}return n}})()}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){var e=xe("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(de.Get,e,void 0,void 0,{prefix:""}).then(n=>n.admin)}whoisSynapseUser(e){var n=xe("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(de.Get,n,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){var n=xe("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(de.Post,n,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e=this;return B(function*(){var n;e.clientWellKnownPromise=lt.getRawClientConfig((n=e.getDomain())!==null&&n!==void 0?n:void 0),e.clientWellKnown=yield e.clientWellKnownPromise,e.emit(Le.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"],n=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(n)}_unstable_getSharedRooms(e){var n=this;return B(function*(){var r=yield n.doesServerSupportUnstableFeature(mQ),i=yield n.doesServerSupportUnstableFeature(gQ),s=yield n.doesServerSupportUnstableFeature(vQ);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=xe("/uk.half-shot.msc2666/user/".concat(i?"mutual_rooms":"shared_rooms","/$userId"),{$userId:e}),a={});var c=[],l=null;do{var d={};l!=null&&s&&(d.batch_token=l);var h=yield n.http.authedRequest(de.Get,o,Yr(Yr({},a),d),void 0,{prefix:Xr.Unstable});c.push(...h.joined),h.next_batch_token!==void 0?l=h.next_batch_token:l=null}while(l!=null);return c})()}getVersions(){var e=this;return B(function*(){if(e.serverVersionsPromise)return e.serverVersionsPromise;e.serverVersionsPromise=e.http.authedRequest(de.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(r=>{throw e.serverVersionsPromise=void 0,r});var n=yield e.serverVersionsPromise;return e.canSupport=yield O0e(n),e.serverVersionsPromise})()}isVersionSupported(e){var n=this;return B(function*(){var{versions:r}=yield n.getVersions();return r&&r.includes(e)})()}doesServerSupportUnstableFeature(e){var n=this;return B(function*(){var r=yield n.getVersions();if(!r)return!1;var i=r.unstable_features;return i&&!!i[e]})()}doesServerForceEncryptionForPreset(e){var n=this;return B(function*(){var r=yield n.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 B(function*(){if(yield e.isVersionSupported("v1.4"))return{threads:Zi.Stable,list:Zi.Stable,fwdPagination:Zi.Stable};try{var[n,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:JE(r,n),list:JE(s,i),fwdPagination:JE(a,o)}}catch{return{threads:Zi.None,list:Zi.None,fwdPagination:Zi.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,n,r,i){var s=arguments,o=this;return B(function*(){var a,c,l=s.length>4&&s[4]!==void 0?s[4]:{dir:ht.Backward},d=i?o.getEncryptedIfNeededEventType(e,i):null,[h,m]=yield Promise.all([o.fetchRoomEvent(e,n),o.fetchRelations(e,n,r,d,l)]),g=o.getEventMapper(),y=h?g(h):void 0,v=m.chunk.map(g);if(d===Z.RoomMessageEncrypted){var w=y?v.concat(y):v;yield Promise.all(w.map(S=>o.decryptEventIfNeeded(S))),i!==null&&(v=v.filter(S=>S.getType()===i))}return y&&r===vn.Replace&&(v=v.filter(S=>S.getSender()===y.getSender())),{originalEvent:y??null,events:v,nextBatch:(a=m.next_batch)!==null&&a!==void 0?a:null,prevBatch:(c=m.prev_batch)!==null&&c!==void 0?c:null}})()}generateClientSecret(){return To(32)}decryptEventIfNeeded(e,n){return e.isState()&&!this.enableEncryptedStateEvents?Promise.resolve():(e.shouldAttemptDecryption()&&this.getCrypto()&&e.attemptDecryption(this.cryptoBackend,n),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve())}termsUrlForService(e,n){switch(e){case fA.IS:return this.http.getUrl("/terms",void 0,$l.V2,n);case fA.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",n);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(){var e,n,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return r&&((e=this.idBaseUrl)!==null&&e!==void 0&&e.startsWith("http://")||(n=this.idBaseUrl)!==null&&n!==void 0&&n.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=Ek(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(de.Get,"/register/available",{username:e}).then(n=>n.available).catch(n=>n.errcode==="M_USER_IN_USE"?!1:Promise.reject(n))}register(e,n,r,i,s,o,a){r&&(i.session=r);var c={auth:i,refresh_token:!0};return e!=null&&(c.username=e),n!=null&&(c.password=n),o!=null&&(c.guest_access_token=o),a!=null&&(c.inhibit_login=a),this.registerRequest(c)}registerGuest(){var{body:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.registerRequest(e||{},"guest")}registerRequest(e,n){var r={};return n&&(r.kind=n),this.http.request(de.Post,"/register",r,e)}refreshToken(e){var n=r=>this.http.authedRequest(de.Post,"/refresh",void 0,{refresh_token:e},{prefix:r,inhibitLogoutEmit:!0});return n(Xr.V3).catch(r=>{if(r.errcode==="M_UNRECOGNIZED")return n(Xr.V1);throw r})}loginFlows(){return this.http.request(de.Get,"/login")}login(e,n){return this.loginRequest(Yr(Yr({},n),{},{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,n){return this.login("m.login.password",{user:e,password:n})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e){var n=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/"+n+"/redirect";r&&(s+="/"+r);var o={redirectUrl:e,[qye.unstable]:i};return this.http.getUrl(s,o).href}loginWithToken(e){return this.login("m.login.token",{token:e})}loginRequest(e){var n=this;return B(function*(){return yield n.http.authedRequest(de.Post,"/login",void 0,e)})()}logout(){var e=arguments,n=this;return B(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:!1;return r&&(n.stopClient(),n.http.abort()),n.http.authedRequest(de.Post,"/logout")})()}deactivateAccount(e,n){var r={};return e&&(r.auth=e),n!==void 0&&(r.erase=n),this.http.authedRequest(de.Post,"/account/deactivate",void 0,r)}requestLoginToken(e){var n=this;return B(function*(){var r={auth:e};return n.http.authedRequest(de.Post,"/login/get_token",void 0,r,{prefix:Xr.V1})})()}getFallbackAuthUrl(e,n){var r=xe("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(r,{session:n}).href}createRoom(e){var n=this;return B(function*(){var r,i=(e.invite_3pid||[]).filter(a=>!a.id_access_token);if(i.length>0&&(r=n.identityServer)!==null&&r!==void 0&&r.getAccessToken){var s=yield n.identityServer.getAccessToken();if(s)for(var o of i)o.id_access_token=s}return n.http.authedRequest(de.Post,"/createRoom",void 0,e)})()}fetchRelations(e,n,r,i){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{dir:ht.Backward},o=s;Un.hasServerSideFwdPaginationSupport===Zi.Experimental&&(o=xF("dir","org.matrix.msc3715.dir",o)),this.canSupport.get(ti.RelationsRecursion)===Zr.Unstable&&(o=xF("recurse","org.matrix.msc3981.recurse",o));var a=B5(o),c="/rooms/$roomId/relations/$eventId";r!==null?(c+="/$relationType",i!==null&&(c+="/$eventType")):i!==null&&(this.logger.warn("eventType: ".concat(i,` ignored when fetching
26
26
  relations as relationType is null`)),i=null);var l=xe(c+"?"+a,{$roomId:e,$eventId:n,$relationType:r,$eventType:i});return this.http.authedRequest(de.Get,l,void 0,void 0,{prefix:Xr.V1})}roomState(e){var n=xe("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(de.Get,n)}fetchRoomEvent(e,n){var r=xe("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:n});return this.http.authedRequest(de.Get,r)}members(e,n,r,i){var s={};n&&(s.membership=n),r&&(s.not_membership=r),i&&(s.at=i);var o=B5(s),a=xe("/rooms/$roomId/members?"+o,{$roomId:e});return this.http.authedRequest(de.Get,a)}upgradeRoom(e,n){var r=xe("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(de.Post,r,void 0,{new_version:n})}getStateEvent(e,n,r){var i={$roomId:e,$eventType:n,$stateKey:r},s=xe("/rooms/$roomId/state/$eventType",i);return r!==void 0&&(s=xe(s+"/$stateKey",i)),this.http.authedRequest(de.Get,s)}sendStateEvent(e,n,r){var i=arguments,s=this;return B(function*(){var o=i.length>3&&i[3]!==void 0?i[3]:"",a=i.length>4&&i[4]!==void 0?i[4]:{},c=s.getRoom(e),l=new $i({room_id:e,type:n,state_key:o,content:r});yield s.encryptStateEventIfNeeded(l,c??void 0);var d={$roomId:e,$eventType:l.getWireType(),$stateKey:l.getWireStateKey()},h=xe("/rooms/$roomId/state/$eventType",d);return o!==void 0&&(h=xe(h+"/$stateKey",d)),s.http.authedRequest(de.Put,h,void 0,l.getWireContent(),a)})()}encryptStateEventIfNeeded(e,n){var r=this;return B(function*(){if(r.enableEncryptedStateEvents&&n&&!(!r.cryptoBackend&&r.usingExternalCrypto)){if(!r.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");(yield r.shouldEncryptEventForRoom(e,n))&&(yield r.cryptoBackend.isStateEncryptionEnabledInRoom(n.roomId))&&(["m.room.create","m.room.member","m.room.join_rules","m.room.power_levels","m.room.third_party_invite","m.room.history_visibility","m.room.guest_access","m.room.encryption"].includes(e.getType())||(yield r.cryptoBackend.encryptEvent(e,n)))}})()}roomInitialSync(e,n){var r,i=xe("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(de.Get,i,{limit:(r=n?.toString())!==null&&r!==void 0?r:"30"})}setRoomReadMarkersHttpRequest(e,n,r,i){var s=this;return B(function*(){var o=xe("/rooms/$roomId/read_markers",{$roomId:e}),a={[ls.FullyRead]:n,[ls.Read]:r};return((yield s.doesServerSupportUnstableFeature("org.matrix.msc2285.stable"))||(yield s.isVersionSupported("v1.4")))&&(a[ls.ReadPrivate]=i),s.http.authedRequest(de.Post,o,void 0,a)})()}getJoinedRooms(){var e=xe("/joined_rooms",{});return this.http.authedRequest(de.Get,e)}getJoinedRoomMembers(e){var n=xe("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(de.Get,n)}publicRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{server:n,limit:r,since:i}=e,s=Hve(e,$ye);if(Object.keys(s).length===0){var o={server:n,limit:r,since:i};return this.http.authedRequest(de.Get,"/publicRooms",o)}else{var a={server:n},c=Yr({limit:r,since:i},s);return this.http.authedRequest(de.Post,"/publicRooms",a,c)}}createAlias(e,n){var r=xe("/directory/room/$alias",{$alias:e}),i={room_id:n};return this.http.authedRequest(de.Put,r,void 0,i)}deleteAlias(e){var n=xe("/directory/room/$alias",{$alias:e});return this.http.authedRequest(de.Delete,n)}getLocalAliases(e){var n=xe("/rooms/$roomId/aliases",{$roomId:e}),r=Xr.V3;return this.http.authedRequest(de.Get,n,void 0,void 0,{prefix:r})}getRoomIdForAlias(e){var n=xe("/directory/room/$alias",{$alias:e});return this.http.authedRequest(de.Get,n)}getRoomDirectoryVisibility(e){var n=xe("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(de.Get,n)}setRoomDirectoryVisibility(e,n){var r=xe("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(de.Put,r,void 0,{visibility:n})}searchUserDirectory(e){var{term:n,limit:r}=e,i={search_term:n};return r!==void 0&&(i.limit=r),this.http.authedRequest(de.Post,"/user_directory/search",void 0,i)}uploadContent(e,n){return this.http.uploadContent(e,n)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,n){var r=n?xe("/profile/$userId/$info",{$userId:e,$info:n}):xe("/profile/$userId",{$userId:e});return this.http.authedRequest(de.Get,r)}doesServerSupportExtendedProfiles(){var e=this;return B(function*(){return(yield e.doesServerSupportUnstableFeature(yQ))||(yield e.doesServerSupportUnstableFeature(bQ))})()}getExtendedProfileRequestPrefix(){var e=this;return B(function*(){return(yield e.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable"))?Xr.V3:"/_matrix/client/unstable/uk.tcpip.msc4133"})()}getExtendedProfile(e){var n=this;return B(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");return n.http.authedRequest(de.Get,xe("/profile/$userId",{$userId:e}),void 0,void 0,{prefix:yield n.getExtendedProfileRequestPrefix()})})()}getExtendedProfileProperty(e,n){var r=this;return B(function*(){if(!(yield r.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=yield r.http.authedRequest(de.Get,xe("/profile/$userId/$key",{$userId:e,$key:n}),void 0,void 0,{prefix:yield r.getExtendedProfileRequestPrefix()});return i[n]})()}setExtendedProfileProperty(e,n){var r=this;return B(function*(){if(!(yield r.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=r.getUserId();yield r.http.authedRequest(de.Put,xe("/profile/$userId/$key",{$userId:i,$key:e}),void 0,{[e]:n},{prefix:yield r.getExtendedProfileRequestPrefix()})})()}deleteExtendedProfileProperty(e){var n=this;return B(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var r=n.getUserId();yield n.http.authedRequest(de.Delete,xe("/profile/$userId/$key",{$userId:r,$key:e}),void 0,void 0,{prefix:yield n.getExtendedProfileRequestPrefix()})})()}patchExtendedProfile(e){var n=this;return B(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var r=n.getUserId();return n.http.authedRequest(de.Patch,xe("/profile/$userId",{$userId:r}),{},e,{prefix:yield n.getExtendedProfileRequestPrefix()})})()}setExtendedProfile(e){var n=this;return B(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var r=n.getUserId();yield n.http.authedRequest(de.Put,xe("/profile/$userId",{$userId:r}),{},e,{prefix:yield n.getExtendedProfileRequestPrefix()})})()}getThreePids(){return this.http.authedRequest(de.Get,"/account/3pid")}addThreePidOnly(e){var n=this;return B(function*(){var r="/account/3pid/add";return n.http.authedRequest(de.Post,r,void 0,e)})()}bindThreePid(e){var n=this;return B(function*(){var r="/account/3pid/bind";return n.http.authedRequest(de.Post,r,void 0,e)})()}unbindThreePid(e,n){var r=this;return B(function*(){var i="/account/3pid/unbind",s={medium:e,address:n,id_server:r.getIdentityServerUrl(!0)};return r.http.authedRequest(de.Post,i,void 0,s)})()}deleteThreePid(e,n){var r="/account/3pid/delete";return this.http.authedRequest(de.Post,r,void 0,{medium:e,address:n})}setPassword(e,n,r){var i="/account/password",s={auth:e,new_password:n,logout_devices:r};return this.http.authedRequest(de.Post,i,void 0,s)}getDevices(){return this.http.authedRequest(de.Get,"/devices")}getDevice(e){var n=xe("/devices/$device_id",{$device_id:e});return this.http.authedRequest(de.Get,n)}setDeviceDetails(e,n){var r=xe("/devices/$device_id",{$device_id:e});return this.http.authedRequest(de.Put,r,void 0,n)}deleteDevice(e,n){var r=xe("/devices/$device_id",{$device_id:e}),i={};return n&&(i.auth=n),this.http.authedRequest(de.Delete,r,void 0,i)}deleteMultipleDevices(e,n){var r={devices:e};n&&(r.auth=n);var i="/delete_devices";return this.http.authedRequest(de.Post,i,void 0,r)}getPushers(){var e=this;return B(function*(){var n=yield e.http.authedRequest(de.Get,"/pushers");return(yield e.doesServerSupportUnstableFeature("org.matrix.msc3881"))||(n.pushers=n.pushers.map(r=>(r.hasOwnProperty(J5.name)||(r[J5.name]=!0),r))),n})()}setPusher(e){var n="/pushers/set";return this.http.authedRequest(de.Post,n,void 0,e)}removePusher(e,n){var r="/pushers/set",i={pushkey:e,app_id:n,kind:null};return this.http.authedRequest(de.Post,r,void 0,i)}setLocalNotificationSettings(e,n){var r="".concat(QX.name,".").concat(e);return this.setAccountData(r,n)}getPushRules(){return this.http.authedRequest(de.Get,"/pushrules/").then(e=>(this.setPushRules(e),this.pushRules))}setPushRules(e){this.pushRules=qa.rewriteDefaultRules(this.logger,e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,n,r,i){var s=xe("/pushrules/"+e+"/$kind/$ruleId",{$kind:n,$ruleId:r});return this.http.authedRequest(de.Put,s,void 0,i)}deletePushRule(e,n,r){var i=xe("/pushrules/"+e+"/$kind/$ruleId",{$kind:n,$ruleId:r});return this.http.authedRequest(de.Delete,i)}setPushRuleEnabled(e,n,r,i){var s=xe("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:n,$ruleId:r});return this.http.authedRequest(de.Put,s,void 0,{enabled:i})}setPushRuleActions(e,n,r,i){var s=xe("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:n,$ruleId:r});return this.http.authedRequest(de.Put,s,void 0,{actions:i})}search(e,n){var{body:r,next_batch:i}=e,s={};return i&&(s.next_batch=i),this.http.authedRequest(de.Post,"/search",s,r,{abortSignal:n})}uploadKeysRequest(e,n){return this.http.authedRequest(de.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(de.Post,"/keys/signatures/upload",void 0,e)}downloadKeysForUsers(e){var{token:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r={device_keys:{}};return n!==void 0&&(r.token=n),e.forEach(i=>{r.device_keys[i]=[]}),this.http.authedRequest(de.Post,"/keys/query",void 0,r)}claimOneTimeKeys(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"signed_curve25519",r=arguments.length>2?arguments[2]:void 0,i={};n===void 0&&(n="signed_curve25519");for(var[s,o]of e){var a=i[s]||{};iC(i,s,a),iC(a,o,n)}var c={one_time_keys:i};r&&(c.timeout=r);var l="/keys/claim";return this.http.authedRequest(de.Post,l,void 0,c)}getKeyChanges(e,n){var r={from:e,to:n};return this.http.authedRequest(de.Get,"/keys/changes",r)}uploadDeviceSigningKeys(e,n){var r=Object.assign({},n);return e&&Object.assign(r,{auth:e}),this.http.authedRequest(de.Post,"/keys/device_signing/upload",void 0,r,{prefix:Xr.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");var n=this.http.getUrl("/account/register",void 0,$l.V2,this.idBaseUrl);return this.http.requestOtherUrl(de.Post,n,e)}requestEmailToken(e,n,r,i,s){var o={client_secret:n,email:e,send_attempt:r?.toString()};return i&&(o.next_link=i),this.http.idServerRequest(de.Post,"/validate/email/requestToken",o,$l.V2,s)}requestMsisdnToken(e,n,r,i,s,o){var a={client_secret:r,country:e,phone_number:n,send_attempt:i?.toString()};return s&&(a.next_link=s),this.http.idServerRequest(de.Post,"/validate/msisdn/requestToken",a,$l.V2,o)}submitMsisdnToken(e,n,r,i){var s={sid:e,client_secret:n,token:r};return this.http.idServerRequest(de.Post,"/validate/msisdn/submitToken",s,$l.V2,i??void 0)}submitMsisdnTokenOtherUrl(e,n,r,i){var s={sid:n,client_secret:r,token:i};return this.http.requestOtherUrl(de.Post,e,s)}getIdentityHashDetails(e){return this.http.idServerRequest(de.Get,"/hash_details",void 0,$l.V2,e)}identityHashedLookup(e,n){var r=this;return B(function*(){var i={},s=yield r.getIdentityHashDetails(n);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 m=B(function*(g){var y=g[0].toLowerCase(),v=g[1].toLowerCase(),w=yield rQ("".concat(y," ").concat(v," ").concat(i.pepper)),S=Z3(w);return o[S]=g[0],S});return function(g){return m.apply(this,arguments)}}())),i.algorithm="sha256";else if(s.algorithms.includes("none"))i.addresses=e.map(m=>{var g=m[0].toLowerCase(),y=m[1].toLowerCase(),v="".concat(g," ").concat(y);return o[v]=m[0],v}),i.algorithm="none";else throw new Error("Unsupported identity server: unknown hash algorithm");var a=yield r.http.idServerRequest(de.Post,"/lookup",i,$l.V2,n);if(!(a!=null&&a.mappings))return[];var c=[];for(var l of Object.keys(a.mappings)){var d=a.mappings[l],h=o[l];if(!h)throw new Error("Identity server returned more results than expected");c.push({address:h,mxid:d})}return c})()}lookupThreePid(e,n,r){var i=this;return B(function*(){var s=yield i.identityHashedLookup([[n,e]],r),o=s.find(c=>c.address===n);if(!o)return{};var a={address:n,medium:e,mxid:o.mxid};return a})()}bulkLookupThreePids(e,n){var r=this;return B(function*(){var i=yield r.identityHashedLookup(e.map(c=>[c[1],c[0]]),n),s=[],o=function*(l){var d=e.find(h=>h[1]===l.address);if(!d)throw new Error("Identity sever returned unexpected results");s.push([d[0],l.address,l.mxid])};for(var a of i)yield*o(a);return{threepids:s}})()}getIdentityAccount(e){return this.http.idServerRequest(de.Get,"/account",void 0,$l.V2,e)}sendToDevice(e,n,r){var i=xe("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:r||this.makeTxnId()}),s={messages:Mh(n)},o=new Map;for(var[a,c]of n)o.set(a,Array.from(c.keys()));return this.logger.debug("PUT ".concat(i),o),this.http.authedRequest(de.Put,i,void 0,s)}encryptAndSendToDevice(e,n,r){var i=this;return B(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,n,r);yield i.queueToDevice(s)})()}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(de.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,n){var r=xe("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(de.Get,r,n)}getThirdpartyUser(e,n){var r=xe("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(de.Get,r,n)}getTerms(e,n){var r=this.termsUrlForService(e,n);return this.http.requestOtherUrl(de.Get,r)}agreeToTerms(e,n,r,i){var s=this.termsUrlForService(e,n),o={Authorization:"Bearer "+r};return this.http.requestOtherUrl(de.Post,s,{user_accepts:i},{headers:o})}reportEvent(e,n,r,i){var s=xe("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:n});return this.http.authedRequest(de.Post,s,void 0,{score:r,reason:i})}reportRoom(e,n){var r=xe("/rooms/$roomId/report",{$roomId:e});return this.http.authedRequest(de.Post,r,void 0,{reason:n})}getRoomHierarchy(e,n,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0,o=xe("/rooms/$roomId/hierarchy",{$roomId:e}),a={suggested_only:String(i),max_depth:r?.toString(),from:s,limit:n?.toString()};return this.http.authedRequest(de.Get,o,a,void 0,{prefix:Xr.V1}).catch(c=>{if(c.errcode==="M_UNRECOGNIZED")return this.http.authedRequest(de.Get,o,a,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw c})}unstableCreateFileTree(e){var n=this;return B(function*(){var{room_id:r}=yield n.createRoom({name:e,preset:nT.PrivateChat,power_level_content_override:Yr(Yr({},O1e),{},{users:{[n.getUserId()]:100}}),creation_content:{[sC]:wg.Space},initial_state:[{type:z5.name,state_key:Y5.name,content:{[W5.name]:!0}},{type:Z.RoomEncryption,state_key:"",content:{algorithm:"m.megolm.v1.aes-sha2"}}]});return new G$(n,r)})()}unstableGetFileTreeSpace(e){var n,r,i=this.getRoom(e);if(i?.getMyMembership()!==Be.Join)return null;var s=i.currentState.getStateEvents(Z.RoomCreate,""),o=i.currentState.getStateEvents(z5.name,Y5.name);if(!s)throw new Error("Expected single room create event");return!(o!=null&&(n=o.getContent())!==null&&n!==void 0&&n[W5.name])||((r=s.getContent())===null||r===void 0?void 0:r[sC])!==wg.Space?null:new G$(this,e)}slidingSync(e,n,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(de.Post,"/sync",i,e,{prefix:"/_matrix/client/unstable/org.matrix.simplified_msc3575",baseUrl:n,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(ti.IntentionalMentions)!==Zr.Unsupported}getRoomSummary(e,n){var r=this;return B(function*(){var i={prefix:"/_matrix/client/unstable/im.nheko.summary"};try{var s=xe("/summary/$roomid",{$roomid:e});return yield r.http.authedRequest(de.Get,s,{via:n},void 0,i)}catch(a){if(a instanceof tr&&a.errcode==="M_UNRECOGNIZED"){var o=xe("/rooms/$roomid/summary",{$roomid:e});return yield r.http.authedRequest(de.Get,o,{via:n},void 0,i)}else throw a}})()}processThreadEvents(e,n,r){e.processThreadedEvents(n,r)}processThreadRoots(e,n,r){this.supportsThreads()&&e.processThreadRoots(n,r)}processBeaconEvents(e,n){this.processAggregatedTimelineEvents(e,n)}processAggregatedTimelineEvents(e,n){n!=null&&n.length&&e&&(e.currentState.processBeaconEvents(n,this),e.processPollEvents(n))}whoami(){var e=this;return B(function*(){return e.http.authedRequest(de.Get,"/account/whoami")})()}timestampToEvent(e,n,r){var i=this;return B(function*(){var s=xe("/rooms/$roomId/timestamp_to_event",{$roomId:e}),o={ts:n.toString(),dir:r};try{return yield i.http.authedRequest(de.Get,s,o,void 0,{prefix:Xr.V1})}catch(a){if(a.errcode==="M_UNRECOGNIZED"&&(a.httpStatus===400||a.httpStatus===404||a.httpStatus===405))return yield i.http.authedRequest(de.Get,s,o,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw a}})()}getAuthMetadata(){var e=this;return B(function*(){var n;try{n=yield e.http.request(de.Get,"/auth_metadata",void 0,void 0,{prefix:Xr.Unstable+"/org.matrix.msc2965"})}catch(i){if(i instanceof tr&&i.errcode==="M_UNRECOGNIZED"){var{issuer:r}=yield e.http.request(de.Get,"/auth_issuer",void 0,void 0,{prefix:Xr.Unstable+"/org.matrix.msc2965"});return a7(r)}throw i}return c7(n)})()}}L(sT,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY");function aB(t){return Object.fromEntries(Object.entries(t).map(e=>{var[n,r]=e;return["".concat(Vc,".").concat(n),r]}))}function _Q(t,e){var n,r=t.getUserId(),i=e.getId(),s=t.getRoom(e.getRoomId());if(!(!s||!r||!i)){if(!s.findEventById(i)){M.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 c=s.getThread(e.threadRootId);a=c?c.hasUserReadEvent(r,i):!0}else a=s.hasUserReadEvent(r,i);if(!a){var l=t.getPushActionsForEvent(e,!0),d=!!(l!=null&&(n=l.tweaks)!==null&&n!==void 0&&n.highlight);if(d){var h=s.getUnreadCountForEventContext(Jt.Highlight,e)+1;o?s.setThreadUnreadNotificationCount(e.threadRootId,Jt.Highlight,h):s.setUnreadNotificationCount(Jt.Highlight,h)}var m=!!(l!=null&&l.notify);if(m){var g=s.getUnreadCountForEventContext(Jt.Total,e)+1;o?s.setThreadUnreadNotificationCount(e.threadRootId,Jt.Total,g):s.setUnreadNotificationCount(Jt.Total,g)}}}}function ov(t){return mb(t)?u_:t.threadRootId}function mb(t){if(!t.threadRootId||t.isThreadRoot)return!0;if(!t.isRelation())return M.warn("Event is not a relation or a thread root, but still has a threadRootId! id=".concat(t.getId())),!0;if(t.isRelation(wn.name))return!1;var e=t.relationEventId===t.threadRootId;return e}function cB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function lB(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?cB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):cB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var us=function(t){return t.New="Thread.new",t.Update="Thread.update",t.NewReply="Thread.newReply",t.ViewThread="Thread.viewThread",t.Delete="Thread.delete",t}({}),Zi=function(t){return t[t.None=0]="None",t[t.Experimental=1]="Experimental",t[t.Stable=2]="Stable",t}({});function JE(t,e){return t?Zi.Stable:e?Zi.Experimental:Zi.None}class Un extends CJ{constructor(e,n,r){var i,s;if(super(),i=this,this.id=e,this.rootEvent=n,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",!Un.hasServerSideSupport),L(this,"initalEventFetchProm",void 0),L(this,"replayEvents",[]),L(this,"onTimelineReset",B(function*(){yield i.processRootEventPromise,i.processRootEventPromise=void 0})),L(this,"onBeforeRedaction",(o,a)=>{o!=null&&o.isRelation(wn.name)&&this.room.eventShouldLiveIn(o).threadId===this.id&&o.getId()!==this.id&&!a.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(us.Update,this))}),L(this,"onRedaction",function(){var o=B(function*(a,c,l){if(l===i.id)if(i.replyCount<=0){for(var d of i.timeline)i.clearEventMetadata(d);i.lastEvent=i.rootEvent,i._currentUserParticipated=!1,i.emit(us.Delete,i)}else{var h;((h=i.lastEvent)===null||h===void 0?void 0:h.getId())===a.getAssociatedId()&&(yield i.processRootEventPromise,i.processRootEventPromise=void 0),yield i.updateThreadMetadata()}});return function(a,c,l){return o.apply(this,arguments)}}()),L(this,"onTimelineEvent",(o,a,c)=>{if(!c){var l=o.getSender();l&&a&&this.shouldSendLocalEchoReceipt(l,o)&&a.addLocalEchoReceipt(l,o,ls.Read),o.getId()!==this.id&&o.isRelation(wn.name)&&this.replyCount++}this.onEcho(o,c??!1)}),L(this,"onLocalEcho",o=>{this.onEcho(o,!1)}),L(this,"onEcho",function(){var o=B(function*(a,c){a.threadRootId===i.id&&i.lastEvent!==a&&(yield i.updateThreadMetadata(),a.isRelation(wn.name)&&(c||(i.lastEvent=void 0,i.emit(us.NewReply,i,a))))});return function(a,c){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:sv.Chronological,this.timelineSet=new ag(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new $v(this),this.reEmitter.reEmit(this.timelineSet,[ke.Timeline,ke.TimelineReset]),this.room.on(Kt.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 B(function*(){try{var n=yield e.client.fetchRoomEvent(e.roomId,e.id),r=e.client.getEventMapper();e.rootEvent=r(n)}catch(i){M.error("Failed to fetch thread root to construct thread with",i)}yield e.processEvent(e.rootEvent)})()}static setServerSideSupport(e){Un.hasServerSideSupport=e,e!==Zi.Stable&&(Ig.setPreferUnstable(!0),kg.setPreferUnstable(!0),wn.setPreferUnstable(!0))}static setServerSideListSupport(e){Un.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){Un.hasServerSideFwdPaginationSupport=e}shouldSendLocalEchoReceipt(e,n){var r,i=(r=this.client.canSupport.get(ti.RelationsRecursion))!==null&&r!==void 0?r:Zr.Unsupported;if(i===Zr.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()>n.getTs())return!1}}return!0}get roomState(){return this.room.getLiveTimeline().getState(Me.FORWARDS)}addEventToTimeline(e,n){this.findEventById(e.getId())||this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:n,fromCache:!1,roomState:this.roomState,addToState:!1})}insertEventIntoTimeline(e){var n=e.getId();n&&(this.findEventById(n)||this.timelineSet.insertEventIntoTimeline(e,this.liveTimeline,this.roomState,!1))}addEvents(e,n){e.forEach(r=>this.addEvent(r,n,!1)),this.updateThreadMetadata()}addEvent(e,n){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(!Un.hasServerSideSupport)this.addEventToTimeline(e,n),this.client.decryptEventIfNeeded(e);else if(e.isRelation(vn.Annotation)||e.isRelation(vn.Replace)){this.addRelatedThreadEvent(e,n);return}else!n&&s?(this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e)):n?this.addEventToTimeline(e,n):this.insertEventIntoTimeline(e);e.getId()!==this.id&&e.isRelation(wn.name)&&!n&&s&&(this.lastEvent=void 0),r&&(this.emit(us.NewReply,this,e),this.updateThreadMetadata())}addRelatedThreadEvent(e,n){if(this.initialEventsFetched){var s,o=(s=this.client.canSupport.get(ti.RelationsRecursion))!==null&&s!==void 0?s:Zr.Unsupported;o===Zr.Unsupported?this.insertEventIntoTimeline(e):this.addEventToTimeline(e,n)}else{var r;if((r=this.replayEvents)===null||r===void 0||r.push(e),e.isRelation(vn.Annotation)){var i;(i=this.timelineSet.relations)===null||i===void 0||i.aggregateChildEvent(e,this.timelineSet)}}}processEvent(e){var n=this;return B(function*(){e&&(n.setEventMetadata(e),yield n.fetchEditsWhereNeeded(e))})()}processReceipts(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];for(var{eventId:n,receiptType:r,userId:i,receipt:s,synthetic:o}of e)this.addReceiptToStructure(n,r,i,s,o)}getRootEventBundledRelationship(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.rootEvent;return e?.getServerAggregatedRelation(wn.name)}processRootEvent(){var e=this;return B(function*(){var n=e.getRootEventBundledRelationship();if(Un.hasServerSideSupport&&n){e.replyCount=n.count,e._currentUserParticipated=!!n.current_user_participated;var r=e.client.getEventMapper();e.lastEvent=r(lB(lB({},n.latest_event),{},{room_id:e.roomId})),e.updatePendingReplyCount(),yield e.processEvent(e.lastEvent)}})()}updatePendingReplyCount(){var e=this.pendingEventOrdering===sv.Detached?this.room.getPendingEvents():this.events,n=e.filter(r=>{var i;return r.threadRootId===this.id&&r.isRelation(wn.name)&&r.status!==null&&r.getId()!==((i=this.lastEvent)===null||i===void 0?void 0:i.getId())});this.lastPendingEvent=n.length?n[n.length-1]:void 0,this.pendingReplyCount=n.length}resetLiveTimeline(e,n){var r=this;return B(function*(){var i=r.liveTimeline;r.timelineSet.resetLiveTimeline(e??void 0,n??void 0);var s=r.liveTimeline,o,a;if(e){var c=yield r.client.createMessagesRequest(r.roomId,e,1,ht.Forward);o=c.end}if(n){var l=yield r.client.createMessagesRequest(r.roomId,n,1,ht.Backward);a=l.start}n&&i.getPaginationToken(ht.Forward)===n&&i.setPaginationToken(a??null,ht.Forward),e&&s.getPaginationToken(ht.Backward)===e&&s.setPaginationToken(o??null,ht.Backward)})()}updateThreadFromRootEvent(){var e=this;return B(function*(){Un.hasServerSideSupport&&(!e.initialEventsFetched&&!e.lastEvent&&(yield e.processRootEvent()),yield e.fetchRootEvent()),yield e.processRootEvent()})()}updateThreadMetadata(){var e=this;return B(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 n of e.replayEvents)e.addEvent(n,!1);e.replayEvents=null,e.emit(ke.TimelineReset,e.room,e.timelineSet,!0)}catch(r){M.error("Failed to load start of newly created thread: ",r),e.initialEventsFetched=!1}e.emit(us.Update,e)})()}fetchEditsWhereNeeded(){var e=arguments,n=this;return B(function*(){var r,i=(r=n.client.canSupport.get(ti.RelationsRecursion))!==null&&r!==void 0?r:Zr.Unsupported;if(i===Zr.Unsupported){for(var s=e.length,o=new Array(s),a=0;a<s;a++)o[a]=e[a];return Promise.all(o.filter(Gye).map(function(){var c=B(function*(l){try{var d=yield n.client.relations(n.roomId,l.getId(),vn.Replace,l.getType(),{limit:1});if(d.events.length){var h=d.events[0];l.makeReplaced(h),n.insertEventIntoTimeline(h)}}catch(m){M.error("Failed to load edits for encrypted thread event",m)}});return function(l){return c.apply(this,arguments)}}()))}})()}setEventMetadata(e){e&&(Me.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){if(e){var n;e.setThread(void 0),(n=e.event)===null||n===void 0||(n=n.unsigned)===null||n===void 0||(n=n["m.relations"])===null||n===void 0||delete n[wn.name]}}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:i=>i.isRelation(wn.name),n=this.timeline.length-1;n>=0;n--){var r=this.timeline[n];if(e(r))return r}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,n;return(e=(n=this.lastPendingEvent)!==null&&n!==void 0?n: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 $i}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(e,n){throw new Error("Unsupported function on the thread model")}getEventReadUpTo(e,n){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,n);if(i){var c=this.room.getLastUnthreadedReceiptFor(e);if(!c)return a;for(var l=((d=this.timeline)===null||d===void 0?void 0:d.length)-1;l>=0;--l){var d,h,m=this.timeline[l];if(m.getId()===a)return a;if(m.getTs()<c.ts)return(h=m.getId())!==null&&h!==void 0?h:a}}return a}hasUserReadEvent(e,n){if(e===this.client.getUserId()){var r,i,s,o,a,c,l=((r=(i=this.lastReply())===null||i===void 0?void 0:i.getTs())!==null&&r!==void 0?r:0)<this.room.getOldestThreadedReceiptTs(),d=(s=(o=this.room.getLastUnthreadedReceiptFor(e))===null||o===void 0?void 0:o.ts)!==null&&s!==void 0?s:0,h=((a=this===null||this===void 0||(c=this.lastReply())===null||c===void 0?void 0:c.getTs())!==null&&a!==void 0?a:0)<d;if(l||h)return!0}return this.room.hasUserReadEvent(e,n)}setUnread(e,n){return this.room.setThreadUnreadNotificationCount(this.id,e,n)}getLastUnthreadedReceiptFor(e){return this.room.getLastUnthreadedReceiptFor(e)}}L(Un,"hasServerSideSupport",Zi.None);L(Un,"hasServerSideListSupport",Zi.None);L(Un,"hasServerSideFwdPaginationSupport",Zi.None);function Gye(t){return t.isEncrypted()&&(t.isRelation(wn.name)||t.isThreadRoot)}var Ig=new K3("related_by_senders","io.element.relation_senders"),kg=new K3("related_by_rel_types","io.element.relation_types"),wn=new K3("m.thread","io.element.thread"),Ba=function(t){return t[t.My=0]="My",t[t.All=1]="All",t}({});function SQ(t){switch(t){case Ba.My:return"participated";default:return"all"}}class uB extends Error{constructor(e,n,r){super(n),this.code=e,L(this,"detailedString",void 0),this.name="DecryptionError",this.detailedString=Kye(this,r)}}function Kye(t,e){var n=t.name+"[msg: "+t.message;return e&&(n+=", "+Object.keys(e).map(r=>r+": "+e[r]).join(", ")),n+="]",n}var dB=Object.freeze({visible:!0}),Kt=function(t){return t.Decrypted="Event.decrypted",t.BeforeRedaction="Event.beforeRedaction",t.VisibilityChange="Event.visibilityChange",t.LocalEventIdReplaced="Event.localEventIdReplaced",t.Status="Event.status",t.Replaced="Event.replaced",t.RelationsCreated="Event.relationsCreated",t.SentinelUpdated="Event.sentinelUpdated",t}({});class $i extends On{setMetadata(e,n){var r,i,s=this.isState()&&this.getType()===Z.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()===Z.RoomMember){var c=e.getSentinelMember(this.getStateKey());c!==this.target&&(o=!0),this.target=c}this.isState()&&n&&(this.forwardLooking=!1),o&&this.emit(Kt.SentinelUpdated)}constructor(){var e,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.event=n,L(this,"pushDetails",{}),L(this,"_replacingEvent",null),L(this,"_localRedactionEvent",null),L(this,"_isCancelled",!1),L(this,"clearEvent",void 0),L(this,"visibility",dB),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 n[i]=="string"&&(n[i]=Sk(n[i]))}),["membership","avatar_url","displayname"].forEach(i=>{var s;typeof((s=n.content)===null||s===void 0?void 0:s[i])=="string"&&(n.content[i]=Sk(n.content[i]))}),["rel_type"].forEach(i=>{var s;typeof((s=n.content)===null||s===void 0||(s=s["m.relates_to"])===null||s===void 0?void 0:s[i])=="string"&&(n.content["m.relates_to"][i]=Sk(n.content["m.relates_to"][i]))}),this.txnId=n.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 $v(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=to.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){var e=Object.assign({},this.getContent());if(this.getWireType()===Z.RoomMessageEncrypted)for(var[n,r]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(n)||e[n]===void 0&&(e[n]=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 n;return"id=".concat(this.getId()," type=").concat(this.getWireType()," sender=").concat(this.getSender()," room=").concat(e," ts=").concat((n=this.getDate())===null||n===void 0?void 0:n.toISOString())}else{var r=this.getContent()[X3];return"msgid=".concat(r," type=").concat(this.getWireType()," sender=").concat(this.getSender())}}getOriginalContent(){var e;if(this._localRedactionEvent)return{};if(this.clearEvent){var n;return(n=this.clearEvent.content)!==null&&n!==void 0?n:{}}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 n=(e=this.getWireContent())===null||e===void 0?void 0:e["m.relates_to"];if(n?.rel_type===wn.name)return n.event_id;if(this.thread)return this.thread.id;if(this.threadId!==void 0)return this.threadId;var r=this.getUnsigned();if(typeof r[oC.name]=="string")return r[oC.name]}}get isThreadRoot(){if(this.isState())return!1;var e=this.getServerAggregatedRelation(wn.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.clearEvent?this.clearEvent.state_key:this.event.state_key}getWireStateKey(){return this.event.state_key}isState(){return this.event.state_key!==void 0}getMembershipAtEvent(){var e=this.getUnsigned();return ZX.findIn(e)}makeEncrypted(e,n,r,i){this.clearEvent={type:this.event.type,content:this.event.content,state_key:this.event.state_key},this.event.type=e,this.event.content=n,this.senderCurve25519Key=r,this.claimedEd25519Key=i,this.isState()&&(this.event.state_key="".concat(this.clearEvent.type,":").concat(this.clearEvent.state_key))}isBeingDecrypted(){return this.decryptionPromise!=null}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){return this._decryptionFailureReason!==null}get decryptionFailureReason(){return this._decryptionFailureReason}shouldAttemptDecryption(){return!(this.isRedacted()||this.isBeingDecrypted()||this.clearEvent||!this.isEncrypted())}attemptDecryption(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[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?(M.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 n=[{userId:e,deviceId:"*"}];return n}decryptionLoop(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:{};for(yield Promise.resolve();;){r.retryDecryption=!1;var s=void 0;try{var o=yield e.decryptEvent(r);i.isRetry===!0&&M.info("Decrypted event on retry (".concat(r.getDetails(),")")),r.setClearData(o),r._decryptionFailureReason=null}catch(c){var a=c instanceof uB?c.detailedString:String(c);if(s=c,r.retryDecryption){M.log("Error decrypting event (".concat(r.getDetails(),"), but retrying: ").concat(a));continue}M.warn("Error decrypting event (".concat(r.getDetails(),"): ").concat(a)),r.setClearDataForDecryptionFailure(String(c)),r._decryptionFailureReason=c instanceof uB?c.code:K1e.UNKNOWN_ERROR}r.decryptionPromise=null,r.retryDecryption=!1,r.setPushDetails(),i.emit!==!1&&r.emit(Kt.Decrypted,r,s);return}})()}setClearData(e){var n,r;this.clearEvent=e.clearEvent,this.senderCurve25519Key=(n=e.senderCurve25519Key)!==null&&n!==void 0?n: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:Z.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.event.type===Z.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(Kt.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var n,r,i=(n=e?.visible)!==null&&n!==void 0?n:!0,s=(r=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=dB:this.visibility=Object.freeze({visible:!1,reason:s}),this.emit(Kt.VisibilityChange,this,i))}messageVisibility(){return this.visibility}makeRedacted(e,n){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(Kt.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)&&!zye.has(r)&&delete this.event[r];this.isEncrypted()&&(this.clearEvent=void 0);var i=this.getType()in fB?fB[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(n),e.moveToMainTimeline(n)),this.invalidateExtensibleEvent()}moveAllRelatedToMainTimeline(e){var n=this.thread;if(this.moveToMainTimeline(e),n)for(var r of n.events){var i;((i=r.getRelation())===null||i===void 0?void 0:i.event_id)===this.getId()&&r.moveAllRelatedToMainTimeline(e)}}moveToMainTimeline(e){var n;(n=this.thread)===null||n===void 0||n.timelineSet.removeEvent(this.getId()),this.setThread(void 0);var r=e.getLiveTimeline();r.getTimelineSet().insertEventIntoTimeline(this,r,r.getState(Me.FORWARDS),!1)}isRedacted(){return!!this.getUnsigned().redacted_because}isRedaction(){return this.getType()===Z.RoomRedaction}asVisibilityChange(){if(!Dh.matches(this.getType()))return null;var e=this.getRelation();if(!e||e.rel_type!="m.reference")return null;var n=e.event_id;if(!n)return null;var r=this.getWireContent(),i=!!r.visible,s=r.reason;return s&&typeof s!="string"?null:{visible:i,reason:s,eventId:n}}isVisibilityEvent(){return Dh.matches(this.getType())}getRedactionEvent(){var e,n;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(n=this.event.unsigned)!==null&&n!==void 0&&n.redacted_because?this.event.unsigned.redacted_because:{}}getPushActions(){return this.pushDetails.actions||null}getPushDetails(){return this.pushDetails}setPushDetails(e,n){this.pushDetails={actions:e,rule:n}}handleRemoteEcho(e){var n,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(Kt.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-((n=this.getAge())!==null&&n!==void 0?n:0)}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(Kt.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(Kt.LocalEventIdReplaced,this)}isRelation(e){var n,r=(n=this.getWireContent())===null||n===void 0?void 0:n["m.relates_to"];return this.isState()&&(r!=null&&r.rel_type)&&[vn.Replace,vn.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(Kt.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var n;return(n=this.getUnsigned()["m.relations"])===null||n===void 0?void 0:n[e]}replacingEventId(){var e=this.getServerAggregatedRelation(vn.Replace);if(e)return e.event_id;if(this._replacingEvent)return this._replacingEvent.getId()}replacingEvent(){return this._replacingEvent}replacingEventDate(){var e=this.getServerAggregatedRelation(vn.Replace);if(e){var n=e.origin_server_ts;if(Number.isFinite(n))return new Date(n)}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 n=this.getRelation();n?n.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 $i(JSON.parse(JSON.stringify(this.event)));for(var[n,r]of Object.entries(this))n!=="event"&&(e[n]=r);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;var n=H5(this.event),r=H5(e.event);return JSON.stringify(n)===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,[us.Update]),this.thread=e,this.setThreadId(e?.id),e&&this.reEmitter.reEmit(e,[us.Update]))}getThread(){return this.thread}setThreadId(e){this.threadId=e}}var zye=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),fB={[Z.RoomMember]:{membership:1},[Z.RoomJoinRules]:{join_rule:1},[Z.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}},Wye=["1","2","3","4","5","6","7","8","9","10","11"];function Yye(t){return!Wye.includes(t)}var yo=function(t){return t[t.NotStarted=0]="NotStarted",t[t.InProgress=1]="InProgress",t[t.Finished=2]="Finished",t}(yo||{}),pt=function(t){return t.Events="RoomState.events",t.Members="RoomState.members",t.NewMember="RoomState.newMember",t.Update="RoomState.update",t.BeaconLiveness="RoomState.BeaconLiveness",t.Marker="RoomState.Marker",t}({});class gb extends On{constructor(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{status:yo.NotStarted};super(),this.roomId=e,this.oobMemberFlags=n,L(this,"reEmitter",new $v(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",[]),L(this,"getVersionWarning",!1),this.updateModifiedTime()}getRoomVersion(){var e,n=this.getStateEvents(Z.RoomCreate,"");return n?(e=n.getContent().room_version)!==null&&e!==void 0?e:"1":(this.getVersionWarning||(M.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}getJoinedMemberCount(){return this.summaryJoinedMemberCount!==null?this.summaryJoinedMemberCount:(this.joinedMemberCount===null&&(this.joinedMemberCount=this.getMembers().reduce((e,n)=>n.membership===Be.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,n)=>n.membership===Be.Invite?e+1:e,0)),this.invitedMemberCount)}setInvitedMemberCount(e){this.summaryInvitedMemberCount=e}getMembers(){return Object.values(this.members)}getMembersExcept(e){return this.getMembers().filter(n=>!e.includes(n.userId))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;var n=this.sentinels[e];if(n===void 0){n=new cb(this.roomId,e);var r=this.members[e];r!=null&&r.events.member&&n.setMembershipEvent(r.events.member,this),this.sentinels[e]=n}return n}getStateEvents(e,n){if(!this.events.has(e))return n===void 0?[]:null;if(n===void 0)return Array.from(this.events.get(e).values());var r=this.events.get(e).get(n);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 gb(this.roomId,this.oobMemberFlags),n=this.oobMemberFlags.status;return this.oobMemberFlags.status=yo.NotStarted,Array.from(this.events.values()).forEach(r=>{e.setStateEvents(Array.from(r.values()))}),this.oobMemberFlags.status=n,this.summaryInvitedMemberCount!==null&&e.setInvitedMemberCount(this.getInvitedMemberCount()),this.summaryJoinedMemberCount!==null&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==yo.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 n=e.filter(r=>!this.events.has(r.getType())||!this.events.get(r.getType()).has(r.getStateKey()));this.setStateEvents(n)}setStateEvents(e,n){this.updateModifiedTime(),e.forEach(r=>{if(!(r.getRoomId()!==this.roomId||!r.isState())){ZO.matches(r.getType())&&this.setBeacon(r);var i=this.getStateEventMatching(r);if(this.setStateEvent(r),r.getType()===Z.RoomMember){var s;this.updateDisplayNameCache(r.getStateKey(),(s=r.getContent().displayname)!==null&&s!==void 0?s:""),this.updateThirdPartyTokenCache(r)}this.emit(pt.Events,r,this,i)}}),this.onBeaconLivenessChange(),e.forEach(r=>{if(!(r.getRoomId()!==this.roomId||!r.isState()))if(r.getType()===Z.RoomMember){var i=r.getStateKey();(r.getContent().membership===Be.Leave||r.getContent().membership===Be.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(pt.Members,r,this,s)}else if(r.getType()===Z.RoomPowerLevels){if(r.getStateKey()!=="")return;var o=Object.values(this.members),a=this.getStateEvents(Z.RoomCreate,""),c=hB(this.getRoomVersion(),a);o.forEach(l=>{var d=l.getLastModifiedTime();if(a){var h=pB(l.userId,r,c);l.setPowerLevel(h,r)}d!==l.getLastModifiedTime()&&this.emit(pt.Members,r,this,l)}),this.sentinels={}}else XX.matches(r.getType())&&this.emit(pt.Marker,r,n)}),this.emit(pt.Update,this)}processBeaconEvents(e,n){var r=this;return B(function*(){if(!(!e.length||!r.beacons.size)){var i=[...r.beacons.values()].reduce((l,d)=>(l[d.beaconInfoId]=d,l),{}),s=(l,d)=>{if(pA.matches(d.getType())){var h=i[l];h&&h.addLocations([d])}},o=function*(d){var h,m=(h=d.getRelation())===null||h===void 0?void 0:h.event_id;if(!m||!i[m])return{v:void 0};if(!pA.matches(d.getType())&&!d.isEncrypted())return{v:void 0};try{yield n.decryptEventIfNeeded(d),s(m,d)}catch{d.isDecryptionFailure()&&d.once(Kt.Decrypted,B(function*(){s(m,d)}))}},a;for(var c of e)if(a=yield*o(c),a)return a.v}})()}getOrCreateMember(e,n){var r=this.members[e];return r||(r=new cb(this.roomId,e),this.members[e]=r,this.emit(pt.NewMember,n,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 n=cC(e);if(this.beacons.has(n)){var r=this.beacons.get(n);if(e.isRedacted()){var i;r.beaconInfoId===((i=e.getRedactionEvent())===null||i===void 0?void 0:i.redacts)&&(r.destroy(),this.beacons.delete(n));return}return r.update(e)}if(!e.isRedacted()){var s=new EJ(e);this.reEmitter.reEmit(s,[qn.New,qn.Update,qn.Destroy,qn.LivenessChange]),this.emit(qn.New,e,s),s.on(qn.LivenessChange,this.onBeaconLivenessChange.bind(this)),s.on(qn.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(pt.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var n,r;return(n=(r=this.events.get(e.getType()))===null||r===void 0?void 0:r.get(e.getStateKey()))!==null&&n!==void 0?n:null}updateMember(e){var n=this.getStateEvents(Z.RoomCreate,""),r=this.getStateEvents(Z.RoomPowerLevels,"");if(r&&n){var i=pB(e.userId,r,hB(this.getRoomVersion(),n));e.setPowerLevel(i,r)}delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===yo.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===yo.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===yo.NotStarted&&(this.oobMemberFlags.status=yo.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===yo.InProgress&&(this.oobMemberFlags.status=yo.NotStarted)}clearOutOfBandMembers(){var e=0;Object.keys(this.members).forEach(n=>{var r=this.members[n];r.isOutOfBand()&&(++e,delete this.members[n])}),M.log("LL: RoomState removed ".concat(e," members...")),this.oobMemberFlags.status=yo.NotStarted}setOutOfBandMembers(e){M.log("LL: RoomState about to set ".concat(e.length," OOB members ...")),this.oobMemberFlags.status===yo.InProgress&&(M.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=yo.Finished,e.forEach(n=>this.setOutOfBandMember(n)),this.emit(pt.Update,this))}setOutOfBandMember(e){if(e.getType()===Z.RoomMember){var n=e.getStateKey(),r=this.getMember(n);if(!(r&&!r.isOutOfBand())){var i=this.getOrCreateMember(n,e);i.setMembershipEvent(e,this),i.markOutOfBand(),this.updateDisplayNameCache(i.userId,i.name),this.setStateEvent(e),this.updateMember(i),this.emit(pt.Members,e,this,i)}}}setTypingEvent(e){Object.values(this.members).forEach(function(n){n.setTypingEvent(e)})}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var n;return(n=this.displayNameToUserIds.get(Qd(e)))!==null&&n!==void 0?n:[]}maySendRedactionForEvent(e,n){var r=this.getMember(n);if(!r||r.membership===Be.Leave||e.status||e.isRedacted())return!1;var i=this.maySendEvent(Z.RoomRedaction,n);return i?e.getSender()===n?!0:this.hasSufficientPowerLevelFor("redact",r.powerLevel):!1}hasSufficientPowerLevelFor(e,n){var r=this.getStateEvents(Z.RoomPowerLevels,""),i={};r&&(i=r.getContent());var s=50;return AF(i[e])&&(s=i[e]),n>=s}maySendMessage(e){return this.maySendEventOfType(Z.RoomMessage,e,!1)}maySendEvent(e,n){return this.maySendEventOfType(e,n,!1)}mayClientSendStateEvent(e,n){return n.isGuest()||!n.credentials.userId?!1:this.maySendStateEvent(e,n.credentials.userId)}maySendStateEvent(e,n){return this.maySendEventOfType(e,n,!0)}maySendEventOfType(e,n,r){var i,s=this.getStateEvents(Z.RoomPowerLevels,""),o,a={},c=0,l=0;s&&(o=s.getContent(),a=o.events||{},Number.isSafeInteger(o.state_default)?c=o.state_default:c=50,Number.isSafeInteger(o.events_default)&&(l=o.events_default));var d=r?c:l;Number.isSafeInteger(a[e])&&(d=a[e]);var h=this.getMember(n),m=(i=h?.powerLevel)!==null&&i!==void 0?i:0;return m>=d}mayTriggerNotifOfType(e,n){var r=this.getMember(n);if(!r)return!1;var i=this.getStateEvents(Z.RoomPowerLevels,""),s=50;return i&&i.getContent()&&i.getContent().notifications&&AF(i.getContent().notifications[e])&&(s=i.getContent().notifications[e]),r.powerLevel>=s}getJoinRule(){var e,n=this.getStateEvents(Z.RoomJoinRules,""),r=(e=n?.getContent())!==null&&e!==void 0?e:{};return r.join_rule||ef.Invite}getHistoryVisibility(){var e,n=this.getStateEvents(Z.RoomHistoryVisibility,""),r=(e=n?.getContent())!==null&&e!==void 0?e:{};return r.history_visibility||QO.Shared}getGuestAccess(){var e,n=this.getStateEvents(Z.RoomGuestAccess,""),r=(e=n?.getContent())!==null&&e!==void 0?e:{};return r.guest_access||dC.Forbidden}findPredecessor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(e){var n=this.getStateEvents(Z.RoomPredecessor,"");if(n){var r=n.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(Z.RoomCreate,"");if(a){var c=a.getContent().predecessor;if(c){var l=c.room_id;if(typeof l=="string"){var d=c.event_id;return(typeof d!="string"||d==="")&&(d=void 0),{roomId:l,eventId:d}}}}return null}updateThirdPartyTokenCache(e){if(e.getContent().third_party_invite){var n=(e.getContent().third_party_invite.signed||{}).token;if(n){var r=this.getStateEvents(Z.RoomThirdPartyInvite,n);r&&(this.tokenToInvite[n]=e)}}}updateDisplayNameCache(e,n){var r=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],r){var i=Qd(r),s=this.displayNameToUserIds.get(i);if(s){var o=s.filter(d=>d!==e);this.displayNameToUserIds.set(i,o)}}this.userIdsToDisplayNames[e]=n;var a=n&&Qd(n);if(a){var c,l=(c=this.displayNameToUserIds.get(a))!==null&&c!==void 0?c:[];l.push(e),this.displayNameToUserIds.set(a,l)}}}function hB(t,e){var n=new Set;if(Yye(t)&&e){var r=e.getSender();r&&n.add(r);var i=e.getDirectionalContent().additional_creators;Array.isArray(i)&&i.forEach(s=>n.add(s))}return n}function pB(t,e,n){if(n.has(t))return 1/0;var r=e.getDirectionalContent(),i=r.users||{};return i[t]!==void 0&&Number.isInteger(i[t])?i[t]:r.users_default!==void 0?r.users_default:0}function mB(t){var e=typeof t=="string"&&!!t&&t!=="undefined"&&t!=="null";return e||typeof t=="number"}class vb{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 vu(()=>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",(n,r,i)=>{var s;if(i.membership!==Be.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(pt.Members,this.onRoomMember),e.currentState.getMembers().forEach(n=>{this.onRoomMember(null,e.currentState,n)})}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(pt.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,n){return[]}storeEvents(e,n,r,i){}storeFilter(e){!(e!=null&&e.userId)||!(e!=null&&e.filterId)||this.filters.getOrCreate(e.userId).set(e.filterId,e)}getFilter(e,n){var r;return((r=this.filters.get(e))===null||r===void 0?void 0:r.get(n))||null}getFilterIdByName(e){if(!this.localStorage)return null;var n="mxjssdk_memory_filter_"+e;try{var r=this.localStorage.getItem(n);if(mB(r))return r}catch{}return null}setFilterIdByName(e,n){if(this.localStorage){var r="mxjssdk_memory_filter_"+e;try{mB(n)?this.localStorage.setItem(r,n):this.localStorage.removeItem(r)}catch{}}}storeAccountDataEvents(e){e.forEach(n=>{var r=!Object.keys(n.getContent()).length;r?this.accountData.delete(n.getType()):this.accountData.set(n.getType(),n)})}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 vu(()=>new Map),this.accountData=new Map,Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers.get(e)||null)}setOutOfBandMembers(e,n){return this.oobMembers.set(e,n),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 n=this;return B(function*(){var r;return(r=n.pendingEvents[e])!==null&&r!==void 0?r:[]})()}setPendingEvents(e,n){var r=this;return B(function*(){r.pendingEvents[e]=n})()}saveToDeviceBatches(e){for(var n of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:n.eventType,txnId:n.txnId,batch:n.batch});return Promise.resolve()}getOldestToDeviceBatch(){var e=this;return B(function*(){return e.pendingToDeviceBatches.length===0?null:e.pendingToDeviceBatches[0]})()}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter(n=>n.id!==e),Promise.resolve()}destroy(){return B(function*(){})()}}var EQ=(t=>(t.ToWidget="toWidget",t.FromWidget="fromWidget",t))(EQ||{});function Xye(t){if(t==="toWidget")return"fromWidget";if(t==="fromWidget")return"toWidget";throw new Error("Invalid direction")}var Kl=(t=>(t.MSC2762="org.matrix.msc2762",t.MSC2762_UPDATE_STATE="org.matrix.msc2762_update_state",t.MSC2871="org.matrix.msc2871",t.MSC2873="org.matrix.msc2873",t.MSC2931="org.matrix.msc2931",t.MSC2974="org.matrix.msc2974",t.MSC2876="org.matrix.msc2876",t.MSC3819="org.matrix.msc3819",t.MSC3846="town.robin.msc3846",t.MSC3869="org.matrix.msc3869",t.MSC3973="org.matrix.msc3973",t.MSC4039="org.matrix.msc4039",t))(Kl||{});const Jye=["0.0.1","0.0.2","org.matrix.msc2762","org.matrix.msc2762_update_state","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 Qye extends Y3.EventEmitter{constructor(e,n,r,i){super(),this.sendDirection=e,this.initialWidgetId=n,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=n}get ready(){return this._ready}get widgetId(){return this._widgetId||null}get nextRequestId(){const e=`widgetapi-${Date.now()}`;let n=0,r=e;for(;this.outboundRequests.has(r);)r=`${e}-${n++}`;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,n){return this.sendInternal({...e,response:n})}send(e,n){return this.sendComplete(e,n).then(r=>r.response)}sendComplete(e,n){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:n};return e===vr.UpdateVisibility&&(r.visible=n.visible),new Promise((i,s)=>{const o=h=>{d(),i(h)},a=h=>{d(),s(h)},c=setTimeout(()=>a(new Error("Request timed out")),(this.timeoutSeconds||1)*1e3),l=()=>a(new Error("Transport stopped"));this.stopController.signal.addEventListener("abort",l);const d=()=>{this.outboundRequests.delete(r.requestId),clearTimeout(c),this.stopController.signal.removeEventListener("abort",l)};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 n=e.data;if(!(!n.action||!n.requestId||!n.widgetId))if(n.response){if(n.api!==this.sendDirection)return;this.handleResponse(n)}else{const r=n;if(r.api!==Xye(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 n=this.outboundRequests.get(e.requestId);if(n)if(ebe(e.response)){const{message:r,...i}=e.response.error;n.reject(new yC(r,i))}else n.resolve(e)}}var vr=(t=>(t.SupportedApiVersions="supported_api_versions",t.Capabilities="capabilities",t.NotifyCapabilities="notify_capabilities",t.ThemeChange="theme_change",t.LanguageChange="language_change",t.TakeScreenshot="screenshot",t.UpdateVisibility="visibility",t.OpenIDCredentials="openid_credentials",t.WidgetConfig="widget_config",t.CloseModalWidget="close_modal",t.ButtonClicked="button_clicked",t.SendEvent="send_event",t.SendToDevice="send_to_device",t.UpdateState="update_state",t.UpdateTurnServers="update_turn_servers",t))(vr||{}),Qn=(t=>(t.SupportedApiVersions="supported_api_versions",t.ContentLoaded="content_loaded",t.SendSticker="m.sticker",t.UpdateAlwaysOnScreen="set_always_on_screen",t.GetOpenIDCredentials="get_openid",t.CloseModalWidget="close_modal",t.OpenModalWidget="open_modal",t.SetModalButtonEnabled="set_button_enabled",t.SendEvent="send_event",t.SendToDevice="send_to_device",t.WatchTurnServers="watch_turn_servers",t.UnwatchTurnServers="unwatch_turn_servers",t.BeeperReadRoomAccountData="com.beeper.read_room_account_data",t.MSC2876ReadEvents="org.matrix.msc2876.read_events",t.MSC2931Navigate="org.matrix.msc2931.navigate",t.MSC2974RenegotiateCapabilities="org.matrix.msc2974.request_capabilities",t.MSC3869ReadRelations="org.matrix.msc3869.read_relations",t.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",t.MSC4039GetMediaConfigAction="org.matrix.msc4039.get_media_config",t.MSC4039UploadFileAction="org.matrix.msc4039.upload_file",t.MSC4039DownloadFileAction="org.matrix.msc4039.download_file",t.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",t))(Qn||{}),eg=(t=>(t.Allowed="allowed",t.Blocked="blocked",t.PendingUserConfirmation="request",t))(eg||{}),wQ=(t=>(t.Custom="m.custom",t.JitsiMeet="m.jitsi",t.Stickerpicker="m.stickerpicker",t))(wQ||{}),CQ=(t=>(t.Close="m.close",t))(CQ||{}),Dc=(t=>(t.Send="send",t.Receive="receive",t))(Dc||{});class Ji{constructor(e,n,r,i,s){this.direction=e,this.eventType=n,this.kind=r,this.keyStr=i,this.raw=s}matchesAsStateEvent(e,n,r){return this.kind!=="state_event"||this.direction!==e||this.eventType!==n?!1:this.keyStr===null||this.keyStr===r}matchesAsToDeviceEvent(e,n){return!(this.kind!=="to_device"||this.direction!==e||this.eventType!==n)}matchesAsRoomEvent(e,n,r=null){if(this.kind!=="event"||this.direction!==e||this.eventType!==n)return!1;if(this.eventType==="m.room.message"){if(this.keyStr===null||this.keyStr===r)return!0}else return!0;return!1}matchesAsRoomAccountData(e,n){return!(this.kind!=="room_account"||this.direction!==e||this.eventType!==n)}static forStateEvent(e,n,r){n=n.replace(/#/g,"\\#"),r=r!=null?`#${r}`:"";const i=`org.matrix.msc2762.${e}.state_event:${n}${r}`;return Ji.findEventCapabilities([i])[0]}static forToDeviceEvent(e,n){const r=`org.matrix.msc3819.${e}.to_device:${n}`;return Ji.findEventCapabilities([r])[0]}static forRoomEvent(e,n){const r=`org.matrix.msc2762.${e}.event:${n}`;return Ji.findEventCapabilities([r])[0]}static forRoomMessageEvent(e,n){n=n??"";const r=`org.matrix.msc2762.${e}.event:m.room.message#${n}`;return Ji.findEventCapabilities([r])[0]}static forRoomAccountData(e,n){const r=`com.beeper.capabilities.${e}.room_account_data:${n}`;return Ji.findEventCapabilities([r])[0]}static findEventCapabilities(e){const n=[];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 c=null;if(s.includes("#")&&a){const l=s.split("#"),d=l.findIndex(h=>!h.endsWith("\\"));s=l.slice(0,d+1).map(h=>h.endsWith("\\")?h.substring(0,h.length-1):h).join("#"),c=l.slice(d+1).join("#")}n.push(new Ji(i,s,o,c,r))}return n}}var kh=(t=>(t.AnyRoom="*",t))(kh||{});const G3=class G3 extends Error{constructor(e,n){super(e),this.data=n}};G3.prototype.name=G3.name;let yC=G3;class Zye extends Y3.EventEmitter{constructor(e=null,n=null){if(super(),this.clientOrigin=n,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 Qye(EQ.FromWidget,e,window.parent,window),this.transport.targetOrigin=n,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(n=>this.requestCapability(n))}requestCapabilityForRoomTimeline(e){this.requestCapability(`org.matrix.msc2762.timeline:${e}`)}requestCapabilityToSendState(e,n){this.requestCapability(Ji.forStateEvent(Dc.Send,e,n).raw)}requestCapabilityToReceiveState(e,n){this.requestCapability(Ji.forStateEvent(Dc.Receive,e,n).raw)}requestCapabilityToSendToDevice(e){this.requestCapability(Ji.forToDeviceEvent(Dc.Send,e).raw)}requestCapabilityToReceiveToDevice(e){this.requestCapability(Ji.forToDeviceEvent(Dc.Receive,e).raw)}requestCapabilityToSendEvent(e){this.requestCapability(Ji.forRoomEvent(Dc.Send,e).raw)}requestCapabilityToReceiveEvent(e){this.requestCapability(Ji.forRoomEvent(Dc.Receive,e).raw)}requestCapabilityToSendMessage(e){this.requestCapability(Ji.forRoomMessageEvent(Dc.Send,e).raw)}requestCapabilityToReceiveMessage(e){this.requestCapability(Ji.forRoomMessageEvent(Dc.Receive,e).raw)}requestCapabilityToReceiveRoomAccountData(e){this.requestCapability(Ji.forRoomAccountData(Dc.Receive,e).raw)}requestOpenIDConnectToken(){return new Promise((e,n)=>{this.transport.sendComplete(Qn.GetOpenIDCredentials,{}).then(r=>{const i=r.response;if(i.state===eg.Allowed)e(i);else if(i.state===eg.Blocked)n(new Error("User declined to verify their identity"));else if(i.state===eg.PendingUserConfirmation){const s=o=>{o.preventDefault();const a=o.detail;a.data.original_request_id===r.requestId&&(a.data.state===eg.Allowed?(e(a.data),this.transport.reply(a,{})):a.data.state===eg.Blocked?(n(new Error("User declined to verify their identity")),this.transport.reply(a,{})):(n(new Error("Invalid state on reply: "+i.state)),this.transport.reply(a,{error:{message:"Invalid state"}})),this.off(`action:${vr.OpenIDCredentials}`,s))};this.on(`action:${vr.OpenIDCredentials}`,s)}else n(new Error("Invalid state: "+i.state))}).catch(n)})}updateRequestedCapabilities(){return this.transport.send(Qn.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}sendContentLoaded(){return this.transport.send(Qn.ContentLoaded,{}).then()}sendSticker(e){return this.transport.send(Qn.SendSticker,e).then()}setAlwaysOnScreen(e){return this.transport.send(Qn.UpdateAlwaysOnScreen,{value:e}).then(n=>n.success)}openModalWidget(e,n,r=[],i={},s=wQ.Custom){return this.transport.send(Qn.OpenModalWidget,{type:s,url:e,name:n,buttons:r,data:i}).then()}closeModalWidget(e={}){return this.transport.send(Qn.CloseModalWidget,e).then()}sendRoomEvent(e,n,r,i,s){return this.sendEvent(e,void 0,n,r,i,s)}sendStateEvent(e,n,r,i,s,o){return this.sendEvent(e,n,r,i,s,o)}sendEvent(e,n,r,i,s,o){return this.transport.send(Qn.SendEvent,{type:e,content:r,...n!==void 0&&{state_key:n},...i!==void 0&&{room_id:i},...s!==void 0&&{delay:s},...o!==void 0&&{parent_delay_id:o}})}updateDelayedEvent(e,n){return this.transport.send(Qn.MSC4157UpdateDelayedEvent,{delay_id:e,action:n})}sendToDevice(e,n,r){return this.transport.send(Qn.SendToDevice,{type:e,encrypted:n,messages:r})}readRoomAccountData(e,n){const r={type:e};return n&&(n.includes(kh.AnyRoom)?r.room_ids=kh.AnyRoom:r.room_ids=n),this.transport.send(Qn.BeeperReadRoomAccountData,r).then(i=>i.events)}readRoomEvents(e,n,r,i,s){const o={type:e,msgtype:r};return n!==void 0&&(o.limit=n),i&&(i.includes(kh.AnyRoom)?o.room_ids=kh.AnyRoom:o.room_ids=i),s&&(o.since=s),this.transport.send(Qn.MSC2876ReadEvents,o).then(a=>a.events)}async readEventRelations(e,n,r,i,s,o,a,c){if(!(await this.getClientVersions()).includes(Kl.MSC3869))throw new Error("The read_relations action is not supported by the client.");const d={event_id:e,rel_type:r,event_type:i,room_id:n,to:a,from:o,limit:s,direction:c};return this.transport.send(Qn.MSC3869ReadRelations,d)}readStateEvents(e,n,r,i){const s={type:e,state_key:r===void 0?!0:r};return n!==void 0&&(s.limit=n),i&&(i.includes(kh.AnyRoom)?s.room_ids=kh.AnyRoom:s.room_ids=i),this.transport.send(Qn.MSC2876ReadEvents,s).then(o=>o.events)}setModalButtonEnabled(e,n){if(e===CQ.Close)throw new Error("The close button cannot be disabled");return this.transport.send(Qn.SetModalButtonEnabled,{button:e,enabled:n}).then()}navigateTo(e){if(!e||!e.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(Qn.MSC2931Navigate,{uri:e}).then()}async*getTurnServers(){let e;const n=async r=>{r.preventDefault(),e(r.detail.data),await this.transport.reply(r.detail,{})};if(this.on(`action:${vr.UpdateTurnServers}`,n),this.turnServerWatchers===0)try{await this.transport.send(Qn.WatchTurnServers,{})}catch(r){throw this.off(`action:${vr.UpdateTurnServers}`,n),r}this.turnServerWatchers++;try{for(;;)yield await new Promise(r=>e=r)}finally{this.off(`action:${vr.UpdateTurnServers}`,n),this.turnServerWatchers--,this.turnServerWatchers===0&&await this.transport.send(Qn.UnwatchTurnServers,{})}}async searchUserDirectory(e,n){if(!(await this.getClientVersions()).includes(Kl.MSC3973))throw new Error("The user_directory_search action is not supported by the client.");const i={search_term:e,limit:n};return this.transport.send(Qn.MSC3973UserDirectorySearch,i)}async getMediaConfig(){if(!(await this.getClientVersions()).includes(Kl.MSC4039))throw new Error("The get_media_config action is not supported by the client.");const n={};return this.transport.send(Qn.MSC4039GetMediaConfigAction,n)}async uploadFile(e){if(!(await this.getClientVersions()).includes(Kl.MSC4039))throw new Error("The upload_file action is not supported by the client.");const r={file:e};return this.transport.send(Qn.MSC4039UploadFileAction,r)}async downloadFile(e){if(!(await this.getClientVersions()).includes(Kl.MSC4039))throw new Error("The download_file action is not supported by the client.");const r={content_uri:e};return this.transport.send(Qn.MSC4039DownloadFileAction,r)}start(){this.transport.start(),this.getClientVersions().then(e=>{e.includes(Kl.MSC2974)&&(this.supportsMSC2974Renegotiate=!0)})}handleMessage(e){const n=new CustomEvent(`action:${e.detail.action}`,{detail:e.detail,cancelable:!0});if(this.emit(`action:${e.detail.action}`,n),!n.defaultPrevented)switch(e.detail.action){case vr.SupportedApiVersions:return this.replyVersions(e.detail);case vr.Capabilities:return this.handleCapabilities(e.detail);case vr.UpdateVisibility:return this.transport.reply(e.detail,{});case vr.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:Jye})}getClientVersions(){return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(Qn.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(n=>(n.includes(Kl.MSC2871)?this.once(`action:${vr.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 xy=(t=>(t.Screenshots="m.capability.screenshot",t.StickerSending="m.sticker",t.AlwaysOnScreen="m.always_on_screen",t.RequiresClient="io.element.requires_client",t.MSC2931Navigate="org.matrix.msc2931.navigate",t.MSC3846TurnServers="town.robin.msc3846.turn_servers",t.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",t.MSC4039UploadFile="org.matrix.msc4039.upload_file",t.MSC4039DownloadFile="org.matrix.msc4039.download_file",t.MSC4157SendDelayedEvent="org.matrix.msc4157.send.delayed_event",t.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",t))(xy||{});function ebe(t){const e=t.error;return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}function gB(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function L2(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?gB(Object(n),!0).forEach(function(r){L(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gB(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function tbe(t){var e,n,r,i=2;for(typeof Symbol<"u"&&(n=Symbol.asyncIterator,r=Symbol.iterator);i--;){if(n&&(e=t[n])!=null)return e.call(t);if(r&&(e=t[r])!=null)return new QE(e.call(t));n="@@asyncIterator",r="@@iterator"}throw new TypeError("Object is not async iterable")}function QE(t){function e(n){if(Object(n)!==n)return Promise.reject(new TypeError(n+" is not an object."));var r=n.done;return Promise.resolve(n.value).then(function(i){return{value:i,done:r}})}return QE=function(r){this.s=r,this.n=r.next},QE.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 QE(t)}var ZE=function(t){return t.PendingEventsChanged="PendingEvent.pendingEventsChanged",t}({});class TQ extends sT{constructor(e,n,r,i,s){var o,a,c,l,d,h,m,g,y,v,w,S,R,x;super(i),o=this,this.widgetApi=e,this.capabilities=n,this.roomId=r,L(this,"room",void 0),L(this,"widgetApiReady",void 0),L(this,"roomStateSynced",void 0),L(this,"lifecycle",void 0),L(this,"syncState",null),L(this,"pendingSendingEventsTxId",[]),L(this,"eventEmitter",new On),L(this,"updateTxId",function(){var k=B(function*(A){if(A.getSender()===o.getUserId()&&o.pendingSendingEventsTxId.some(U=>A.getType()===U.type)){for(var O,D=(O=o.pendingSendingEventsTxId.find(U=>U.id===A.getId()))===null||O===void 0?void 0:O.txId;!D&&o.pendingSendingEventsTxId.length>0;){var N;yield new Promise(U=>o.eventEmitter.once(ZE.PendingEventsChanged,()=>U())),D=(N=o.pendingSendingEventsTxId.find(U=>U.id===A.getId()))===null||N===void 0?void 0:N.txId}D&&(A.setTxnId(D),A.setUnsigned(L2(L2({},A.getUnsigned()),{},{transaction_id:D}))),o.pendingSendingEventsTxId=o.pendingSendingEventsTxId.filter(U=>U.id!==A.getId()),o.pendingSendingEventsTxId.length===0&&o.eventEmitter.emit(ZE.PendingEventsChanged)}});return function(A){return k.apply(this,arguments)}}()),L(this,"onEvent",function(){var k=B(function*(A){if(A.preventDefault(),A.detail.data.room_id===o.roomId){var O=new $i(A.detail.data);yield o.updateTxId(O),o.syncApi instanceof Vd?(yield o.supportUpdateState())?yield o.syncApi.injectRoomEvents(o.room,void 0,[],[O]):yield o.syncApi.injectRoomEvents(o.room,[],void 0,[O]):(yield o.supportUpdateState())?yield o.syncApi.injectRoomEvents(o.room,[],[O]):M.error("slididng sync cannot be used in widget mode if the client widget driver does not support the version: 'org.matrix.msc2762_update_state'"),o.emit(Le.Event,O),o.setSyncState(Gt.Syncing),M.info("Received event ".concat(O.getId()," ").concat(O.getType()))}else{var{event_id:D,room_id:N}=A.detail.data;M.info("Received event ".concat(D," for a different room ").concat(N,"; discarding"))}yield o.ack(A)});return function(A){return k.apply(this,arguments)}}()),L(this,"onToDevice",function(){var k=B(function*(A){A.preventDefault();var O=new $i({type:A.detail.data.type,sender:A.detail.data.sender,content:A.detail.data.content});A.detail.data.encrypted&&O.makeEncrypted(Z.RoomMessageEncrypted,{},"",""),o.emit(Le.ToDeviceEvent,O),o.setSyncState(Gt.Syncing),yield o.ack(A)});return function(A){return k.apply(this,arguments)}}()),L(this,"onStateUpdate",function(){var k=B(function*(A){A.preventDefault(),(yield o.supportUpdateState())||M.warn("received update_state widget action but the widget driver did not claim to support 'org.matrix.msc2762_update_state'");for(var O of A.detail.data.state)if(O.room_id===o.roomId){var D=new $i(O);o.syncApi instanceof Vd?yield o.syncApi.injectRoomEvents(o.room,void 0,[D]):yield o.syncApi.injectRoomEvents(o.room,[D]),M.info("Updated state entry ".concat(D.getType()," ").concat(D.getStateKey()," to ").concat(D.getId()))}else{var{event_id:N,room_id:U}=A.detail.data;M.info("Received state entry ".concat(N," for a different room ").concat(U,"; discarding"))}yield o.ack(A)});return function(A){return k.apply(this,arguments)}}());var T=this.widgetApi.transport.send.bind(this.widgetApi.transport);this.widgetApi.transport.send=function(){var k=B(function*(A,O){try{return yield T(A,O)}catch(D){vB(D)}});return function(A,O){return k.apply(this,arguments)}}();var I=this.widgetApi.transport.sendComplete.bind(this.widgetApi.transport);this.widgetApi.transport.sendComplete=function(){var k=B(function*(A,O){try{return yield I(A,O)}catch(D){vB(D)}});return function(A,O){return k.apply(this,arguments)}}(),this.widgetApiReady=new Promise(k=>this.widgetApi.once("ready",k)),this.roomStateSynced=(a=n.receiveState)!==null&&a!==void 0&&a.length?new Promise(k=>this.widgetApi.once("action:".concat(vr.UpdateState),k)):Promise.resolve(),((c=n.sendEvent)!==null&&c!==void 0&&c.length||(l=n.receiveEvent)!==null&&l!==void 0&&l.length||n.sendMessage===!0||Array.isArray(n.sendMessage)&&n.sendMessage.length||n.receiveMessage===!0||Array.isArray(n.receiveMessage)&&n.receiveMessage.length||(d=n.sendState)!==null&&d!==void 0&&d.length||(h=n.receiveState)!==null&&h!==void 0&&h.length)&&e.requestCapabilityForRoomTimeline(r),(m=n.sendEvent)===null||m===void 0||m.forEach(k=>e.requestCapabilityToSendEvent(k)),(g=n.receiveEvent)===null||g===void 0||g.forEach(k=>e.requestCapabilityToReceiveEvent(k)),n.sendMessage===!0?e.requestCapabilityToSendMessage():Array.isArray(n.sendMessage)&&n.sendMessage.forEach(k=>e.requestCapabilityToSendMessage(k)),n.receiveMessage===!0?e.requestCapabilityToReceiveMessage():Array.isArray(n.receiveMessage)&&n.receiveMessage.forEach(k=>e.requestCapabilityToReceiveMessage(k)),(y=n.sendState)===null||y===void 0||y.forEach(k=>{var{eventType:A,stateKey:O}=k;return e.requestCapabilityToSendState(A,O)}),(v=n.receiveState)===null||v===void 0||v.forEach(k=>{var{eventType:A,stateKey:O}=k;return e.requestCapabilityToReceiveState(A,O)}),(w=n.sendToDevice)===null||w===void 0||w.forEach(k=>e.requestCapabilityToSendToDevice(k)),(S=n.receiveToDevice)===null||S===void 0||S.forEach(k=>e.requestCapabilityToReceiveToDevice(k)),n.sendDelayedEvents&&((R=n.sendEvent)!==null&&R!==void 0&&R.length||n.sendMessage===!0||Array.isArray(n.sendMessage)&&n.sendMessage.length||(x=n.sendState)!==null&&x!==void 0&&x.length)&&e.requestCapability(xy.MSC4157SendDelayedEvent),n.updateDelayedEvents&&e.requestCapability(xy.MSC4157UpdateDelayedEvent),n.turnServers&&e.requestCapability(xy.MSC3846TurnServers),e.on("action:".concat(vr.SendEvent),this.onEvent),e.on("action:".concat(vr.SendToDevice),this.onToDevice),e.on("action:".concat(vr.UpdateState),this.onStateUpdate),e.start(),s&&e.sendContentLoaded()}supportUpdateState(){var e=this;return B(function*(){return(yield e.widgetApi.getClientVersions()).includes(Kl.MSC2762_UPDATE_STATE)})()}startClient(){var e=arguments,n=this;return B(function*(){var r=e.length>0&&e[0]!==void 0?e[0]:{};n.lifecycle=new AbortController;var i=n.getUserId();if(i&&n.store.storeUser(new yu(i)),r.slidingSync?n.syncApi=new zJ(r.slidingSync,n,r,n.buildSyncApiOptions()):n.syncApi=new Vd(n,r,n.buildSyncApiOptions()),n.room=n.syncApi.createRoom(n.roomId),n.store.storeRoom(n.room),yield n.widgetApiReady,yield n.supportUpdateState())yield n.roomStateSynced;else{var s,o;yield Promise.all((s=(o=n.capabilities.receiveState)===null||o===void 0?void 0:o.map(function(){var a=B(function*(c){var{eventType:l,stateKey:d}=c,h=yield n.widgetApi.readStateEvents(l,void 0,d,[n.roomId]),m=h.map(g=>new $i(g));n.syncApi instanceof Vd?yield n.syncApi.injectRoomEvents(n.room,void 0,m):yield n.syncApi.injectRoomEvents(n.room,m),m.forEach(g=>{n.emit(Le.Event,g),M.info("Backfilled event ".concat(g.getId()," ").concat(g.getType()," ").concat(g.getStateKey()))})});return function(c){return a.apply(this,arguments)}}()))!==null&&s!==void 0?s:[])}r.clientWellKnownPollPeriod!==void 0&&(n.clientWellKnownIntervalID=setInterval(()=>{n.fetchClientWellKnown()},1e3*r.clientWellKnownPollPeriod),n.fetchClientWellKnown()),n.setSyncState(Gt.Syncing),M.info("Finished initial sync"),n.matrixRTC.start(),n.capabilities.turnServers&&n.watchTurnServers()})()}stopClient(){this.widgetApi.off("action:".concat(vr.SendEvent),this.onEvent),this.widgetApi.off("action:".concat(vr.SendToDevice),this.onToDevice),this.widgetApi.off("action:".concat(vr.UpdateState),this.onStateUpdate),super.stopClient(),this.lifecycle.abort()}joinRoom(e){var n=this;return B(function*(){if(e===n.roomId)return n.room;throw new Error("Unknown room: ".concat(e))})()}encryptAndSendEvent(e,n,r){var i=this;return B(function*(){var s=n.event.redacts?L2(L2({},n.getContent()),{},{redacts:n.event.redacts}):n.getContent();if(r){var o=yield i.widgetApi.sendRoomEvent(n.getType(),s,e.roomId,"delay"in r?r.delay:void 0,"parent_delay_id"in r?r.parent_delay_id:void 0).catch(Tc);return i.validateSendDelayedEventResponse(o)}var a=n.getTxnId();a&&i.pendingSendingEventsTxId.push({type:n.getType(),id:void 0,txId:a});var c;try{c=yield i.widgetApi.sendRoomEvent(n.getType(),s,e.roomId).catch(Tc)}catch(l){throw i.updatePendingEventStatus(e,n,rt.NOT_SENT),l}return e.updatePendingEvent(n,rt.SENT,c.event_id),i.pendingSendingEventsTxId.forEach(l=>{l.txId===a&&(l.id=c.event_id)}),i.eventEmitter.emit(ZE.PendingEventsChanged),{event_id:c.event_id}})()}sendStateEvent(e,n,r){var i=arguments,s=this;return B(function*(){var o=i.length>3&&i[3]!==void 0?i[3]:"",a=yield s.widgetApi.sendStateEvent(n,o,r,e).catch(Tc);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,n,r,i){var s=arguments,o=this;return B(function*(){var a=s.length>4&&s[4]!==void 0?s[4]:"";if(!(yield o.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","sendDelayedStateEvent");var c=yield o.widgetApi.sendStateEvent(r,a,i,e,"delay"in n?n.delay:void 0,"parent_delay_id"in n?n.parent_delay_id:void 0).catch(Tc);return o.validateSendDelayedEventResponse(c)})()}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,n){var r=this;return B(function*(){if(!(yield r.doesServerSupportUnstableFeature(Vc)))throw new Gd("Server does not support the delayed events API","updateDelayedEvent");return yield r.widgetApi.updateDelayedEvent(e,n).catch(Tc),{}})()}encryptAndSendToDevice(e,n,r){var i=this;return B(function*(){var s=new vu(()=>new Map);for(var{userId:o,deviceId:a}of n)s.getOrCreate(o).set(a,r);yield i.widgetApi.sendToDevice(e,!0,Mh(s)).catch(Tc)})()}sendToDevice(e,n){var r=this;return B(function*(){return yield r.widgetApi.sendToDevice(e,!1,Mh(n)).catch(Tc),{}})()}getOpenIdToken(){var e=this;return B(function*(){var n=yield e.widgetApi.requestOpenIDConnectToken().catch(Tc);return{access_token:n.access_token,expires_in:n.expires_in,matrix_server_name:n.matrix_server_name,token_type:n.token_type}})()}queueToDevice(e){var n=this;return B(function*(){var{eventType:r,batch:i}=e,s=new vu(()=>new Map);for(var{userId:o,deviceId:a,payload:c}of i)s.getOrCreate(o).set(a,c);yield n.widgetApi.sendToDevice(r,!1,Mh(s)).catch(Tc)})()}sendToDeviceViaWidgetApi(e,n,r){var i=this;return B(function*(){yield i.widgetApi.sendToDevice(e,n,Mh(r)).catch(Tc)})()}checkTurnServers(){var e=this;return B(function*(){return e.turnServers.length>0})()}getSyncState(){return this.syncState}setSyncState(e){var n=this.syncState;this.syncState=e,this.emit(Le.Sync,e,n)}ack(e){var n=this;return B(function*(){yield n.widgetApi.transport.reply(e.detail,{})})()}watchTurnServers(){var e=this;return B(function*(){var n=e.widgetApi.getTurnServers(),r=()=>{n.return(void 0)};e.lifecycle.signal.addEventListener("abort",r);try{var i=!1,s=!1,o;try{for(var a=tbe(n),c;i=!(c=yield a.next()).done;i=!1){var l=c.value;e.turnServers=[{urls:l.uris,username:l.username,credential:l.password}],e.emit(Le.TurnServers,e.turnServers),M.log("Received TURN server: ".concat(l.uris))}}catch(d){s=!0,o=d}finally{try{i&&a.return!=null&&(yield a.return())}finally{if(s)throw o}}}catch(d){M.warn("Error watching TURN servers",d)}finally{e.lifecycle.signal.removeEventListener("abort",r)}})()}}function vB(t){throw t instanceof yC&&t.data.matrix_api_error?tr.fromWidgetApiErrorData(t.data.matrix_api_error):t}function Tc(t){throw t instanceof Error&&t.message==="Request timed out"?new wp("widget api timeout"):t}class nbe{constructor(){L(this,"unthreadedReadReceipts",new Map),L(this,"threadedReadReceipts",new vu(()=>new Map))}setUnthreaded(e,n){this.unthreadedReadReceipts.set(e,n)}setThreaded(e,n,r){this.threadedReadReceipts.getOrCreate(e).set(n,r)}allUnthreaded(){return this.unthreadedReadReceipts.entries()}*allThreaded(){for(var e of this.threadedReadReceipts.values())for(var n of e.entries())yield n}consumeEphemeralEvents(e){e?.forEach(n=>{n.type!==Z.Receipt||!n.content||Object.keys(n.content).forEach(r=>{Object.entries(n.content[r]).forEach(i=>{var[s,o]=i;if(OO(s))for(var a of Object.keys(o)){var c=n.content[r][s][a],l={data:n.content[r][s][a],type:s,eventId:r};c.thread_id?this.setThreaded(c.thread_id,a,l):this.setUnthreaded(a,l)}})})})}buildAccumulatedReceiptEvent(e){var n={type:Z.Receipt,room_id:e,content:{}},r=new vu(()=>new vu(()=>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 n.content=Mh(r),r.size>0?n:null}}var Bl=function(t){return t.Invite="invite",t.Leave="leave",t.Join="join",t.Knock="knock",t}({});function rbe(t){return"_localTs"in t&&t._localTs!==void 0}class RQ{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 n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.accumulateRooms(e,n),this.accumulateAccountData(e),this.nextBatch=e.next_batch}accumulateAccountData(e){!e.account_data||!e.account_data.events||e.account_data.events.forEach(n=>{this.accountData[n.type]=n})}accumulateRooms(e){var n=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,Bl.Invite,e.rooms.invite[r],n)}),e.rooms.join&&Object.keys(e.rooms.join).forEach(r=>{this.accumulateRoom(r,Bl.Join,e.rooms.join[r],n)}),e.rooms.leave&&Object.keys(e.rooms.leave).forEach(r=>{this.accumulateRoom(r,Bl.Leave,e.rooms.leave[r],n)}),e.rooms.knock&&Object.keys(e.rooms.knock).forEach(r=>{this.accumulateRoom(r,Bl.Knock,e.rooms.knock[r],n)}))}accumulateRoom(e,n,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;switch(n){case Bl.Invite:this.knockRooms[e]&&delete this.knockRooms[e],this.accumulateInviteState(e,r);break;case Bl.Knock:this.accumulateKnockState(e,r);break;case Bl.Join:this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,r,i);break;case Bl.Leave:this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:M.error("Unknown cateogory: ",n)}}accumulateInviteState(e,n){if(!(!n.invite_state||!n.invite_state.events)){if(!this.inviteRooms[e]){this.inviteRooms[e]={invite_state:n.invite_state};return}var r=this.inviteRooms[e];n.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,n){if(!(!n.knock_state||!n.knock_state.events)){if(!this.knockRooms[e]){this.knockRooms[e]={knock_state:n.knock_state};return}var r=this.knockRooms[e];n.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,n){var r,i,s,o,a,c,l=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 nbe});var d=this.joinRooms[e];if(n.account_data&&n.account_data.events&&n.account_data.events.forEach(I=>{d._accountData[I.type]=I}),n.unread_notifications&&(d._unreadNotifications=n.unread_notifications),d._unreadThreadNotifications=(r=(i=n[ub.stable])!==null&&i!==void 0?i:n[ub.unstable])!==null&&r!==void 0?r:void 0,n.summary){var h,m,g,y="m.heroes",v="m.invited_member_count",w="m.joined_member_count",S=d._summary,R=n.summary;S[y]=(h=R[y])!==null&&h!==void 0?h:S[y],S[w]=(m=R[w])!==null&&m!==void 0?m:S[w],S[v]=(g=R[v])!==null&&g!==void 0?g:S[v]}if(d._receipts.consumeEphemeralEvents((s=n.ephemeral)===null||s===void 0?void 0:s.events),n.timeline&&n.timeline.limited&&(d._timeline=[]),(o=n.state)===null||o===void 0||(o=o.events)===null||o===void 0||o.forEach(I=>{O2(d._currentState,I)}),(a=n["org.matrix.msc4222.state_after"])===null||a===void 0||(a=a.events)===null||a===void 0||a.forEach(I=>{O2(d._currentState,I)}),(c=n.timeline)===null||c===void 0||(c=c.events)===null||c===void 0||c.forEach((I,k)=>{var A;n["org.matrix.msc4222.state_after"]||O2(d._currentState,I);var O;if(l)O=I;else{var D;O=Object.assign({},I),O.unsigned!==void 0&&(O.unsigned=Object.assign({},O.unsigned));var N=(D=I.unsigned)===null||D===void 0?void 0:D.age;N!==void 0&&(O._localTs=Date.now()-N)}d._timeline.push({event:O,token:k===0&&(A=n.timeline.prev_batch)!==null&&A!==void 0?A:null})}),d._timeline.length>this.opts.maxTimelineEntries){for(var x=d._timeline.length-this.opts.maxTimelineEntries,T=x;T<d._timeline.length;T++)if(d._timeline[T].token){d._timeline=d._timeline.slice(T,d._timeline.length);break}}}getJSON(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,n={join:{},invite:{},knock:{},leave:{}};Object.keys(this.inviteRooms).forEach(i=>{n.invite[i]=this.inviteRooms[i]}),Object.keys(this.knockRooms).forEach(i=>{n.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(m=>{o.account_data.events.push(s._accountData[m])});var a=s._receipts.buildAccumulatedReceiptEvent(i);a&&o.ephemeral.events.push(a),s._timeline.forEach(m=>{if(!o.timeline.prev_batch){if(!m.token)return;o.timeline.prev_batch=m.token}var g;!e&&rbe(m.event)?(g=Object.assign({},m.event),g.unsigned!==void 0&&(g.unsigned=Object.assign({},g.unsigned)),delete g._localTs,g.unsigned=g.unsigned||{},g.unsigned.age=Date.now()-m.event._localTs):g=m.event,o.timeline.events.push(g)});for(var c=Object.create(null),l=o.timeline.events.length-1;l>=0;l--){var d=o.timeline.events[l];if(!(d.state_key===null||d.state_key===void 0)){var h=d_(d);h.unsigned&&(h.unsigned.prev_content&&(h.content=h.unsigned.prev_content),h.unsigned.prev_sender&&(h.sender=h.unsigned.prev_sender)),O2(c,h)}}Object.keys(s._currentState).forEach(m=>{Object.keys(s._currentState[m]).forEach(g=>{var y=s._currentState[m][g];o["org.matrix.msc4222.state_after"].events.push(y),c[m]&&c[m][g]&&(y=c[m][g]),o.state.events.push(y)})}),n.join[i]=o});var r=[];return Object.keys(this.accountData).forEach(i=>{r.push(this.accountData[i])}),{nextBatch:this.nextBatch,roomsData:n,accountData:r}}getNextBatchToken(){return this.nextBatch}}function O2(t,e){e.state_key===null||e.state_key===void 0||!e.type||(t[e.type]||(t[e.type]=Object.create(null)),t[e.type][e.state_key]=e)}var IQ=function(t){return t[t.Blocked=-1]="Blocked",t[t.Unverified=0]="Unverified",t[t.Verified=1]="Verified",t}({});class ibe{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||IQ.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 yB=function(){},sbe=10;class obe{constructor(e,n){var r,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.client=e,this.timelineSet=n,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=n.room)===null||r===void 0||r.on(ke.Timeline,this.onTimelineEvent.bind(this))}load(e){var n=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(l=>l.getId()===e),s<0)throw new Error("getEventTimeline result didn't include requested event");var a=Math.min(o.length,s+Math.ceil(n/2)),c=Math.max(0,a-n);this.start=new IA(i,c-i.getBaseIndex()),this.end=new IA(i,a-i.getBaseIndex()),this.eventCount=a-c};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==Me.BACKWARDS){var n;return(n=this.start)!==null&&n!==void 0?n:null}else if(e==Me.FORWARDS){var r;return(r=this.end)!==null&&r!==void 0?r:null}else throw new Error("Invalid direction '"+e+"'")}extend(e,n){var r=this.getTimelineIndex(e);if(!r)return!1;var i=e==Me.BACKWARDS?r.retreat(n):r.advance(n);if(i){this.eventCount+=i,yB("TimelineWindow: increased cap by "+i+" (now "+this.eventCount+")");var s=this.eventCount-this.windowLimit;return s>0&&this.unpaginate(s,e!=Me.BACKWARDS),!0}return!1}onTimelineEvent(e,n,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 n=this.getTimelineIndex(e);if(!n)return!1;if(e==Me.BACKWARDS){if(n.index>n.minIndex())return!0}else if(n.index<n.maxIndex())return!0;var r=n.timeline.getNeighbouringTimeline(e),i=n.timeline.getPaginationToken(e);return!!r||!!i}paginate(e,n){var r=arguments,i=this;return B(function*(){var s=r.length>2&&r[2]!==void 0?r[2]:!0,o=r.length>3&&r[3]!==void 0?r[3]:sbe,a=i.getTimelineIndex(e);if(!a)return!1;if(a.pendingPaginate)return a.pendingPaginate;if(i.extend(e,n))return!0;if(!s||o===0)return!1;var c=a.timeline.getPaginationToken(e);if(!c)return!1;var l=i.client.paginateEventTimeline(a.timeline,{backwards:e==Me.BACKWARDS,limit:n}).finally(function(){a.pendingPaginate=void 0}).then(d=>d?i.paginate(e,n,!0,o-1):i.paginate(e,n,!1,0));return a.pendingPaginate=l,l})()}unpaginate(e,n){var r=n?this.start:this.end;if(!r)throw new Error("Attempting to unpaginate startOfTimeline=".concat(n," 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=n?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,yB("TimelineWindow.unpaginate: dropped "+i+" (now "+this.eventCount+")")}}getEvents(){if(!this.start)return[];for(var e=[],n=this.start.timeline;n;){var r,i,s=n.getEvents(),o=0,a=s.length;n===this.start.timeline&&(o=this.start.index+n.getBaseIndex()),n===((r=this.end)===null||r===void 0?void 0:r.timeline)&&(a=this.end.index+n.getBaseIndex());for(var c=o;c<a;c++)e.push(s[c]);if(n===((i=this.end)===null||i===void 0?void 0:i.timeline))break;n=n.getNeighbouringTimeline(Me.FORWARDS)}return e}}class IA{constructor(e,n){this.timeline=e,this.index=n,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 n;if(e<0){if(n=Math.max(e,this.minIndex()-this.index),n<0)return this.index+=n,n}else if(n=Math.min(e,this.maxIndex()-this.index),n>0)return this.index+=n,n;var r=this.timeline.getNeighbouringTimeline(e<0?Me.BACKWARDS:Me.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 R1="m.login.email.identity",bB="m.login.msisdn",kA=function(t){return t.Password="m.login.password",t.Recaptcha="m.login.recaptcha",t.Terms="m.login.terms",t.Email="m.login.email.identity",t.Msisdn="m.login.msisdn",t.Sso="m.login.sso",t.SsoUnstable="org.matrix.login.sso",t.Dummy="m.login.dummy",t.RegistrationToken="m.login.registration_token",t.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token",t}({});class kQ extends Error{constructor(e,n,r){super(e),this.required_stages=n,this.flows=r,L(this,"name","NoAuthFlowFoundError")}}class l7{constructor(e){var n=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",B(function*(){if(n.requestingEmailToken)M.warn("Could not request email token: Already requesting");else{M.trace("Requesting email token. Attempt: "+n.emailAttempt),n.requestingEmailToken=!0;try{var r=yield n.requestEmailTokenCallback(n.inputs.emailAddress,n.clientSecret,n.emailAttempt++,n.data.session);n.emailSid=r.sid,M.trace("Email token request succeeded")}finally{n.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 B(function*(){var n;e.attemptAuthDeferred=Promise.withResolvers();var r=e.attemptAuthDeferred.promise;if((n=e.data)!==null&&n!==void 0&&(n=n.flows)!==null&&n!==void 0&&n.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 B(function*(){if(e.data.session&&e.attemptAuthDeferred&&!e.submitPromise){var n={};if(e.currentStage==R1&&e.emailSid){var r={sid:e.emailSid,client_secret:e.clientSecret},i=e.matrixClient.getIdentityServerUrl();i&&(r.id_server=new URL(i).host),n={type:R1,threepid_creds:r}}e.submitAuthDict(n,!0)}})()}getSessionId(){var e;return(e=this.data)===null||e===void 0?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var n;return(n=this.data)===null||n===void 0||(n=n.params)===null||n===void 0?void 0:n[e]}getChosenFlow(){return this.chosenFlow}submitAuthDict(e){var n=arguments,r=this;return B(function*(){var i,s=n.length>1&&n[1]!==void 0?n[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 c;(c=r.busyChangedCallback)===null||c===void 0||c.call(r,!1)}}})()}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}doRequest(e){var n=arguments,r=this;return B(function*(){var i=n.length>1&&n[1]!==void 0?n[1]:!1;try{var s=yield r.requestCallback(e,i);r.attemptAuthDeferred.resolve(s),r.attemptAuthDeferred=null}catch(y){var o,a,c,l,d=y instanceof tr?y:null,h=(o=d==null||(a=d.data)===null||a===void 0?void 0:a.flows)!==null&&o!==void 0?o:null,m=((c=r.data)===null||c===void 0?void 0:c.flows)||!!h;if(!d||d.httpStatus!==401||!d.data||!m)if(i)M.log("Background poll request failed doing UI auth: ignoring",y);else{var g;(g=r.attemptAuthDeferred)===null||g===void 0||g.reject(y)}d&&!d.data&&(d.data={}),d&&!d.data.flows&&!d.data.completed&&!d.data.session&&(d.data.flows=r.data.flows,d.data.completed=r.data.completed,d.data.session=r.data.session),d&&(r.data=d.data);try{r.startNextAuthStage()}catch(v){r.attemptAuthDeferred.reject(v),r.attemptAuthDeferred=null;return}if(!r.emailSid&&(l=r.chosenFlow)!==null&&l!==void 0&&l.stages.includes(kA.Email))try{yield r.requestEmailToken()}catch(v){r.attemptAuthDeferred.reject(v),r.attemptAuthDeferred=null}}})()}startNextAuthStage(){var e,n,r=this.chooseStage();if(!r)throw new Error("No incomplete flows from the server");if(this.currentStage=r,r===kA.Dummy){this.submitAuthDict({type:"m.login.dummy"});return}if((e=this.data)!==null&&e!==void 0&&e.errcode||(n=this.data)!==null&&n!==void 0&&n.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===R1?{emailSid:this.emailSid}:{})}chooseStage(){this.chosenFlow===null&&(this.chosenFlow=this.chooseFlow()),M.log("Active flow => %s",JSON.stringify(this.chosenFlow));var e=this.firstUncompletedStage(this.chosenFlow);return M.log("Next stage: %s",e),e}scoreFlow(e){var n=e.stages.length;return this.supportedStages!==void 0&&(n+=e.stages.filter(r=>!this.supportedStages.has(r)).length*10),n}chooseFlow(){var e,n=((e=this.data)===null||e===void 0?void 0:e.flows)||[],r=!!this.inputs.emailAddress||!!this.emailSid,i=!!this.inputs.phoneCountry&&!!this.inputs.phoneNumber;n.sort((d,h)=>this.scoreFlow(d)-this.scoreFlow(h));for(var s of n){var o=!1,a=!1;for(var c of s.stages)c===R1?o=!0:c==bB&&(a=!0);if(o==r&&a==i)return s}var l=[];throw r&&l.push(R1),i&&l.push(bB),new kQ("No appropriate authentication flow found",l,n)}firstUncompletedStage(e){var n,r=((n=this.data)===null||n===void 0?void 0:n.completed)||[];return e.stages.find(i=>!r.includes(i))}}function xQ(t,e){return new Promise((n,r)=>{var i=!0,s=t.open(e);s.onupgradeneeded=()=>{i=!1},s.onblocked=()=>r(s.error),s.onsuccess=()=>{var o=s.result;o.close(),i||t.deleteDatabase(e),n(i)},s.onerror=()=>r(s.error)})}var AQ=[t=>{t.createObjectStore("users",{keyPath:["userId"]}),t.createObjectStore("accountData",{keyPath:["type"]}),t.createObjectStore("sync",{keyPath:["clobber"]})},t=>{var e=t.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]});e.createIndex("room","room_id")},t=>{t.createObjectStore("client_options",{keyPath:["clobber"]})},t=>{t.createObjectStore("to_device_queue",{autoIncrement:!0})}],abe=AQ.length;function M2(t,e,n){var r=t.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(n(a)),a.continue()}})}function mh(t){return new Promise((e,n)=>{t.oncomplete=function(r){e(r)},t.onerror=function(){n(t.error)}})}function PQ(t){return new Promise((e,n)=>{t.onsuccess=function(r){e(r)},t.onerror=function(){n(t.error)}})}function cbe(t){return new Promise((e,n)=>{t.onsuccess=()=>e(t),t.onerror=r=>n(r)})}function Fk(t){return PQ(t).then(e=>t.result)}class _B{static exists(e,n){return n="matrix-js-sdk:"+(n||"default"),xQ(e,n)}constructor(e){var n=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:"+n,this.syncAccumulator=new RQ}connect(e){var n=this;if(!this.disconnected)return M.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,M.log("LocalIndexedDBStoreBackend.connect: connecting...");var r=this.indexedDB.open(this.dbName,abe);return r.onupgradeneeded=i=>{var s=r.result,o=i.oldVersion;M.log("LocalIndexedDBStoreBackend.connect: upgrading from ".concat(o)),o<1&&(this._isNewlyCreated=!0),AQ.forEach((a,c)=>{o<=c&&a(s)})},r.onblocked=()=>{M.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},M.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),PQ(r).then(B(function*(){M.log("LocalIndexedDBStoreBackend.connect: connected"),n.db=r.result,n.db.onversionchange=()=>{var i;(i=n.db)===null||i===void 0||i.close(),n.disconnected=!0,n.db=void 0},n.db.onclose=()=>{n.disconnected=!0,n.db=void 0,e?.()},yield n.init()}))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then(e=>{var[n,r]=e;M.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:r.nextBatch,rooms:r.roomsData,account_data:{events:n}},!0)})}getOutOfBandMembers(e){return new Promise((n,r)=>{var i=this.db.transaction(["oob_membership_events"],"readonly"),s=i.objectStore("oob_membership_events"),o=s.index("room"),a=IDBKeyRange.only(e),c=o.openCursor(a),l=[],d=!1;c.onsuccess=()=>{var h=c.result;if(!h)return!l.length&&!d?n(null):n(l);var m=h.value;m.oob_written?d=!0:l.push(m),h.continue()},c.onerror=h=>{r(h)}}).then(n=>(M.log("LL: got ".concat(n?.length," membershipEvents from storage for room ").concat(e," ...")),n))}setOutOfBandMembers(e,n){var r=this;return B(function*(){M.log("LL: backend about to store ".concat(n.length)+" members for ".concat(e));var i=r.db.transaction(["oob_membership_events"],"readwrite"),s=i.objectStore("oob_membership_events");n.forEach(a=>{s.put(a)});var o={room_id:e,oob_written:!0,state_key:0};s.put(o),yield mh(i),M.log("LL: backend done storing for ".concat(e,"!"))})()}clearOutOfBandMembers(e){var n=this;return B(function*(){var r=n.db.transaction(["oob_membership_events"],"readonly"),i=r.objectStore("oob_membership_events"),s=i.index("room"),o=IDBKeyRange.only(e),a=Fk(s.openKeyCursor(o,"next")).then(y=>(y?.primaryKey)[1]),c=Fk(s.openKeyCursor(o,"prev")).then(y=>(y?.primaryKey)[1]),[l,d]=yield Promise.all([a,c]),h=n.db.transaction(["oob_membership_events"],"readwrite"),m=h.objectStore("oob_membership_events"),g=IDBKeyRange.bound([e,l],[e,d]);M.log("LL: Deleting all users + marker in storage for room ".concat(e,", with key range:"),[e,l],[e,d]),yield cbe(m.delete(g))})()}clearDatabase(){return new Promise(e=>{var n;M.log("Removing indexeddb instance: ".concat(this.dbName)),(n=this.db)===null||n===void 0||n.close();var r=this.indexedDB.deleteDatabase(this.dbName);r.onblocked=()=>{M.log("can't yet delete indexeddb ".concat(this.dbName," because it is open elsewhere"))},r.onerror=()=>{var i;M.warn("unable to delete js-sdk store indexeddb: ".concat((i=r.error)===null||i===void 0?void 0:i.name)),e()},r.onsuccess=()=>{M.log("Removed indexeddb instance: ".concat(this.dbName)),e()}})}getSavedSync(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=this.syncAccumulator.getJSON();return n.nextBatch?e?Promise.resolve(d_(n)):Promise.resolve(n):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then(()=>{this.syncAccumulator.accumulate(e)})}syncToDatabase(e){var n=this;return B(function*(){return n.syncToDatabasePromise?(M.warn("Skipping syncToDatabase() as persist already in flight"),n.pendingUserPresenceData.push(...e),n.syncToDatabasePromise):(e.unshift(...n.pendingUserPresenceData),n.syncToDatabasePromise=n.doSyncToDatabase(e),n.syncToDatabasePromise)})()}doSyncToDatabase(e){var n=this;return B(function*(){try{var r=n.syncAccumulator.getJSON(!0);yield Promise.all([n.persistUserPresenceEvents(e),n.persistAccountData(r.accountData),n.persistSyncData(r.nextBatch,r.roomsData)])}finally{n.syncToDatabasePromise=void 0}})()}persistSyncData(e,n){return M.log("Persisting sync data up to",e),km(()=>{var r=this.db.transaction(["sync"],"readwrite"),i=r.objectStore("sync");return i.put({clobber:"-",nextBatch:e,roomsData:n}),mh(r).then(()=>{M.log("Persisted sync data up to",e)})})}persistAccountData(e){return km(()=>{var n=this.db.transaction(["accountData"],"readwrite"),r=n.objectStore("accountData");for(var i of e)r.put(i);return mh(n).then()})}persistUserPresenceEvents(e){return km(()=>{var n=this.db.transaction(["users"],"readwrite"),r=n.objectStore("users");for(var i of e)r.put({userId:i[0],event:i[1]});return mh(n).then()})}getUserPresenceEvents(){return km(()=>{var e=this.db.transaction(["users"],"readonly"),n=e.objectStore("users");return M2(n,void 0,r=>[r.value.userId,r.value.event])})}loadAccountData(){return M.log("LocalIndexedDBStoreBackend: loading account data..."),km(()=>{var e=this.db.transaction(["accountData"],"readonly"),n=e.objectStore("accountData");return M2(n,void 0,r=>r.value).then(r=>(M.log("LocalIndexedDBStoreBackend: loaded account data"),r))})}loadSyncData(){return M.log("LocalIndexedDBStoreBackend: loading sync data..."),km(()=>{var e=this.db.transaction(["sync"],"readonly"),n=e.objectStore("sync");return M2(n,void 0,r=>r.value).then(r=>(M.log("LocalIndexedDBStoreBackend: loaded sync data"),r.length>1&&M.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"),n=e.objectStore("client_options");return M2(n,void 0,r=>{var i;return(i=r.value)===null||i===void 0?void 0:i.options}).then(r=>r[0])})}storeClientOptions(e){var n=this;return B(function*(){var r=n.db.transaction(["client_options"],"readwrite"),i=r.objectStore("client_options");i.put({clobber:"-",options:e}),yield mh(r)})()}saveToDeviceBatches(e){var n=this;return B(function*(){var r=n.db.transaction(["to_device_queue"],"readwrite"),i=r.objectStore("to_device_queue");for(var s of e)i.add(s);yield mh(r)})()}getOldestToDeviceBatch(){var e=this;return B(function*(){var n=e.db.transaction(["to_device_queue"],"readonly"),r=n.objectStore("to_device_queue"),i=yield Fk(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 n=this;return B(function*(){var r=n.db.transaction(["to_device_queue"],"readwrite"),i=r.objectStore("to_device_queue");i.delete(e),yield mh(r)})()}destroy(){var e=this;return B(function*(){var n;(n=e.db)===null||n===void 0||n.close()})()}}class lbe{constructor(e,n){this.workerFactory=e,this.dbName=n,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){M.error("Got reply from worker with no seq");return}var o=this.inFlight[i.seq];if(o===void 0){M.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 M.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,n){return this.doCmd("setOutOfBandMembers",[e,n])}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 n=this;return B(function*(){return n.doCmd("saveToDeviceBatches",[e])})()}getOldestToDeviceBatch(){var e=this;return B(function*(){return e.doCmd("getOldestToDeviceBatch")})()}removeToDeviceBatch(e){var n=this;return B(function*(){return n.doCmd("removeToDeviceBatch",[e])})()}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then(()=>{M.log("IndexedDB worker is ready")})),this.startPromise}doCmd(e,n){return Promise.resolve().then(()=>{var r,i=this.nextSeq++,s=Promise.withResolvers();return this.inFlight[i]=s,(r=this.worker)===null||r===void 0||r.postMessage({command:e,seq:i,args:n}),s.promise})}destroy(){var e=this;return B(function*(){var n;(n=e.worker)===null||n===void 0||n.terminate()})()}}var ube=1e3*60*5;class LQ extends vb{static exists(e,n){return _B.exists(e,n)}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 On),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(()=>{M.log("Deleted indexeddb data.")},n=>{throw M.error("Failed to delete indexeddb data: ".concat(n)),n})),null)),L(this,"reallySave",this.degradable(()=>{this.syncTs=Date.now();var n=[];for(var r of this.getUsers())this.userModifiedMap[r.userId]!==r.getLastModifiedTime()&&r.events.presence&&(n.push([r.userId,r.events.presence.event]),this.userModifiedMap[r.userId]=r.getLastModifiedTime());return this.backend.syncToDatabase(n)},null)),L(this,"setSyncData",this.degradable(n=>this.backend.setSyncData(n),"setSyncData")),L(this,"getOutOfBandMembers",this.degradable(n=>this.backend.getOutOfBandMembers(n),"getOutOfBandMembers")),L(this,"setOutOfBandMembers",this.degradable((n,r)=>(super.setOutOfBandMembers(n,r),this.backend.setOutOfBandMembers(n,r)),"setOutOfBandMembers")),L(this,"clearOutOfBandMembers",this.degradable(n=>(super.clearOutOfBandMembers(n),this.backend.clearOutOfBandMembers(n)),"clearOutOfBandMembers")),L(this,"getClientOptions",this.degradable(()=>this.backend.getClientOptions(),"getClientOptions")),L(this,"storeClientOptions",this.degradable(n=>(super.storeClientOptions(n),this.backend.storeClientOptions(n)),"storeClientOptions")),!e.indexedDB)throw new Error("Missing required option: indexedDB");e.workerFactory?this.backend=new lbe(e.workerFactory,e.dbName):this.backend=new _B(e.indexedDB,e.dbName)}on(e,n){this.emitter.on(e,n)}startup(){return this.startedUp?(M.log("IndexedDBStore.startup: already started"),Promise.resolve()):(M.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect(this.onClose).then(()=>(M.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents())).then(e=>{M.log("IndexedDBStore.startup: processing presence events"),e.forEach(n=>{var[r,i]=n;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 $i(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>ube}save(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,n){var r=this,i=n?super[n]:null;return B(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(c){M.error("IndexedDBStore failure, degrading to MemoryStore",c),r.emitter.emit("degraded",c);try{M.log("IndexedDBStore trying to delete degraded data"),yield r.backend.clearDatabase(),M.log("IndexedDBStore delete after degrading succeeded")}catch(l){M.warn("IndexedDBStore delete after degrading failed",l)}if(i)return i.call(r,...o)}})}getPendingEvents(e){var n=()=>super.getPendingEvents,r=this;return B(function*(){if(!r.localStorage)return n().call(r,e);var i=r.localStorage.getItem($k(e));if(i)try{return JSON.parse(i)}catch(s){M.error("Could not parse persisted pending events",s)}return[]})()}setPendingEvents(e,n){var r=()=>super.setPendingEvents,i=this;return B(function*(){if(!i.localStorage)return r().call(i,e,n);n.length>0?i.localStorage.setItem($k(e),JSON.stringify(n)):i.localStorage.removeItem($k(e))})()}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function $k(t){return"mx_pending_events_".concat(t)}var rc="crypto.",SB=rc+"migration",Bk=rc+"account",dbe=rc+"cross_signing_keys",ew=rc+"inboundgroupsessions/",fbe=rc+"inboundgroupsessions.withheld/",hbe=rc+"rooms/",Hk=rc+"sessionsneedingbackup";function Mm(t){return rc+"sessions/"+t}function Vk(t,e){return ew+t+"/"+e}function pbe(t,e){return fbe+t+"/"+e}function mbe(t){return hbe+t}class oT extends z3{static exists(e){for(var n=e.length,r=0;r<n;r++){var i;if((i=e.key(r))!==null&&i!==void 0&&i.startsWith(rc))return!0}return!1}constructor(e){super(),this.store=e}containsData(){var e=this;return B(function*(){return oT.exists(e.store)})()}getMigrationState(){var e=this;return B(function*(){var n;return(n=Ko(e.store,SB))!==null&&n!==void 0?n:tv.NOT_STARTED})()}setMigrationState(e){var n=this;return B(function*(){gh(n.store,SB,e)})()}countEndToEndSessions(e,n){for(var r=0,i=0;i<this.store.length;++i){var s=this.store.key(i);if(s!=null&&s.startsWith(Mm(""))){var o=Ko(this.store,s);r+=Object.keys(o??{}).length}}n(r)}_getEndToEndSessions(e){var n=Ko(this.store,Mm(e)),r={};for(var[i,s]of Object.entries(n||{}))typeof s=="string"?r[i]={session:s}:r[i]=s;return r}getEndToEndSession(e,n,r,i){var s,o=this._getEndToEndSessions(e);i((s=o[n])!==null&&s!==void 0?s:{})}getEndToEndSessions(e,n,r){var i;r((i=this._getEndToEndSessions(e))!==null&&i!==void 0?i:{})}storeEndToEndSession(e,n,r,i){var s=this._getEndToEndSessions(e)||{};s[n]=r,gh(this.store,Mm(e),s)}getEndToEndSessionsBatch(){var e=this;return B(function*(){for(var n=[],r=0;r<e.store.length;++r){var i;if((i=e.store.key(r))!==null&&i!==void 0&&i.startsWith(Mm(""))){var s=e.store.key(r).split("/")[1];for(var o of Object.values(e._getEndToEndSessions(s)))if(n.push(o),n.length>=nv)return n}}return n.length===0?null:n})()}deleteEndToEndSessionsBatch(e){var n=this;return B(function*(){for(var{deviceKey:r,sessionId:i}of e){var s=n._getEndToEndSessions(r)||{};delete s[i],Object.keys(s).length===0?n.store.removeItem(Mm(r)):gh(n.store,Mm(r),s)}})()}getEndToEndInboundGroupSession(e,n,r,i){i(Ko(this.store,Vk(e,n)),Ko(this.store,pbe(e,n)))}storeEndToEndInboundGroupSession(e,n,r,i){gh(this.store,Vk(e,n),r)}countEndToEndInboundGroupSessions(){var e=this;return B(function*(){for(var n=0,r=0;r<e.store.length;++r){var i=e.store.key(r);i!=null&&i.startsWith(ew)&&(n+=1)}return n})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return B(function*(){for(var n=Ko(e.store,Hk)||{},r=[],i=0;i<e.store.length;++i){var s=e.store.key(i);if(s!=null&&s.startsWith(ew)){var o=s.slice(ew.length);if(r.push({senderKey:o.slice(0,43),sessionId:o.slice(44),sessionData:Ko(e.store,s),needsBackup:o in n}),r.length>=nv)return r}}return r.length===0?null:r})()}deleteEndToEndInboundGroupSessionsBatch(e){var n=this;return B(function*(){for(var{senderKey:r,sessionId:i}of e){var s=Vk(r,i);n.store.removeItem(s)}})()}getEndToEndRooms(e,n){for(var r={},i=mbe(""),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]=Ko(this.store,o)}}n(r)}markSessionsNeedingBackup(e){var n=Ko(this.store,Hk)||{};for(var r of e)n[r.senderKey+"/"+r.sessionId]=!0;return gh(this.store,Hk,n),Promise.resolve()}deleteAllData(){return this.store.removeItem(Bk),Promise.resolve()}getAccount(e,n){var r=Ko(this.store,Bk);n(r)}storeAccount(e,n){gh(this.store,Bk,n)}getCrossSigningKeys(e,n){var r=Ko(this.store,dbe);n(r)}getSecretStorePrivateKey(e,n,r){var i=Ko(this.store,rc+"ssss_cache.".concat(r));n(i)}storeSecretStorePrivateKey(e,n,r){gh(this.store,rc+"ssss_cache.".concat(n),r)}doTxn(e,n,r){return Promise.resolve(r(null))}}function Ko(t,e){try{return JSON.parse(t.getItem(e))}catch(n){M.log("Error: Failed to get key %s: %s",e,n.message),M.log(n.stack)}return null}function gh(t,e,n){t.setItem(e,JSON.stringify(n))}let gbe=class{constructor(e){this.db=e,L(this,"nextTxnId",0),e.onversionchange=()=>{M.log("versionchange for indexeddb ".concat(this.db.name,": closing")),e.close()}}containsData(){return B(function*(){throw Error("Not implemented for Backend")})()}startup(){var e=this;return B(function*(){return e})()}deleteAllData(){return B(function*(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")})()}getMigrationState(){var e=this;return B(function*(){var n=tv.NOT_STARTED;return yield e.doTxn("readonly",[qt.STORE_ACCOUNT],r=>{var i=r.objectStore(qt.STORE_ACCOUNT),s=i.get(G5);s.onsuccess=()=>{var o;n=(o=s.result)!==null&&o!==void 0?o:tv.NOT_STARTED}}),n})()}setMigrationState(e){var n=this;return B(function*(){yield n.doTxn("readwrite",[qt.STORE_ACCOUNT],r=>{var i=r.objectStore(qt.STORE_ACCOUNT);i.put(e,G5)})})()}getAccount(e,n){var r=e.objectStore("account"),i=r.get("-");i.onsuccess=function(){try{n(i.result||null)}catch(s){Os(e,s)}}}storeAccount(e,n){var r=e.objectStore("account");r.put(n,"-")}getCrossSigningKeys(e,n){var r=e.objectStore("account"),i=r.get("crossSigningKeys");i.onsuccess=function(){try{n(i.result||null)}catch(s){Os(e,s)}}}getSecretStorePrivateKey(e,n,r){var i=e.objectStore("account"),s=i.get("ssss_cache:".concat(r));s.onsuccess=function(){try{n(s.result||null)}catch(o){Os(e,o)}}}storeSecretStorePrivateKey(e,n,r){var i=e.objectStore("account");i.put(r,"ssss_cache:".concat(n))}countEndToEndSessions(e,n){var r=e.objectStore("sessions"),i=r.count();i.onsuccess=function(){try{n(i.result)}catch(s){Os(e,s)}}}getEndToEndSessions(e,n,r){var i=n.objectStore("sessions"),s=i.index("deviceKey"),o=s.openCursor(e),a={};o.onsuccess=function(){var c=o.result;if(c)a[c.value.sessionId]={session:c.value.session,lastReceivedMessageTs:c.value.lastReceivedMessageTs},c.continue();else try{r(a)}catch(l){Os(n,l)}}}getEndToEndSession(e,n,r,i){var s=r.objectStore("sessions"),o=s.get([e,n]);o.onsuccess=function(){try{o.result?i({session:o.result.session,lastReceivedMessageTs:o.result.lastReceivedMessageTs}):i(null)}catch(a){Os(r,a)}}}storeEndToEndSession(e,n,r,i){var s=i.objectStore("sessions");s.put({deviceKey:e,sessionId:n,session:r.session,lastReceivedMessageTs:r.lastReceivedMessageTs})}getEndToEndSessionsBatch(){var e=this;return B(function*(){var n=[];return yield e.doTxn("readonly",[qt.STORE_SESSIONS],r=>{var i=r.objectStore(qt.STORE_SESSIONS),s=i.openCursor();s.onsuccess=function(){try{var o=s.result;o&&(n.push(o.value),n.length<nv&&o.continue())}catch(a){Os(r,a)}}}),n.length===0?null:n})()}deleteEndToEndSessionsBatch(e){var n=this;return B(function*(){yield n.doTxn("readwrite",[qt.STORE_SESSIONS],function(){var r=B(function*(i){try{var s=i.objectStore(qt.STORE_SESSIONS),o=function*(){var d=s.delete([a,c]);yield new Promise(h=>{d.onsuccess=h})};for(var{deviceKey:a,sessionId:c}of e)yield*o()}catch(l){Os(i,l)}});return function(i){return r.apply(this,arguments)}}())})()}getEndToEndInboundGroupSession(e,n,r,i){var s=!1,o=!1,a=r.objectStore("inbound_group_sessions"),c=a.get([e,n]);c.onsuccess=function(){try{c.result?s=c.result.session:s=null,o!==!1&&i(s,o)}catch(h){Os(r,h)}};var l=r.objectStore("inbound_group_sessions_withheld"),d=l.get([e,n]);d.onsuccess=function(){try{d.result?o=d.result.session:o=null,s!==!1&&i(s,o)}catch(h){Os(r,h)}}}storeEndToEndInboundGroupSession(e,n,r,i){var s=i.objectStore("inbound_group_sessions");s.put({senderCurve25519Key:e,sessionId:n,session:r})}countEndToEndInboundGroupSessions(){var e=this;return B(function*(){var n=0;return yield e.doTxn("readonly",[qt.STORE_INBOUND_GROUP_SESSIONS],r=>{var i=r.objectStore(qt.STORE_INBOUND_GROUP_SESSIONS),s=i.count();s.onsuccess=()=>{n=s.result}}),n})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return B(function*(){var n=[];return yield e.doTxn("readonly",[qt.STORE_INBOUND_GROUP_SESSIONS,qt.STORE_BACKUP],r=>{var i=r.objectStore(qt.STORE_INBOUND_GROUP_SESSIONS),s=r.objectStore(qt.STORE_BACKUP),o=i.openCursor();o.onsuccess=function(){try{var a=o.result;if(a){var c=s.get(a.key);c.onsuccess=()=>{n.push({senderKey:a.value.senderCurve25519Key,sessionId:a.value.sessionId,sessionData:a.value.session,needsBackup:c.result!==void 0}),n.length<nv&&a.continue()}}}catch(l){Os(r,l)}}}),n.length===0?null:n})()}deleteEndToEndInboundGroupSessionsBatch(e){var n=this;return B(function*(){yield n.doTxn("readwrite",[qt.STORE_INBOUND_GROUP_SESSIONS],function(){var r=B(function*(i){try{var s=i.objectStore(qt.STORE_INBOUND_GROUP_SESSIONS),o=function*(){var d=s.delete([a,c]);yield new Promise(h=>{d.onsuccess=h})};for(var{senderKey:a,sessionId:c}of e)yield*o()}catch(l){Os(i,l)}});return function(i){return r.apply(this,arguments)}}())})()}getEndToEndDeviceData(e,n){var r=e.objectStore("device_data"),i=r.get("-");i.onsuccess=function(){try{n(i.result||null)}catch(s){Os(e,s)}}}getEndToEndRooms(e,n){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{n(r)}catch(a){Os(e,a)}}}markSessionsNeedingBackup(e,n){var r=this;return B(function*(){n||(n=r.db.transaction("sessions_needing_backup","readwrite"));var i=n.objectStore("sessions_needing_backup");yield Promise.all(e.map(s=>new Promise((o,a)=>{var c=i.put({senderCurve25519Key:s.senderKey,sessionId:s.sessionId});c.onsuccess=o,c.onerror=a})))})()}doTxn(e,n,r){var i=this.db.transaction(n,e),s=bbe(i),o=r(i);return s.then(()=>o)}};var OQ=[t=>{ybe(t)},t=>{t.createObjectStore("account")},t=>{var e=t.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]});e.createIndex("deviceKey","deviceKey")},t=>{t.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},t=>{t.createObjectStore("device_data")},t=>{t.createObjectStore("rooms")},t=>{t.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},t=>{t.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},t=>{var e=t.createObjectStore("session_problems",{keyPath:["deviceKey","time"]});e.createIndex("deviceKey","deviceKey"),t.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},t=>{t.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},t=>{t.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}],MQ=OQ.length;function vbe(t,e){M.log("Upgrading IndexedDBCryptoStore from version ".concat(e)+" to ".concat(MQ)),OQ.forEach((n,r)=>{e<=r&&n(t)})}function ybe(t){var e=t.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});e.createIndex("session",["requestBody.room_id","requestBody.session_id"]),e.createIndex("state","state")}function Os(t,e){t._mx_abortexception=e;try{t.abort()}catch{}}function bbe(t){return new Promise((e,n)=>{t.oncomplete=()=>{t._mx_abortexception!==void 0&&n(t._mx_abortexception),e(null)},t.onerror=r=>{t._mx_abortexception!==void 0?n(t._mx_abortexception):(M.log("Error performing indexeddb txn",r),n(t.error))},t.onabort=r=>{t._mx_abortexception!==void 0?n(t._mx_abortexception):(M.log("Error performing indexeddb txn",r),n(t.error))}})}class qt{static exists(e,n){return xQ(e,n)}static existsAndIsNotMigrated(e,n){return new Promise((r,i)=>{var s=!0,o=e.open(n);o.onupgradeneeded=()=>{s=!1},o.onblocked=()=>i(o.error),o.onsuccess=()=>{var a=o.result;if(!s)a.close(),e.deleteDatabase(n),r(!1);else{var c=a.transaction([qt.STORE_ACCOUNT],"readonly"),l=c.objectStore(qt.STORE_ACCOUNT),d=l.get(G5);d.onsuccess=()=>{var h,m=(h=d.result)!==null&&h!==void 0?h:tv.NOT_STARTED;r(m===tv.NOT_STARTED)},d.onerror=()=>{i(d.error)},a.close()}},o.onerror=()=>i(o.error)})}constructor(e,n){this.indexedDB=e,this.dbName=n,L(this,"backendPromise",void 0),L(this,"backend",void 0)}containsData(){var e=this;return B(function*(){return qt.exists(e.indexedDB,e.dbName)})()}startup(){return this.backendPromise?this.backendPromise:(this.backendPromise=new Promise((e,n)=>{if(!this.indexedDB){n(new Error("no indexeddb support available"));return}M.log("connecting to indexeddb ".concat(this.dbName));var r=this.indexedDB.open(this.dbName,MQ);r.onupgradeneeded=i=>{var s=r.result,o=i.oldVersion;vbe(s,o)},r.onblocked=()=>{M.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{M.log("Error connecting to indexeddb",i),n(r.error)},r.onsuccess=()=>{var i=r.result;M.log("connected to indexeddb ".concat(this.dbName)),e(new gbe(i))}}).then(e=>e.doTxn("readonly",[qt.STORE_INBOUND_GROUP_SESSIONS,qt.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],n=>{e.getEndToEndInboundGroupSession("","",n,()=>{})}).then(()=>e)).catch(e=>{if(e.name==="VersionError")throw M.warn("Crypto DB is too new for us to use!",e),new t7(e7.TooNew);M.warn("unable to connect to indexeddb ".concat(this.dbName)+": falling back to localStorage store: ".concat(e));try{if(!(globalThis.localStorage instanceof Storage))throw new Error("localStorage is not available");return new oT(globalThis.localStorage)}catch(n){return M.warn("Unable to open localStorage: falling back to in-memory store: ".concat(n)),new z3}}).then(e=>(this.backend=e,e)),this.backendPromise)}deleteAllData(){return new Promise((e,n)=>{if(!this.indexedDB){n(new Error("no indexeddb support available"));return}M.log("Removing indexeddb instance: ".concat(this.dbName));var r=this.indexedDB.deleteDatabase(this.dbName);r.onblocked=()=>{M.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},r.onerror=i=>{M.log("Error deleting data from indexeddb",i),n(r.error)},r.onsuccess=()=>{M.log("Removed indexeddb instance: ".concat(this.dbName)),e()}}).catch(e=>{M.warn("unable to delete IndexedDBCryptoStore: ".concat(e))})}getMigrationState(){return this.backend.getMigrationState()}setMigrationState(e){return this.backend.setMigrationState(e)}getAccount(e,n){this.backend.getAccount(e,n)}storeAccount(e,n){this.backend.storeAccount(e,n)}getCrossSigningKeys(e,n){this.backend.getCrossSigningKeys(e,n)}getSecretStorePrivateKey(e,n,r){this.backend.getSecretStorePrivateKey(e,n,r)}storeSecretStorePrivateKey(e,n,r){this.backend.storeSecretStorePrivateKey(e,n,r)}countEndToEndSessions(e,n){this.backend.countEndToEndSessions(e,n)}getEndToEndSession(e,n,r,i){this.backend.getEndToEndSession(e,n,r,i)}getEndToEndSessions(e,n,r){this.backend.getEndToEndSessions(e,n,r)}storeEndToEndSession(e,n,r,i){this.backend.storeEndToEndSession(e,n,r,i)}countEndToEndInboundGroupSessions(){return this.backend.countEndToEndInboundGroupSessions()}getEndToEndSessionsBatch(){return this.backend.getEndToEndSessionsBatch()}deleteEndToEndSessionsBatch(e){return this.backend.deleteEndToEndSessionsBatch(e)}getEndToEndInboundGroupSession(e,n,r,i){this.backend.getEndToEndInboundGroupSession(e,n,r,i)}storeEndToEndInboundGroupSession(e,n,r,i){this.backend.storeEndToEndInboundGroupSession(e,n,r,i)}getEndToEndInboundGroupSessionsBatch(){return this.backend.getEndToEndInboundGroupSessionsBatch()}deleteEndToEndInboundGroupSessionsBatch(e){return this.backend.deleteEndToEndInboundGroupSessionsBatch(e)}getEndToEndRooms(e,n){this.backend.getEndToEndRooms(e,n)}markSessionsNeedingBackup(e,n){return this.backend.markSessionsNeedingBackup(e,n)}doTxn(e,n,r,i){return this.backend.doTxn(e,n,r,i)}}L(qt,"STORE_ACCOUNT","account");L(qt,"STORE_SESSIONS","sessions");L(qt,"STORE_INBOUND_GROUP_SESSIONS","inbound_group_sessions");L(qt,"STORE_INBOUND_GROUP_SESSIONS_WITHHELD","inbound_group_sessions_withheld");L(qt,"STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","shared_history_inbound_group_sessions");L(qt,"STORE_PARKED_SHARED_HISTORY","parked_shared_history");L(qt,"STORE_DEVICE_DATA","device_data");L(qt,"STORE_ROOMS","rooms");L(qt,"STORE_BACKUP","sessions_needing_backup");var _be=function(t){return t.Email="email",t.Phone="msisdn",t}({}),Sbe=new Ar("delegated_oidc_compatibility","org.matrix.msc3824.delegated_oidc_compatibility"),Ebe=function(t){return t.Gitlab="gitlab",t.Github="github",t.Apple="apple",t.Google="google",t.Facebook="facebook",t.Twitter="twitter",t}({}),wbe=function(t){return t.LOGIN="login",t.REGISTER="register",t}({}),Cbe="us.cloke.msc4175.tz";class Tbe{constructor(e){L(this,"relations",void 0),this.relations=e.filter(n=>!!n)}getRelations(){return this.relations.reduce((e,n)=>[...e,...n.getRelations()],[])}on(e,n){this.relations.forEach(r=>r.on(e,n))}off(e,n){this.relations.forEach(r=>r.off(e,n))}}var Rbe=function(t){return t.Global="Global",t.SetItemError="setItem",t.GetItemError="getItem",t.RemoveItemError="removeItem",t.ClearError="clear",t.QuotaExceededError="QuotaExceededError",t}({});class Ibe extends On{}var kbe=new Ibe,DQ=()=>new z3;function NQ(t){DQ=t}function UQ(t){var e,n,r;return t.store=(e=t.store)!==null&&e!==void 0?e:new vb({localStorage:globalThis.localStorage}),t.scheduler=(n=t.scheduler)!==null&&n!==void 0?n:new rv,t.cryptoStore=(r=t.cryptoStore)!==null&&r!==void 0?r:DQ(),t}function aT(t){return new sT(UQ(t))}function jQ(t,e,n,r){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;return new TQ(t,e,n,UQ(r),i)}const xbe=Object.freeze(Object.defineProperty({__proto__:null,AuthType:kA,AutoDiscovery:lt,AutoDiscoveryAction:So,AutoDiscoveryError:Ia,Beacon:EJ,BeaconEvent:qn,CallEvent:gt,CallFeedEvent:Lc,Category:Bl,ClientEvent:Le,ClientPrefix:Xr,ClientStoppedError:eye,ConditionKind:Ur,ConditionOperator:S1e,ConnectionError:wp,ContentHelpers:Zve,DELEGATED_OIDC_COMPATIBILITY:Sbe,DEVICE_CODE_SCOPE:Uye,DMMemberCountCondition:E1e,DebugLogger:MO,Device:ibe,DeviceVerification:IQ,Direction:ht,DuplicateStrategy:wy,EVENT_VISIBILITY_CHANGE_TYPE:Dh,EventEmitterEvents:WX,EventStatus:rt,EventTimeline:Me,EventTimelineSet:ag,EventType:Z,FILTER_RELATED_BY_REL_TYPES:kg,FILTER_RELATED_BY_SENDERS:Ig,FeatureSupport:Zi,Filter:Us,GET_LOGIN_TOKEN_CAPABILITY:Vye,GroupCall:YO,GroupCallEvent:kn,GroupCallIntent:VJ,GroupCallState:sr,GroupCallStatsReportEvent:uy,GroupCallType:eT,GuestAccess:dC,HTTPError:ep,HistoryVisibility:QO,HttpApiEvent:tA,IdentityPrefix:$l,IdentityProviderBrand:Ebe,IndexedDBCryptoStore:qt,IndexedDBStore:LQ,InteractiveAuth:l7,InvalidCryptoStoreError:t7,InvalidCryptoStoreState:e7,JoinRule:ef,KNOWN_SAFE_ROOM_VERSION:MJ,KeySignatureUploadError:Z1e,KnownMembership:Be,LOCAL_NOTIFICATION_SETTINGS_PREFIX:QX,LocalStorageCryptoStore:oT,LocalStorageErrors:Rbe,LocationAssetType:ev,MAIN_ROOM_TIMELINE:u_,MAXIMUM_MATRIX_VERSION:x1e,MINIMUM_MATRIX_VERSION:k1e,MSC3912_RELATION_BASED_REDACTIONS_PROP:X5,M_ASSET:c_,M_BEACON:pA,M_BEACON_INFO:ZO,M_HTML:Kve,M_LOCATION:l_,M_MESSAGE:Gve,M_POLL_END:lC,M_POLL_KIND_DISCLOSED:t0e,M_POLL_KIND_UNDISCLOSED:n0e,M_POLL_RESPONSE:db,M_POLL_START:r0e,M_TEXT:FO,M_TIMESTAMP:Lf,M_TOPIC:$O,MatrixClient:sT,MatrixError:tr,MatrixEvent:$i,MatrixEventEvent:Kt,MatrixHttpApi:PJ,MatrixScheduler:rv,MediaHandlerEvent:Rh,MediaPrefix:Cg,MemoryCryptoStore:z3,MemoryStore:vb,Method:de,MsgType:ll,NoAuthFlowFoundError:kQ,NotificationCountType:Jt,OidcError:ts,OidcTokenRefresher:Fye,PUSHER_DEVICE_ID:Ave,PUSHER_ENABLED:J5,PendingEventOrdering:sv,Poll:TJ,PollEvent:Md,Preset:nT,ProfileKeyMSC4175Timezone:Cbe,PushRuleActionName:Zd,PushRuleKind:wi,REFERENCE_RELATION:dJ,ReceiptType:ls,RelatedRelations:Tbe,RelationType:vn,Relations:jO,RelationsEvent:KE,RestrictedAllowType:P1e,Room:Q3,RoomCreateTypeField:sC,RoomEvent:ke,RoomMember:cb,RoomMemberEvent:Vs,RoomNameType:Pc,RoomState:gb,RoomStateEvent:pt,RoomSummary:lJ,RoomType:wg,RoomVersionStability:LJ,RoomWidgetClient:TQ,RoomWidgetClientEvent:ZE,RuleId:Ei,SERVICE_TYPES:fA,SSOAction:wbe,STABLE_MSC4133_EXTENDED_PROFILES:bQ,SUPPORTED_MATRIX_VERSIONS:hb,SearchOrderBy:KJ,SearchResult:tT,SecretStorage:J1e,ServerCapabilities:OJ,SetPresence:DJ,SlidingSyncEvent:hA,StatsReport:pu,SyncAccumulator:RQ,SyncState:Gt,THREAD_RELATION_TYPE:wn,Thread:Un,ThreadEvent:us,ThreadFilterType:Ba,ThreepidMedium:_be,TimelineIndex:IA,TimelineWindow:obe,ToDeviceMessageId:X3,TokenRefreshError:xJ,TokenRefreshLogoutError:VO,TweakName:XO,TypedEventEmitter:On,UNSIGNED_MEMBERSHIP_FIELD:ZX,UNSIGNED_THREAD_ID_FIELD:oC,UNSTABLE_ELEMENT_FUNCTIONAL_USERS:JX,UNSTABLE_MSC2666_MUTUAL_ROOMS:gQ,UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS:vQ,UNSTABLE_MSC2666_SHARED_ROOMS:mQ,UNSTABLE_MSC2716_MARKER:XX,UNSTABLE_MSC3088_ENABLED:W5,UNSTABLE_MSC3088_PURPOSE:z5,UNSTABLE_MSC3089_BRANCH:ru,UNSTABLE_MSC3089_LEAF:YX,UNSTABLE_MSC3089_TREE_SUBTYPE:Y5,UNSTABLE_MSC3852_LAST_SEEN_UA:Hye,UNSTABLE_MSC4133_EXTENDED_PROFILES:yQ,UNSTABLE_MSC4140_DELAYED_EVENTS:Vc,UnsupportedDelayedEventsEndpointError:Gd,UpdateDelayedEventAction:zE,User:yu,UserEvent:Ui,Visibility:GJ,anySignal:AJ,calculateRetryBackoff:GO,completeAuthorizationCodeGrant:Nye,createClient:aT,createNewMatrixCall:fb,createRoomWidgetClient:jQ,decodeBase64:Bh,decodeIdToken:dQ,determineFeatureSupport:JE,discoverAndValidateOIDCIssuerWellKnown:a7,encodeBase64:Cy,encodeUnpaddedBase64:$J,encodeUnpaddedBase64Url:Z3,fixNotificationCountOnDecryption:_Q,generateAuthorizationParams:Lye,generateAuthorizationUrl:Oye,generateOidcAuthorizationUrl:Mye,generateScope:iT,getBeaconInfoIdentifier:cC,getHttpUriForMxc:W3,inMainTimelineForReceipt:mb,isDmMemberCountCondition:w1e,isEventTypeSame:zve,isPollEvent:RJ,isTimestampInDuration:Z5,localStorageErrorsEventsEmitter:kbe,parseErrorResponse:qO,registerOidcClient:jye,retryNetworkOperation:nA,safeGetRetryAfterMs:HO,setCryptoStoreFactory:NQ,threadFilterTypeToFilter:SQ,threadIdForReceipt:ov,timeoutSignal:J3,validateAuthMetadata:uQ,validateAuthMetadataAndKeys:c7,validateBearerTokenResponse:pQ,validateIdToken:fQ,validateStoredUserState:hQ},Symbol.toStringTag,{value:"Module"}));if(globalThis.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");globalThis.__js_sdk_entrypoint=!0;var xA;try{xA=globalThis.indexedDB}catch{}xA&&NQ(()=>new qt(xA,"matrix-js-sdk:crypto"));globalThis.matrixcs=xbe;var qk={exports:{}},bt={};/**
27
27
  * @license React
28
28
  * react.production.js
@@ -210,7 +210,7 @@ total: ${r}ms
210
210
  peerConnection: ${i}ms
211
211
  websocket: ${s}ms`)}}function Rn(t){return typeof t=="function"}function rle(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Nx=rle(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
212
212
  `+n.map(function(r,i){return i+1+") "+r.toString()}).join(`
213
- `):"",this.name="UnsubscriptionError",this.errors=n}});function y3(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var j_=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,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=Ef(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(v){e={error:v}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else o.remove(this);var d=this.initialTeardown;if(Rn(d))try{d()}catch(v){s=v instanceof Nx?v.errors:[v]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var m=Ef(h),g=m.next();!g.done;g=m.next()){var y=g.value;try{$K(y)}catch(v){s=s??[],v instanceof Nx?s=Ea(Ea([],Sa(s)),Sa(v.errors)):s.push(v)}}}catch(v){r={error:v}}finally{try{g&&!g.done&&(i=m.return)&&i.call(m)}finally{if(r)throw r.error}}}if(s)throw new Nx(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)$K(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&y3(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&y3(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),ile=j_.EMPTY;function sle(t){return t instanceof j_||t&&"closed"in t&&Rn(t.remove)&&Rn(t.add)&&Rn(t.unsubscribe)}function $K(t){Rn(t)?t():t.unsubscribe()}var iqe={Promise:void 0},sqe={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,Ea([t,e],Sa(n)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function ole(t){sqe.setTimeout(function(){throw t})}function wv(){}function Nw(t){t()}var M8=function(t){cc(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,sle(n)&&n.add(r)):r.destination=cqe,r}return e.create=function(n,r,i){return new FL(n,r,i)},e.prototype.next=function(n){this.isStopped||this._next(n)},e.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(j_),oqe=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){yE(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){yE(r)}else yE(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){yE(n)}},t}(),FL=function(t){cc(e,t);function e(n,r,i){var s=t.call(this)||this,o;return Rn(n)||!n?o={next:n??void 0,error:r??void 0,complete:i??void 0}:o=n,s.destination=new oqe(o),s}return e}(M8);function yE(t){ole(t)}function aqe(t){throw t}var cqe={closed:!0,next:wv,error:aqe,complete:wv},D8=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function $f(t){return t}function lqe(t){return t.length===0?$f:t.length===1?t[0]:function(n){return t.reduce(function(r,i){return i(r)},n)}}var Wn=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var i=this,s=dqe(e)?e:new FL(e,n,r);return Nw(function(){var o=i,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?i._subscribe(s):i._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=BK(n),new n(function(i,s){var o=new FL({next:function(a){try{e(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[D8]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return lqe(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=BK(e),new e(function(r,i){var s;n.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},t.create=function(e){return new t(e)},t}();function BK(t){var e;return(e=t??iqe.Promise)!==null&&e!==void 0?e:Promise}function uqe(t){return t&&Rn(t.next)&&Rn(t.error)&&Rn(t.complete)}function dqe(t){return t&&t instanceof M8||uqe(t)&&sle(t)}function fqe(t){return Rn(t?.lift)}function Lr(t){return function(e){if(fqe(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Yn(t,e,n,r,i){return new hqe(t,e,n,r,i)}var hqe=function(t){cc(e,t);function e(n,r,i,s,o,a){var c=t.call(this,n)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(l){try{r(l)}catch(d){n.error(d)}}:t.prototype._next,c._error=s?function(l){try{s(l)}catch(d){n.error(d)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=i?function(){try{i()}catch(l){n.error(l)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e}(M8),pqe=rle(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ii=function(t){cc(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new HK(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new pqe},e.prototype.next=function(n){var r=this;Nw(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=Ef(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(n)}}catch(l){i={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(n){var r=this;Nw(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var i=r.observers;i.length;)i.shift().error(n)}})},e.prototype.complete=function(){var n=this;Nw(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.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 n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?ile:(this.currentObservers=null,a.push(n),new j_(function(){r.currentObservers=null,y3(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?n.error(s):o&&n.complete()},e.prototype.asObservable=function(){var n=new Wn;return n.source=this,n},e.create=function(n,r){return new HK(n,r)},e}(Wn),HK=function(t){cc(e,t);function e(n,r){var i=t.call(this)||this;return i.destination=n,i.source=r,i}return e.prototype.next=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,n)},e.prototype.error=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&i!==void 0?i:ile},e}(ii),_s=function(t){cc(e,t);function e(n){var r=t.call(this)||this;return r._value=n,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(n){var r=t.prototype._subscribe.call(this,n);return!r.closed&&n.next(this._value),r},e.prototype.getValue=function(){var n=this,r=n.hasError,i=n.thrownError,s=n._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(n){t.prototype.next.call(this,this._value=n)},e}(ii),mqe={now:function(){return Date.now()}},gqe=function(t){cc(e,t);function e(n,r){return t.call(this)||this}return e.prototype.schedule=function(n,r){return this},e}(j_),VK={setInterval:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,Ea([t,e],Sa(n)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},vqe=function(t){cc(e,t);function e(n,r){var i=t.call(this,n,r)||this;return i.scheduler=n,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(n,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=n;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(n,r,i){return i===void 0&&(i=0),VK.setInterval(n.flush.bind(n,this),i)},e.prototype.recycleAsyncId=function(n,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&VK.clearInterval(r)},e.prototype.execute=function(n,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(n,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(n,r){var i=!1,s;try{this.work(n)}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 n=this,r=n.id,i=n.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,y3(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(gqe),qK=function(){function t(e,n){n===void 0&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(e,n,r){return n===void 0&&(n=0),new this.schedulerActionCtor(this,e).schedule(r,n)},t.now=mqe.now,t}(),yqe=function(t){cc(e,t);function e(n,r){r===void 0&&(r=qK.now);var i=t.call(this,n,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(n){var r=this.actions;if(this._active){r.push(n);return}var i;this._active=!0;do if(i=n.execute(n.state,n.delay))break;while(n=r.shift());if(this._active=!1,i){for(;n=r.shift();)n.unsubscribe();throw i}},e}(qK),lR=new yqe(vqe),bqe=lR,vg=new Wn(function(t){return t.complete()});function ale(t){return t&&Rn(t.schedule)}function N8(t){return t[t.length-1]}function U8(t){return Rn(N8(t))?t.pop():void 0}function F_(t){return ale(N8(t))?t.pop():void 0}function _qe(t,e){return typeof N8(t)=="number"?t.pop():e}var j8=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function cle(t){return Rn(t?.then)}function lle(t){return Rn(t[D8])}function ule(t){return Symbol.asyncIterator&&Rn(t?.[Symbol.asyncIterator])}function dle(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Sqe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var fle=Sqe();function hle(t){return Rn(t?.[fle])}function ple(t){return yM(this,arguments,function(){var n,r,i,s;return $T(this,function(o){switch(o.label){case 0:n=t.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Eu(n.read())];case 3:return r=o.sent(),i=r.value,s=r.done,s?[4,Eu(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Eu(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function mle(t){return Rn(t?.getReader)}function zi(t){if(t instanceof Wn)return t;if(t!=null){if(lle(t))return Eqe(t);if(j8(t))return wqe(t);if(cle(t))return Cqe(t);if(ule(t))return gle(t);if(hle(t))return Tqe(t);if(mle(t))return Rqe(t)}throw dle(t)}function Eqe(t){return new Wn(function(e){var n=t[D8]();if(Rn(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function wqe(t){return new Wn(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Cqe(t){return new Wn(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,ole)})}function Tqe(t){return new Wn(function(e){var n,r;try{for(var i=Ef(t),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()})}function gle(t){return new Wn(function(e){Iqe(t,e).catch(function(n){return e.error(n)})})}function Rqe(t){return gle(ple(t))}function Iqe(t,e){var n,r,i,s;return vM(this,void 0,void 0,function(){var o,a;return $T(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=bM(t),c.label=1;case 1:return[4,n.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),i={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.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 cf(t,e,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!i)return s}function vle(t,e){return e===void 0&&(e=0),Lr(function(n,r){n.subscribe(Yn(r,function(i){return cf(r,t,function(){return r.next(i)},e)},function(){return cf(r,t,function(){return r.complete()},e)},function(i){return cf(r,t,function(){return r.error(i)},e)}))})}function yle(t,e){return e===void 0&&(e=0),Lr(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function kqe(t,e){return zi(t).pipe(yle(e),vle(e))}function xqe(t,e){return zi(t).pipe(yle(e),vle(e))}function Aqe(t,e){return new Wn(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Pqe(t,e){return new Wn(function(n){var r;return cf(n,e,function(){r=t[fle](),cf(n,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){n.error(a);return}o?n.complete():n.next(s)},0,!0)}),function(){return Rn(r?.return)&&r.return()}})}function ble(t,e){if(!t)throw new Error("Iterable cannot be null");return new Wn(function(n){cf(n,e,function(){var r=t[Symbol.asyncIterator]();cf(n,e,function(){r.next().then(function(i){i.done?n.complete():n.next(i.value)})},0,!0)})})}function Lqe(t,e){return ble(ple(t),e)}function Oqe(t,e){if(t!=null){if(lle(t))return kqe(t,e);if(j8(t))return Aqe(t,e);if(cle(t))return xqe(t,e);if(ule(t))return ble(t,e);if(hle(t))return Pqe(t,e);if(mle(t))return Lqe(t,e)}throw dle(t)}function $_(t,e){return e?Oqe(t,e):zi(t)}function Ct(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t);return $_(t,n)}function Mqe(t){return t instanceof Date&&!isNaN(t)}function Re(t,e){return Lr(function(n,r){var i=0;n.subscribe(Yn(r,function(s){r.next(t.call(e,s,i++))}))})}var Dqe=Array.isArray;function Nqe(t,e){return Dqe(e)?t.apply(void 0,Ea([],Sa(e))):t(e)}function F8(t){return Re(function(e){return Nqe(t,e)})}var Uqe=Array.isArray,jqe=Object.getPrototypeOf,Fqe=Object.prototype,$qe=Object.keys;function _le(t){if(t.length===1){var e=t[0];if(Uqe(e))return{args:e,keys:null};if(Bqe(e)){var n=$qe(e);return{args:n.map(function(r){return e[r]}),keys:n}}}return{args:t,keys:null}}function Bqe(t){return t&&typeof t=="object"&&jqe(t)===Fqe}function Sle(t,e){return t.reduce(function(n,r,i){return n[r]=e[i],n},{})}function Xt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t),r=U8(t),i=_le(t),s=i.args,o=i.keys;if(s.length===0)return $_([],n);var a=new Wn(Hqe(s,n,o?function(c){return Sle(o,c)}:$f));return r?a.pipe(F8(r)):a}function Hqe(t,e,n){return n===void 0&&(n=$f),function(r){GK(e,function(){for(var i=t.length,s=new Array(i),o=i,a=i,c=function(d){GK(e,function(){var h=$_(t[d],e),m=!1;h.subscribe(Yn(r,function(g){s[d]=g,m||(m=!0,a--),a||r.next(n(s.slice()))},function(){--o||r.complete()}))},r)},l=0;l<i;l++)c(l)},r)}}function GK(t,e,n){t?cf(n,t,e):e()}function Vqe(t,e,n,r,i,s,o,a){var c=[],l=0,d=0,h=!1,m=function(){h&&!c.length&&!l&&e.complete()},g=function(v){return l<r?y(v):c.push(v)},y=function(v){l++;var w=!1;zi(n(v,d++)).subscribe(Yn(e,function(S){e.next(S)},function(){w=!0},void 0,function(){if(w)try{l--;for(var S=function(){var R=c.shift();o||y(R)};c.length&&l<r;)S();m()}catch(R){e.error(R)}}))};return t.subscribe(Yn(e,g,function(){h=!0,m()})),function(){}}function B_(t,e,n){return n===void 0&&(n=1/0),Rn(e)?B_(function(r,i){return Re(function(s,o){return e(r,s,i,o)})(zi(t(r,i)))},n):(typeof e=="number"&&(n=e),Lr(function(r,i){return Vqe(r,i,t,n)}))}function Ele(t){return t===void 0&&(t=1/0),B_($f,t)}function qqe(){return Ele(1)}function mp(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return qqe()($_(t,F_(t)))}function Gqe(t){return new Wn(function(e){zi(t()).subscribe(e)})}function Kqe(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=U8(t),r=_le(t),i=r.args,s=r.keys,o=new Wn(function(a){var c=i.length;if(!c){a.complete();return}for(var l=new Array(c),d=c,h=c,m=function(y){var v=!1;zi(i[y]).subscribe(Yn(a,function(w){v||(v=!0,h--),l[y]=w},function(){return d--},void 0,function(){(!d||!v)&&(h||a.next(s?Sle(s,l):l),a.complete())}))},g=0;g<c;g++)m(g)});return n?o.pipe(F8(n)):o}var zqe=["addListener","removeListener"],Wqe=["addEventListener","removeEventListener"],Yqe=["on","off"];function Zo(t,e,n,r){if(Rn(n)&&(r=n,n=void 0),r)return Zo(t,e,n).pipe(F8(r));var i=Sa(Qqe(t)?Wqe.map(function(a){return function(c){return t[a](e,c,n)}}):Xqe(t)?zqe.map(KK(t,e)):Jqe(t)?Yqe.map(KK(t,e)):[],2),s=i[0],o=i[1];if(!s&&j8(t))return B_(function(a){return Zo(a,e,n)})(zi(t));if(!s)throw new TypeError("Invalid event target");return new Wn(function(a){var c=function(){for(var l=[],d=0;d<arguments.length;d++)l[d]=arguments[d];return a.next(1<l.length?l:l[0])};return s(c),function(){return o(c)}})}function KK(t,e){return function(n){return function(r){return t[n](e,r)}}}function Xqe(t){return Rn(t.addListener)&&Rn(t.removeListener)}function Jqe(t){return Rn(t.on)&&Rn(t.off)}function Qqe(t){return Rn(t.addEventListener)&&Rn(t.removeEventListener)}function du(t,e,n){t===void 0&&(t=0),n===void 0&&(n=bqe);var r=-1;return e!=null&&(ale(e)?n=e:r=e),new Wn(function(i){var s=Mqe(t)?+t-n.now():t;s<0&&(s=0);var o=0;return n.schedule(function(){i.closed||(i.next(o++),0<=r?this.schedule(void 0,r):i.complete())},s)})}function Zqe(t,e){return e===void 0&&(e=lR),du(t,t,e)}function H_(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t),r=_qe(t,1/0),i=t;return i.length?i.length===1?zi(i[0]):Ele(r)($_(i,n)):vg}var $L=new Wn(wv),eGe=Array.isArray;function tGe(t){return t.length===1&&eGe(t[0])?t[0]:t}function es(t,e){return Lr(function(n,r){var i=0;n.subscribe(Yn(r,function(s){return t.call(e,s,i++)&&r.next(s)}))})}function nGe(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t=tGe(t),t.length===1?zi(t[0]):new Wn(rGe(t))}function rGe(t){return function(e){for(var n=[],r=function(s){n.push(zi(t[s]).subscribe(Yn(e,function(o){if(n){for(var a=0;a<n.length;a++)a!==s&&n[a].unsubscribe();n=null}e.next(o)})))},i=0;n&&!e.closed&&i<t.length;i++)r(i)}}function wle(t){return Lr(function(e,n){var r=!1,i=null,s=null,o=!1,a=function(){if(s?.unsubscribe(),s=null,r){r=!1;var l=i;i=null,n.next(l)}o&&n.complete()},c=function(){s=null,o&&n.complete()};e.subscribe(Yn(n,function(l){r=!0,i=l,s||zi(t(l)).subscribe(s=Yn(n,a,c))},function(){o=!0,(!r||!s||s.closed)&&n.complete()}))})}function iGe(t,e,n,r,i){return function(s,o){var a=n,c=e,l=0;s.subscribe(Yn(o,function(d){var h=l++;c=a?t(c,d,h):(a=!0,d),o.next(c)},i))}}function Uw(t){return t<=0?function(){return vg}:Lr(function(e,n){var r=0;e.subscribe(Yn(n,function(i){++r<=t&&(n.next(i),t<=r&&n.complete())}))})}function sGe(){return Lr(function(t,e){t.subscribe(Yn(e,wv))})}function oGe(t){return Re(function(){return t})}function aGe(t,e){return B_(function(n,r){return zi(t(n,r)).pipe(Uw(1),oGe(n))})}function cGe(t,e){e===void 0&&(e=lR);var n=du(t,e);return aGe(function(){return n})}function Kc(t,e){return e===void 0&&(e=$f),t=t??lGe,Lr(function(n,r){var i,s=!0;n.subscribe(Yn(r,function(o){var a=e(o);(s||!t(i,a))&&(s=!1,i=a,r.next(o))}))})}function lGe(t,e){return t===e}function uGe(t,e){return Kc(function(n,r){return n[t]===r[t]})}function dGe(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(n){return mp(n,Ct.apply(void 0,Ea([],Sa(t))))}}function fGe(t){return Lr(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function jw(){return Lr(function(t,e){var n,r=!1;t.subscribe(Yn(e,function(i){var s=n;n=i,r&&e.next([s,i]),r=!0}))})}function ql(t,e){return Lr(iGe(t,e,arguments.length>=2,!0))}function hGe(t){return es(function(e,n){return t<=n})}function pGe(t){return Lr(function(e,n){var r=!1,i=0;e.subscribe(Yn(n,function(s){return(r||(r=!t(s,i++)))&&n.next(s)}))})}function dn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t);return Lr(function(r,i){(n?mp(t,r,n):mp(t,r)).subscribe(i)})}function Ot(t,e){return Lr(function(n,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};n.subscribe(Yn(r,function(c){i?.unsubscribe();var l=0,d=s++;zi(t(c,d)).subscribe(i=Yn(r,function(h){return r.next(e?e(c,h,d,l++):h)},function(){i=null,a()}))},function(){o=!0,a()}))})}function zK(){return Ot($f)}function mGe(t,e){return Lr(function(n,r){var i=e;return Ot(function(s,o){return t(i,s,o)},function(s,o){return i=o,o})(n).subscribe(r),function(){i=null}})}function Cle(t){return Lr(function(e,n){zi(t).subscribe(Yn(n,function(){return n.complete()},wv)),!n.closed&&e.subscribe(n)})}function gGe(t,e){return e===void 0&&(e=!1),Lr(function(n,r){var i=0;n.subscribe(Yn(r,function(s){var o=t(s,i++);(o||e)&&r.next(s),!o&&r.complete()}))})}function vGe(t,e,n){var r=Rn(t)||e||n?{next:t,error:e,complete:n}:t;return r?Lr(function(i,s){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var a=!0;i.subscribe(Yn(s,function(c){var l;(l=r.next)===null||l===void 0||l.call(r,c),s.next(c)},function(){var c;a=!1,(c=r.complete)===null||c===void 0||c.call(r),s.complete()},function(c){var l;a=!1,(l=r.error)===null||l===void 0||l.call(r,c),s.error(c)},function(){var c,l;a&&((c=r.unsubscribe)===null||c===void 0||c.call(r)),(l=r.finalize)===null||l===void 0||l.call(r)}))}):$f}function yGe(t,e){return Lr(function(n,r){var i=e??{},s=i.leading,o=s===void 0?!0:s,a=i.trailing,c=a===void 0?!1:a,l=!1,d=null,h=null,m=!1,g=function(){h?.unsubscribe(),h=null,c&&(w(),m&&r.complete())},y=function(){h=null,m&&r.complete()},v=function(S){return h=zi(t(S)).subscribe(Yn(r,g,y))},w=function(){if(l){l=!1;var S=d;d=null,r.next(S),!m&&v(S)}};n.subscribe(Yn(r,function(S){l=!0,d=S,!(h&&!h.closed)&&(o?w():v(S))},function(){m=!0,!(c&&l&&h&&!h.closed)&&r.complete()}))})}function BL(t,e,n){e===void 0&&(e=lR);var r=du(t,e);return yGe(function(){return r},n)}function Tle(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=U8(t);return Lr(function(r,i){for(var s=t.length,o=new Array(s),a=t.map(function(){return!1}),c=!1,l=function(h){zi(t[h]).subscribe(Yn(i,function(m){o[h]=m,!c&&!a[h]&&(a[h]=!0,(c=a.every($f))&&(a=null))},wv))},d=0;d<s;d++)l(d);r.subscribe(Yn(i,function(h){if(c){var m=Ea([h],Sa(o));i.next(n?n.apply(void 0,Ea([],Sa(m))):m)}}))})}function Qe(t){const e=_.useCallback(r=>{const i=t.subscribe(r);return()=>i.unsubscribe()},[t]),n=_.useCallback(()=>t.value,[t]);return _.useSyncExternalStore(e,n)}class li{constructor(e,n){this.defaultValue=n,this.setValue=s=>{this._value$.next(s),localStorage.setItem(this.key,JSON.stringify(s))},this.getValue=()=>this._value$.getValue(),this.key=`matrix-setting-${e}`;const r=localStorage.getItem(this.key);let i=n;if(r!==null)try{i=JSON.parse(r)}catch(s){M.warn(`Invalid value stored for setting ${e}: ${r}.`,s)}this._value$=new _s(i),this.value$=this._value$}}function Gn(t){return[Qe(t.value$),t.setValue]}const Rle=new li("opt-in-analytics",null),uR=()=>{const t=Gn(Rle);return Ut.instance.isEnabled()?t:[!1,null]},$8=new li("developer-settings-tab",!1),Ile=new li("duplicate-tiles",0),kle=new li("show-non-member-tiles",!1),B8=new li("debug-tile-layout",!1),Gb=new li("show-connection-stats",!1),WK=new li("audio-input",void 0),YK=new li("audio-output",void 0),XK=new li("video-input",void 0),xle=new li("background-blur",!1),Ale=new li("hand-raised-show-timer",!1),Ple=new li("reactions-show",!0),H8=new li("reactions-play-sound",!0),Lle=new li("sound-effect-volume",.5),Ole=new li("new-membership-manager",!0),V8=new li("experimental-to-device-transport",!0),Mle=new li("mute-all-audio",!1),JK=new li("always-show-self",!0),Dle=new li("always-show-iphone-earpiece",!1);var dR=(t=>(t[t.Guest=0]="Guest",t[t.Registered=1]="Registered",t))(dR||{});const Fc=class Fc{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 WVe,this.eventSignup=new XVe,this.eventCallStarted=new YVe,this.eventLogin=new JVe,this.eventMuteMicrophone=new QVe,this.eventMuteCamera=new ZVe,this.eventUndecryptableToDevice=new eqe,this.eventQualitySurvey=new tqe,this.eventCallDisconnected=new nqe,this.eventCallConnectDuration=new rqe;let n,r;n=Br().posthogApiKey??void 0,r=Br().posthogApiHost??void 0,n&&r?(this.posthog.init(n,{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):(M.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 Fc(CVe)),this.internalInstance}static resetInstance(){this.internalInstance=null}registerSuperProperties(e){this.enabled&&this.posthog.register(e)}static getPlatformProperties(){return{appVersion:"embedded-v0.16.2",matrixBackend:ut?"embedded":"jssdk",callBackend:"livekit",cryptoVersion:ut?void 0:window.matrixclient?.getCrypto()?.getVersion()}}capture(e,n,r){this.enabled&&this.posthog.capture(e,{...n},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 n=await this.getAnalyticsId();try{if(!n&&!ut){const r=e();await this.setAccountAnalyticsId(r),n=await this.hashedEcAnalyticsId(r)}}catch(r){M.log("Unable to identify user for tracking"+r?.toString())}n?this.posthog.identify(n):M.info("No analyticsID is available. Should not try to setup posthog")}}async getAnalyticsId(){const e=window.matrixclient;let n;return ut?n=Br().posthogUserId:n=(await e.getAccountDataFromServer(Fc.ANALYTICS_EVENT_TYPE))?.id??null,n?await this.hashedEcAnalyticsId(n):null}async hashedEcAnalyticsId(e){const n=window.matrixclient,r="ec"+e+n.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(!ut){const n=window.matrixclient,r=await n.getAccountDataFromServer(Fc.ANALYTICS_EVENT_TYPE);await n.setAccountData(Fc.ANALYTICS_EVENT_TYPE,Object.assign({id:e},r))}}getAnonymity(){return this.anonymity}logout(){this.enabled&&this.posthog.reset(),this.optInListener?.unsubscribe(),this.optInListener=null,this.setAnonymity(0)}onLoginStatusChanged(){this.maybeIdentifyUser().catch(()=>M.log("Could not identify user on login status change"))}updateSuperProperties(){this.platformSuperProperties=Fc.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(Fc.getRandomAnalyticsId),await this.identificationPromise,this.userRegisteredInThisSession()&&this.eventSignup.track()),this.anonymity!==0&&this.updateSuperProperties())}trackEvent({eventName:e,...n},r){const i=()=>{this.anonymity==0||this.anonymity==1||this.capture(e,n,r)};this.identificationPromise?this.identificationPromise.then(i,s=>{M.error("Failed to identify user for tracking",s)}):i()}startListeningToSettingsChanges(){this.optInListener??=Rle.value$.subscribe(e=>{this.setAnonymity(e?2:0),this.maybeIdentifyUser().catch(()=>M.log("Could not identify user"))})}setRegistrationType(e){this.registrationType=e,!(this.anonymity==0||this.anonymity==1)&&this.updateSuperProperties()}};Fc.ANALYTICS_EVENT_TYPE="im.vector.analytics",Fc.internalInstance=null;let Ut=Fc;const bGe=2*60*1e3;class _Ge{async forceFlush(){}onStart(e){try{switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipStart(e);return;case"matrix.groupCallMembership.summaryReport":this.onSummaryReportStart(e);return}}catch(n){M.debug(n)}}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(n){return M.warn("Invalid prev call data",e,"error:",n),null}}set prevCall(e){localStorage.setItem("matrix-prev-call",JSON.stringify(e))}onGroupCallMembershipStart(e){const n=this.prevCall,r=e.attributes["matrix.confId"];if(n!==null&&r===n.callId){const i=xG(e.startTime)-n.hangupTs;i<=bGe&&Ut.instance.trackEvent({eventName:"Rejoin",callId:n.callId,rejoinDuration:i})}}onGroupCallMembershipEnd(e){this.prevCall={callId:e.attributes["matrix.confId"],hangupTs:xG(e.endTime)}}onSummaryReportStart(e){const n=e.events.find(r=>r.name==="matrix.stats.summary");if(n!==void 0){const r=n.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"]}`,c=`${r["matrix.stats.summary.maxPacketLoss"]}`,l=`${r["matrix.stats.summary.peerConnections"]}`,d=`${r["matrix.stats.summary.percentageConcealedAudio"]}`,h=`${r["matrix.stats.summary.opponentUsersInCall"]}`,m=`${r["matrix.stats.summary.opponentDevicesInCall"]}`,g=`${r["matrix.stats.summary.diffDevicesToPeerConnections"]}`,y=`${r["matrix.stats.summary.ratioPeerConnectionToDevices"]}`;Ut.instance.trackEvent({eventName:"MediaReceived",callId:e.attributes["matrix.confId"],mediaReceived:i,audioReceived:o,videoReceived:s,maxJitter:a,maxPacketLoss:c,peerConnections:l,percentageConcealedAudio:d,opponentUsersInCall:h,opponentDevicesInCall:m,diffDevicesToPeerConnections:g,ratioPeerConnectionToDevices:y},{send_instantly:!0})}}}async shutdown(){return Promise.resolve()}}const QK=t=>Object.entries(t).map(([e,n])=>({key:e,type:typeof n,value:n}));class SGe{constructor(){this.spans=[]}async forceFlush(){}onStart(e){this.spans.push(e)}onEnd(){}dump(){const e=Date.now()*1e3,n=new Map;for(const s of this.spans){const o=s.spanContext().traceId;let a=n.get(o);a===void 0&&(a=[],n.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:[...n.entries()].map(([s,o])=>({traceID:s,warnings:null,processes:i,spans:o.map(a=>{const c=a.spanContext(),l=wx(a.startTime),d=a.duration[0]===-1?e-l:wx(a.duration);return{traceID:s,spanID:c.spanId,operationName:a.name,processID:r,warnings:null,startTime:l,duration:d,references:a.parentSpanContext?.spanId===void 0?[]:[{refType:"CHILD_OF",traceID:s,spanID:a.parentSpanContext?.spanId}],tags:QK(a.attributes),logs:a.events.map(h=>({timestamp:wx(h.time),fields:[...QK(h.attributes??{}),{key:"event",type:"string",value:h.name}]}))}})}))})}async shutdown(){}}const EGe="element-call";let K1;class fR{static globalInit(){(!K1||K1.isOtlpEnabled!==!1)&&(M.info("(Re)starting OpenTelemetry debug reporting"),K1?.dispose(),K1=new fR(void 0,Nle()))}static get instance(){return K1}constructor(e,n){const r=[];e?(M.info("Enabling OTLP collector with URL "+e),this.otlpExporter=new VBe({url:e}),r.push(new W$e(this.otlpExporter))):M.info("OTLP collector disabled"),n&&(this.rageshakeProcessor=new SGe,r.push(this.rageshakeProcessor)),r.push(new _Ge),this._provider=new zBe({resource:ace({[Jae]:EGe}),spanProcessors:r}),yx.trace.setGlobalTracerProvider(this._provider),this._tracer=yx.trace.getTracer("my-element-call-otl-tracer")}dispose(){yx.trace.disable(),this._provider?.shutdown().catch(e=>{M.error("Failed to shutdown OpenTelemetry",e)})}get isOtlpEnabled(){return!!this.otlpExporter}get tracer(){return this._tracer}get provider(){return this._provider}}const ZK=async t=>{const{gzip:e}=await lb(async()=>{const{gzip:r}=await import("./pako.esm-Bt8vjcgE.js");return{gzip:r}},[],import.meta.url),n=new TextEncoder().encode(t);return new Blob([e(n)])};async function wGe(t,e){e.append("crypto_version",t.getVersion());const n=await t.getOwnDeviceKeys(),r=[`curve25519:${n.curve25519}`,`ed25519:${n.ed25519}`];e.append("device_keys",r.join(", "));const i=await t.getCrossSigningStatus();e.append("cross_signing_ready",String(await t.isCrossSigningReady())),e.append("cross_signing_key",await t.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 CGe(t,e,n){const r=t.secretStorage;n.append("secret_storage_ready",String(await e.isSecretStorageReady())),n.append("secret_storage_key_in_account",String(await r.hasKey())),n.append("session_backup_key_in_secret_storage",String(!!await t.isKeyBackupKeyStored()));const i=await e.getSessionBackupPrivateKey();n.append("session_backup_key_cached",String(!!i)),n.append("session_backup_key_well_formed",String(i instanceof Uint8Array))}function Nle(){return Br().rageshakeSubmitUrl??void 0}function hR(t=Nle){const{client:e}=jp(),[{sending:n,sent:r,error:i},s]=_.useState({sending:!1,sent:!1,error:void 0});return{submitRageshake:_.useCallback(async a=>{const c=t();if(!c)throw new Error("No rageshake URL is configured");if(!n)try{s({sending:!0,sent:!1,error:void 0});let l="UNKNOWN";window.navigator&&window.navigator.userAgent&&(l=window.navigator.userAgent);let d="UNKNOWN";try{d=String(window.matchMedia("(pointer: coarse)").matches)}catch(y){M.warn("Could not get coarse pointer for rageshake submit.",y)}let h=a.rageshakeRequestId?`Rageshake ${a.rageshakeRequestId}`:"";a.description&&(h+=`: ${a.description}`);const m=new FormData;if(m.append("text",h??"User did not supply any additional text."),m.append("app","matrix-video-chat"),m.append("version","embedded-v0.16.2"),m.append("user_agent",l),m.append("installed_pwa","false"),m.append("touch_input",d),m.append("call_backend","livekit"),m.append("hostname",window.location.hostname),e){const y=e.getUserId(),v=e.getUser(y);m.append("display_name",v?.displayName??""),m.append("user_id",e.credentials.userId??""),m.append("device_id",e.deviceId??""),a.roomId&&m.append("room_id",a.roomId);const w=e.getCrypto();w&&(await wGe(w,m),await CGe(e,w,m))}if(a.label&&m.append("label",a.label),navigator.storage&&navigator.storage.persisted)try{m.append("storageManager_persisted",String(await navigator.storage.persisted()))}catch(y){M.warn("coulr not get navigator peristed storage",y)}else if(document.hasStorageAccess)try{m.append("storageManager_persisted",String(await document.hasStorageAccess()))}catch(y){M.warn("could not get storage access",y)}if(navigator.storage&&navigator.storage.estimate)try{const y=await navigator.storage.estimate();m.append("storageManager_quota",String(y.quota)),m.append("storageManager_usage",String(y.usage)),y.usageDetails&&Object.keys(y.usageDetails).forEach(v=>{m.append(`storageManager_usage_${v}`,String(y.usageDetails[v]))})}catch(y){M.warn("could not obatain storage estimate",y)}if(a.sendLogs){const y=await Mje();for(const v of y)m.append("compressed-log",await ZK(v.lines),v.id);m.append("file",await ZK(fR.instance.rageshakeProcessor.dump()),"traces.json.gz")}a.rageshakeRequestId&&m.append("group_call_rageshake_request_id",a.rageshakeRequestId);const g=await fetch(c,{method:"POST",body:m});if(g.status!==200)throw new Error(`Failed to submit feedback: receive HTTP ${g.status} ${g.statusText}`);s({sending:!1,sent:!0,error:void 0})}catch(l){s({sending:!1,sent:!1,error:l}),M.error(l)}},[e,n,t]),sending:n,sent:r,error:i,available:!!t()}}function TGe(){const{client:t}=jp();return _.useCallback((n,r)=>{t.sendEvent(n,"org.matrix.rageshake_request",{request_id:r}).catch(i=>{M.error("Failed to send org.matrix.rageshake_request event",i)})},[t])}function RGe(t){const[e,n]=_.useState(!1),r=_.useCallback(()=>n(!1),[n]),{client:i}=jp(),[s,o]=_.useState();return _.useEffect(()=>{if(!i)return;const a=c=>{c.getType()==="org.matrix.rageshake_request"&&t===c.getRoomId()&&i.getUserId()!==c.getSender()&&(o(c.getContent().request_id),n(!0))};return i.on(Le.Event,a),()=>{i.removeListener(Le.Event,a)}},[n,t,i]),{rageshakeRequestId:s??"",roomId:t,open:e,onDismiss:r}}const IGe=({description:t})=>{const{submitRageshake:e,sending:n,sent:r,error:i}=hR(),{t:s}=We(),o=_.useCallback(()=>{e({description:t,sendLogs:!0}).catch(c=>{M.error("Failed to send rageshake",c)})},[e,t]);if(!sn.get().rageshake?.submit_url)return null;let a=null;if(n)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(Bt,{onClick:o,className:TG.wideButton,disabled:n,children:c})}return E.jsx("div",{className:TG.rageshakeControl,children:a})},kGe="_error_17zfc_1",xGe="_icon_17zfc_9",bE={error:kGe,icon:xGe},AGe="_endCall_bwclo_8",PGe={endCall:AGe},Ule=({muted:t,...e})=>{const{t:n}=We(),r=t?Hoe:t8,i=n(t?"unmute_microphone_button_label":"mute_microphone_button_label");return E.jsx(qi,{label:i,children:E.jsx(Bt,{iconOnly:!0,Icon:r,kind:t?"primary":"secondary",...e})})},jle=({muted:t,...e})=>{const{t:n}=We(),r=t?N8e:lae,i=n(t?"start_video_button_label":"stop_video_button_label");return E.jsx(qi,{label:i,children:E.jsx(Bt,{iconOnly:!0,Icon:r,kind:t?"primary":"secondary",...e})})},LGe=({enabled:t,...e})=>{const{t:n}=We(),r=n(t?"stop_screenshare_button_label":"screenshare_button_label");return E.jsx(qi,{label:r,children:E.jsx(Bt,{iconOnly:!0,Icon:A8e,kind:t?"primary":"secondary",...e})})},Fle=({className:t,...e})=>{const{t:n}=We();return E.jsx(qi,{label:n("hangup_button_label"),children:E.jsx(Bt,{className:Oe(t,PGe.endCall),iconOnly:!0,Icon:Ooe,destructive:!0,...e})})},$le=t=>{const{t:e}=We();return E.jsx(qi,{label:e("common.settings"),children:E.jsx(Bt,{iconOnly:!0,Icon:x8e,kind:"secondary",...t})})},OGe="_external_jhjdf_8",MGe={external:OGe};function Ble(t,e){const n=Uee(t),r=Wee(t,{state:e});return[n,r]}const il=({ref:t,to:e,state:n,...r})=>{const[i,s]=Ble(e,n);return E.jsx(l7e,{ref:t,...r,href:i,onClick:s})},Jh=({ref:t,className:e,children:n,...r})=>E.jsx("a",{ref:t,className:Oe(e,MGe.external),target:"_blank",rel:"noreferrer noopener",...r,children:n}),q8=({ref:t,to:e,state:n,...r})=>{const[i,s]=Ble(e,n);return E.jsx(Bt,{as:"a",ref:t,...r,href:i,onClick:s})};function Fw(t,e,n,r){_.useEffect(()=>{if(t)return t.addEventListener(e,n,r),()=>t.removeEventListener(e,n,r)},[t,e,n,r])}function Hle(t,e,n){_.useEffect(()=>(t.on(e,n),()=>{t.off(e,n)}),[t,e,n])}function gp(t,e,n){const r=_.useCallback(i=>(t.on(e,i),()=>{t.off(e,i)}),[t,e]);return _.useSyncExternalStore(r,n)}function G8(t){return gp(t,ei.MembershipsChanged,_.useCallback(()=>t.memberships,[t]))}const Vle=_.createContext(void 0),K8=()=>{const t=_.use(Vle);if(!t)throw new Error("useReactions must be used within a ReactionsProvider");return t},DGe=({children:t,rtcSession:e,vm:n})=>{const r=G8(e),i=r0(),s=i?.state==="valid"&&i.supportedFeatures.reactions,o=e.room,a=o.client.getUserId(),c=o.client.getDeviceId(),l=`${a}:${c}`,d=_.useMemo(()=>r.find(S=>S.sender===a&&S.deviceId===c)?.eventId,[r,a,c]),h=Qe(n.reactions$),m=_.useMemo(()=>l!==void 0?h[l]:void 0,[l,h]),g=Qe(n.handsRaised$),y=_.useMemo(()=>l!==void 0?g[l]:void 0,[l,g]),v=_.useCallback(async()=>{if(!l)return;const S=y?.reactionEventId;if(S)try{await o.client.redactEvent(e.room.roomId,S),M.debug("Redacted raise hand event")}catch(R){throw M.error("Failed to redact reaction event",S,R),R}else try{if(!d)throw new Error("Cannot find own membership event");const R=await o.client.sendEvent(e.room.roomId,Z.Reaction,{"m.relates_to":{rel_type:vn.Annotation,event_id:d,key:"🖐️"}});M.debug("Sent raise hand event",R.event_id)}catch(R){M.error("Failed to send raised hand",R)}},[d,l,y,e,o]),w=_.useCallback(async S=>{if(!(!l||m)){if(!d)throw new Error("Cannot find own membership event");await o.client.sendEvent(e.room.roomId,O8,{"m.relates_to":{rel_type:vn.Reference,event_id:d},emoji:S.emoji,name:S.name})}},[d,m,o,l,e]);return E.jsx(Vle,{value:{supportsReactions:s,toggleRaisedHand:v,sendReaction:w},children:t})},NGe="_raisedButton_unw54_1",UGe="_reactionPopupMenu_unw54_5",jGe="_reactionPopupMenuRoot_unw54_21",FGe="_reactionPopupMenuModal_unw54_21",$Ge="_reactionsMenuSection_unw54_47",BGe="_reactionsMenu_unw54_47",HGe="_reactionButton_unw54_81",VGe="_verticalSeperator_unw54_91",qGe="_alert_unw54_99",Ha={raisedButton:NGe,reactionPopupMenu:UGe,reactionPopupMenuRoot:jGe,reactionPopupMenuModal:FGe,reactionsMenuSection:$Ge,reactionsMenu:BGe,reactionButton:HGe,verticalSeperator:VGe,alert:qGe};function ez(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function GGe(...t){return e=>{let n=!1;const r=t.map(i=>{const s=ez(i,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():ez(t[i],null)}}}}function KGe(t){const e=zGe(t),n=_.forwardRef((r,i)=>{const{children:s,...o}=r,a=_.Children.toArray(s),c=a.find(YGe);if(c){const l=c.props.children,d=a.map(h=>h===c?_.Children.count(l)>1?_.Children.only(null):_.isValidElement(l)?l.props.children:null:h);return E.jsx(e,{...o,ref:i,children:_.isValidElement(l)?_.cloneElement(l,void 0,d):null})}return E.jsx(e,{...o,ref:i,children:s})});return n.displayName=`${t}.Slot`,n}function zGe(t){const e=_.forwardRef((n,r)=>{const{children:i,...s}=n;if(_.isValidElement(i)){const o=JGe(i),a=XGe(s,i.props);return i.type!==_.Fragment&&(a.ref=r?GGe(r,o):o),_.cloneElement(i,a)}return _.Children.count(i)>1?_.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var WGe=Symbol("radix.slottable");function YGe(t){return _.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===WGe}function XGe(t,e){const n={...e};for(const r in e){const i=t[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...a)=>{const c=s(...a);return i(...a),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...t,...n}}function JGe(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var QGe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ZGe=QGe.reduce((t,e)=>{const n=KGe(`Primitive.${e}`),r=_.forwardRef((i,s)=>{const{asChild:o,...a}=i,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{}),eKe=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),tKe="VisuallyHidden",HL=_.forwardRef((t,e)=>E.jsx(ZGe.span,{...t,ref:e,style:{...eKe,...t.style}}));HL.displayName=tKe;const nKe="_modal_lmgdq_8",rKe="_dialog_lmgdq_14",iKe="_content_lmgdq_21",sKe="_drawer_lmgdq_32",oKe="_close_lmgdq_59",aKe="_header_lmgdq_84",cKe="_body_lmgdq_114",lKe="_tabbed_lmgdq_129",uKe="_handle_lmgdq_133",Ms={modal:nKe,dialog:rKe,content:iKe,drawer:sKe,close:oKe,header:aKe,body:cKe,tabbed:lKe,handle:uKe},dKe="_bg_180k3_8",fKe="_animate_180k3_23",hKe="_overlay_180k3_42",Bs={bg:dKe,animate:fKe,overlay:hKe},Up=({title:t,hideHeader:e,children:n,className:r,classNameDrawer:i,classNameModal:s,open:o,onDismiss:a,tabbed:c,...l})=>{const{t:d}=We(),h=YT("(hover: none) or (pointer: coarse)"),m=_.useCallback(g=>{g||a?.()},[a]);if(h)return E.jsx(Hs.Root,{open:o,onOpenChange:m,dismissible:a!==void 0,children:E.jsxs(Hs.Portal,{children:[E.jsx(Hs.Overlay,{className:Oe(Bs.bg)}),E.jsx(Hs.Content,{className:Oe(r,i,Bs.overlay,Ms.modal,Ms.drawer,{[Ms.tabbed]:c}),role:"dialog","aria-describedby":void 0,...l,children:E.jsxs("div",{className:Ms.content,children:[E.jsxs("div",{className:Ms.header,children:[E.jsx("div",{className:Ms.handle}),E.jsx(HL,{asChild:!0,children:E.jsx(Hs.Title,{children:t})})]}),E.jsx("div",{className:Ms.body,children:n})]})})]})});{const g=E.jsx(jM,{asChild:!0,children:E.jsx(gl,{as:"h2",weight:"semibold",size:"md",children:t})}),y=E.jsxs("div",{className:Ms.header,children:[g,a!==void 0&&E.jsx(Pse,{className:Ms.close,"data-testid":"modal_close","aria-label":d("action.close"),children:E.jsx(LT,{width:20,height:20})})]});return E.jsx(MM,{open:o,onOpenChange:m,children:E.jsxs(DM,{children:[E.jsx(NM,{className:Oe(Bs.bg,Bs.animate)}),E.jsx(UM,{asChild:!0,"aria-describedby":void 0,role:"dialog",...l,children:E.jsx(Vse,{className:Oe(r,s,Bs.overlay,Bs.animate,Ms.modal,Ms.dialog,{[Ms.tabbed]:c}),children:E.jsxs("div",{className:Ms.content,children:[e?null:y,e?E.jsx(HL,{asChild:!0,children:g}):null,E.jsx("div",{className:Ms.body,children:n})]})})})]})})}},pKe=({raised:t,open:e,...n})=>{const{t:r}=We();return E.jsx(qi,{label:r("common.reactions"),children:E.jsx(Bt,{className:Oe(t&&Ha.raisedButton),"aria-expanded":e,"aria-haspopup":!0,kind:t||e?"primary":"secondary",iconOnly:!0,Icon:t?Xoe:k8e,...n})})};function mKe({sendReaction:t,toggleRaisedHand:e,isHandRaised:n,canReact:r,errorText:i}){const{t:s}=We(),[o,a]=_.useState(!1),c=_.useMemo(()=>o?qb:qb.slice(0,5),[o]),l=s(n?"action.lower_hand":"action.raise_hand");return E.jsxs(E.Fragment,{children:[i&&E.jsx(Zxe,{className:Ha.alert,type:"critical",title:s("error.generic"),children:i}),E.jsxs("div",{className:Ha.reactionPopupMenu,children:[E.jsx("section",{className:Ha.handRaiseSection,children:E.jsx(qi,{label:l,caption:"H",children:E.jsx(Bt,{kind:n?"primary":"secondary","aria-keyshortcuts":"H","aria-pressed":n,"aria-label":l,onClick:()=>e(),iconOnly:!0,Icon:Xoe})})}),E.jsx("div",{className:Ha.verticalSeperator}),E.jsx("section",{className:Ha.reactionsMenuSection,children:E.jsx("menu",{className:Oe(o&&Ha.reactionsMenuExpanded,Ha.reactionsMenu),children:c.map((d,h)=>E.jsx("li",{children:E.jsx(qi,{label:d.name,caption:h<jL?(h+1).toString():void 0,children:E.jsx(Bt,{kind:"secondary",className:Ha.reactionButton,disabled:!r,onClick:()=>t(d),"aria-keyshortcuts":h<jL?(h+1).toString():void 0,children:d.emoji})})},d.name))})}),E.jsx("section",{style:{marginLeft:"var(--cpd-separator-spacing)"},children:E.jsx(qi,{label:s(o?"action.show_less":"action.show_more"),children:E.jsx(Bt,{iconOnly:!0,"aria-label":s(o?"action.show_less":"action.show_more"),Icon:o?y8e:HMe,kind:"tertiary",onClick:()=>a(!o)})})})]})]})}function gKe({identifier:t,vm:e,...n}){const{t:r}=We(),{toggleRaisedHand:i,sendReaction:s}=K8(),[o,a]=_.useState(!1),[c,l]=_.useState(!1),[d,h]=_.useState(),m=!!Qe(e.handsRaised$)[t],g=!Qe(e.reactions$)[t];_.useEffect(()=>{h(void 0)},[c]);const y=_.useCallback(async w=>{try{a(!0),await s(w),h(void 0),l(!1)}catch(S){h(S instanceof Error?S.message:"Unknown error"),M.error("Failed to send reaction",S)}finally{a(!1)}},[s]),v=_.useCallback(()=>{(async()=>{try{a(!0),await i(),l(!1)}catch(S){h(S instanceof Error?S.message:"Unknown error"),M.error("Failed to raise/lower hand",S)}finally{a(!1)}})()},[i]);return E.jsxs(E.Fragment,{children:[E.jsx(pKe,{disabled:o,onClick:()=>l(w=>!w),raised:!!m,open:c,...n}),E.jsx(Up,{open:c,title:r("action.pick_reaction"),hideHeader:!0,classNameModal:Ha.reactionPopupMenuModal,className:Ha.reactionPopupMenuRoot,onDismiss:()=>l(!1),children:E.jsx(mKe,{errorText:d,isHandRaised:!!m,canReact:!o&&!!g,sendReaction:w=>void y(w),toggleRaisedHand:v})})]})}const Kb=({Icon:t,title:e,rageshake:n,fatal:r,children:i,widget:s})=>{const{t:o}=We(),{confineToRoom:a}=no(),c=_.useCallback(()=>{window.location.href="/"},[]),l=({widget:h})=>{const m=()=>{h.api.transport.send(Ri.Close,{}).catch(g=>{M.error("Failed to send close action",g)}).finally(()=>{h.api.transport.stop()})};return E.jsx(Bt,{kind:"primary",onClick:m,children:o("action.close")})},d=()=>r||location.pathname==="/"?E.jsx(Bt,{kind:"tertiary",className:bE.homeLink,onClick:c,children:o("return_home_button")}):E.jsx(q8,{kind:"tertiary",className:bE.homeLink,to:"/",children:o("return_home_button")});return E.jsxs("div",{className:bE.error,children:[E.jsx(moe,{className:bE.icon,children:E.jsx(t,{"aria-hidden":!0})}),E.jsx(gl,{as:"h1",weight:"semibold",size:"md",children:e}),i,n&&E.jsx(IGe,{description:`***Error View***: ${e}`}),s?E.jsx(l,{widget:s}):!a&&E.jsx(d,{})]})};class qle extends Error{constructor(e,n){super(e),this.richMessage=n}}const vKe=()=>{const{t}=We();return E.jsx(Kb,{widget:ut,Icon:Woe,title:t("error.open_elsewhere"),children:E.jsx("p",{children:t("error.open_elsewhere_description",{brand:"Element Call"})})})};class yKe extends qle{constructor(){super("App opened in another tab",E.jsx(vKe,{}))}}const qg=({className:t,children:e})=>{const{header:n}=no();return E.jsxs("div",{className:Oe(lx.page,t),children:[n==="standard"&&E.jsxs(qu,{children:[E.jsx(jf,{children:E.jsx(fp,{})}),E.jsx(Ff,{})]}),E.jsx("div",{className:lx.container,children:E.jsx("div",{className:lx.content,children:e})})]})},zb=({error:t,widget:e})=>{const{t:n}=We();return _.useEffect(()=>{M.error(t),IT(t)},[t]),E.jsx(qg,{children:t instanceof qle?t.richMessage:E.jsx(Kb,{widget:e,Icon:PT,title:n("error.generic"),rageshake:!0,fatal:!0,children:E.jsx("p",{children:n("error.generic_description")})})})},pR=()=>{const{t}=We();return E.jsx(qg,{children:E.jsx("h1",{children:t("common.loading")})})},z8=_.createContext(void 0);z8.Provider;const r0=()=>_.use(z8);function jp(){let t,e;const n=r0();return n?.state==="valid"&&(t=n.authenticated?.client,e=n.setClient),{client:t,setClient:e}}function W8(){const t=r0();let e,n,r=!1,i=!0,s,o=!1,a;return t?.state==="valid"?(e=t.authenticated?.client,n=t.setClient,r=t.authenticated?.isPasswordlessUser??!1,i=!1,o=e!==void 0,a=t.authenticated?.logout):t?.state==="error"&&(s=t.error,i=!1),{client:e,setClient:n,passwordlessUser:r,loading:i,authenticated:o,logout:a,error:s}}const tz="BroadcastChannel"in window?new BroadcastChannel("load"):null,bKe=({children:t})=>{const e=hl(),[n,r]=_.useState(void 0),i=_.useRef(!1);_.useEffect(()=>{i.current||(i.current=!0,_Ke().then(R=>{r(R),Ut.instance.isEnabled()&&Ut.instance.startListeningToSettingsChanges()}).catch(R=>M.error(R)).finally(()=>i.current=!1))},[]);const s=_.useCallback(async R=>{const x=Kle();!n?.client||!x||(await n.client.setPassword({type:"m.login.password",identifier:{type:"m.id.user",user:x.user_id},user:x.user_id,password:x.tempPassword},R),nz({...x,passwordlessUser:!1}),r({...n,passwordlessUser:!1}))},[n]),o=_.useCallback((R,x)=>{const T=n?.client;T&&T!==R&&T.stopClient(),nz(x),r({widgetApi:null,client:R,passwordlessUser:x.passwordlessUser}),Ut.instance.isEnabled()&&Ut.instance.startListeningToSettingsChanges()},[n?.client]),a=_.useCallback(async()=>{const R=n?.client;R&&(await R.logout(!0),await R.clearStores(),Gle(),r(null),await e("/"),Ut.instance.logout(),Ut.instance.setRegistrationType(dR.Guest))},[e,n?.client]);_.useEffect(()=>{ut||tz?.postMessage({})},[]);const[c,l]=_.useState(void 0);Fw(tz,"message",_.useCallback(()=>{n?.client.stopClient(),l(new yKe)},[n?.client,l]));const[d,h]=_.useState(!1),[m,g]=_.useState(!1),[y,v]=_.useState(!1),w=_.useMemo(()=>c?{state:"error",error:c}:n===void 0?void 0:{state:"valid",authenticated:n===null?void 0:{client:n.client,isPasswordlessUser:n.passwordlessUser,changePassword:s,logout:a},setClient:o,disconnected:d,supportedFeatures:{reactions:m,thumbnails:y}},[c,s,n,a,o,d,m,y]),S=_.useCallback((R,x,T)=>{h(SKe(R,T))},[]);return _.useEffect(()=>{if(n){if(window.matrixclient=n.client,window.passwordlessUser=n.passwordlessUser,Ut.hasInstance()&&Ut.instance.onLoginStatusChanged(),n.client&&n.client.on(Le.Sync,S),n.widgetApi){v(!1);const R=n.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.reaction"),x=n.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.room.redaction"),T=n.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.reaction"),I=n.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.room.redaction");!R||!T||!x||!I?(M.warn("Widget does not support reactions"),g(!1)):g(!0)}else g(!0),v(!0);return()=>{n.client&&n.client.removeListener(Le.Sync,S)}}},[n,S]),c?E.jsx(zb,{widget:ut,error:c}):E.jsx(z8,{value:w,children:t})};async function _Ke(){if(ut){M.log("Using a matryoshka client");const t=await ut.client;return{widgetApi:ut.api,client:t,passwordlessUser:!1}}else{const{initSPA:t}=await lb(async()=>{const{initSPA:e}=await import("./spa-pcSdV42q.js");return{initSPA:e}},[],import.meta.url);return t(Kle,Gle)}}const Gle=()=>localStorage.removeItem("matrix-auth-store"),nz=t=>localStorage.setItem("matrix-auth-store",JSON.stringify(t)),Kle=()=>{const t=localStorage.getItem("matrix-auth-store");if(t)return JSON.parse(t)},SKe=(t,e)=>t==="ERROR"&&e?.error?.name==="ConnectionError";function V_(t){const[{success:e,loading:n,displayName:r,avatarUrl:i,error:s},o]=_.useState(()=>{let c;return t&&(c=t.getUser(t.getUserId())??void 0),{success:!1,loading:!1,displayName:c?.rawDisplayName,avatarUrl:c?.avatarUrl,error:void 0}});_.useEffect(()=>{const c=(d,{displayName:h,avatarUrl:m})=>{o({success:!1,loading:!1,displayName:h,avatarUrl:m,error:void 0})};let l;if(t){const d=t.getUserId();l=t.getUser(d),l?.on(Ui.DisplayName,c),l?.on(Ui.AvatarUrl,c)}return()=>{l&&(l.removeListener(Ui.DisplayName,c),l.removeListener(Ui.AvatarUrl,c))}},[t]);const a=_.useCallback(async({displayName:c,avatar:l,removeAvatar:d})=>{if(t){o(h=>({...h,loading:!0,error:void 0,success:!1}));try{await t.setDisplayName(c);let h;d?await t.setAvatarUrl(""):l&&({content_uri:h}=await t.uploadContent(l),await t.setAvatarUrl(h)),o(m=>({...m,displayName:c,avatarUrl:d?void 0:h??m.avatarUrl,loading:!1,success:!0}))}catch(h){o(m=>({...m,loading:!1,error:h instanceof Error?h:Error(h),success:!1}))}}else M.error("Client not initialized before calling saveProfile")},[t]);return{loading:n,error:s,displayName:r,avatarUrl:i,saveProfile:a,success:e}}const EKe="_settingsModal_1dkeq_8",wKe="_volumeSlider_1dkeq_20",rz={settingsModal:EKe,volumeSlider:wKe},CKe="_tabContainer_1nnp9_8",TKe="_tabList_1nnp9_14",iz={tabContainer:CKe,tabList:TKe};function RKe({label:t,tab:e,onTabChange:n,tabs:r}){const i=_.useId();return E.jsxs("div",{className:iz.tabContainer,children:[E.jsx(UMe,{role:"tablist","aria-label":t,className:iz.tabList,children:r.map(({key:s,name:o})=>E.jsx(BMe,{"aria-controls":`${i}[${s}]`,onClick:()=>n(s),active:s===e,children:o},s))}),r.map(({key:s,content:o})=>E.jsx("div",{id:`${i}[${s}]`,style:{display:s===e?void 0:"none"},children:o},s))]})}const IKe="_fieldRow_iwncy_8",kKe="_field_iwncy_8",xKe="_rightAlign_iwncy_21",AKe="_inputField_iwncy_33",PKe="_disabled_iwncy_52",LKe="_prefix_iwncy_110",OKe="_checkboxField_iwncy_131",MKe="_checkbox_iwncy_131",DKe="_description_iwncy_168",NKe="_errorMessage_iwncy_197",UKe="_noLabel_iwncy_210",ea={fieldRow:IKe,field:kKe,rightAlign:xKe,inputField:AKe,disabled:PKe,prefix:LKe,checkboxField:OKe,checkbox:MKe,description:DKe,errorMessage:NKe,noLabel:UKe},jKe=(t,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,...t},_.createElement("path",{d:"m20 6-11 11-5-5"})),FKe=_.forwardRef(jKe);class zle extends Error{constructor(e,n){super(n(e,{lng:"en"})),this.translatedMessage=n(e)}}class $Ke extends zle{}const sz=(t,e)=>new $Ke(t,e);function yt({children:t,rightAlign:e,className:n}){return E.jsx("div",{className:Oe(ea.fieldRow,{[ea.rightAlign]:e},n),children:t})}function BKe({children:t,className:e}){return E.jsx("div",{className:Oe(ea.field,e),children:t})}const Tn=({ref:t,id:e,label:n,className:r,type:i,checked:s,prefix:o,suffix:a,description:c,disabled:l,min:d,...h})=>{const m=_.useId();return E.jsxs(BKe,{className:Oe(i==="checkbox"?ea.checkboxField:ea.inputField,{[ea.prefix]:!!o,[ea.disabled]:l},r),children:[o&&E.jsx("span",{children:o}),i==="textarea"?E.jsx("textarea",{id:e,ref:t,disabled:l,"aria-describedby":m,...h}):E.jsx("input",{id:e,ref:t,type:i,checked:s,disabled:l,"aria-describedby":m,min:d,...h}),E.jsxs("label",{htmlFor:e,children:[i==="checkbox"&&E.jsx("div",{className:ea.checkbox,children:E.jsx(FKe,{})}),n]}),a&&E.jsx("span",{children:a}),c&&E.jsx("p",{id:m,className:n?ea.description:Oe(ea.description,ea.noLabel),children:c})]})};Tn.displayName="InputField";const Bf=({error:t})=>E.jsx("p",{className:ea.errorMessage,children:t instanceof zle?t.translatedMessage:t.message}),HKe="_avatarInputField_1ep5q_8",VKe="_avatar_1ep5q_8",qKe="_fileInput_1ep5q_17",GKe="_edit_1ep5q_21",_E={avatarInputField:HKe,avatar:VKe,fileInput:qKe,edit:GKe},Wle=({id:t,label:e,className:n,avatarUrl:r,userId:i,displayName:s,onRemoveAvatar:o,...a})=>{const{t:c}=We(),[l,d]=_.useState(!1),[h,m]=_.useState(void 0),[g,y]=_.useState(!1),v=_.useRef(null);_.useEffect(()=>{const R=v.current,x=T=>{const I=T;I.target.files&&I.target.files.length>0?(m(URL.createObjectURL(I.target.files[0])),d(!1)):m(void 0)};return R.addEventListener("change",x),()=>{R?.removeEventListener("change",x)}});const w=_.useCallback(()=>{v.current.click()},[v]),S=_.useCallback(()=>{d(!0),o()},[o]);return E.jsxs("div",{className:Oe(_E.avatarInputField,n),children:[E.jsx(Op,{id:i,className:_E.avatar,name:s,size:Lp.XL,src:l?void 0:h||r}),E.jsx("input",{id:t,accept:"image/*",ref:v,type:"file",className:_E.fileInput,role:"button","aria-label":e,...a}),E.jsx("div",{className:_E.edit,children:(r||h)&&!l?E.jsxs(qM,{title:c("action.edit"),showTitle:!1,open:g,onOpenChange:y,trigger:E.jsx(Bt,{iconOnly:!0,Icon:Qq,kind:"tertiary",size:"sm","aria-label":c("action.edit")}),children:[E.jsx(yv,{Icon:P8e,label:c("action.upload_file"),onSelect:w}),E.jsx(yv,{Icon:b8e,label:c("action.remove"),kind:"critical",onSelect:S})]}):E.jsx(Bt,{type:"button",iconOnly:!0,Icon:Qq,kind:"tertiary",size:"sm","aria-label":c("action.edit"),onClick:w})})]})};Wle.displayName="AvatarInputField";const KKe="_content_gj715_8",zKe="_avatarFieldRow_gj715_15",oz={content:KKe,avatarFieldRow:zKe},WKe=({client:t})=>{const{t:e}=We(),{error:n,displayName:r,avatarUrl:i,saveProfile:s}=V_(t),o=_.useMemo(()=>t.getUserId(),[t]),a=_.useRef(null),c=_.useRef(!1),l=_.useCallback(()=>{c.current=!0},[]),d=_.useRef(!1),h=_.useCallback(()=>{d.current=!0,c.current=!0},[]);return _.useEffect(()=>{const m=a.current;return()=>{if(c.current){const g=new FormData(m),y=g.get("displayName"),v=g.get("avatar"),w=typeof v=="string"?v.length:v?.size??0,S=typeof y=="string"?y:y?.name??null;if(!S)return;s({displayName:S,avatar:v&&w>0?v:void 0,removeAvatar:d.current&&(!v||w===0)}).catch(R=>{M.error("Failed to save profile",R)})}}},[s]),E.jsxs("form",{onChange:l,ref:a,className:oz.content,children:[E.jsx(yt,{className:oz.avatarFieldRow,children:o&&r&&E.jsx(Wle,{id:"avatar",name:"avatar",label:e("common.avatar"),avatarUrl:i,userId:o,displayName:r,onRemoveAvatar:h})}),E.jsx(yt,{children:E.jsx(Tn,{id:"userId",name:"userId",label:e("common.username"),type:"text",disabled:!0,value:t.getUserId()})}),E.jsx(yt,{children:E.jsx(Tn,{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"})}),n&&E.jsx(yt,{children:E.jsx(Bf,{error:n})})]})},YKe="_feedback_19yh9_8",Yle={feedback:YKe},Xle=()=>E.jsxs(Ys,{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(Jh,{href:"https://element.io/privacy",children:"Privacy Policy"})," ","and our"," ",E.jsx(Jh,{href:"https://element.io/cookie-policy",children:"Cookie Policy"}),"."]}),XKe=({roomId:t})=>{const{t:e}=We(),{submitRageshake:n,sending:r,sent:i,error:s,available:o}=hR(),a=TGe(),c=_.useCallback(h=>{h.preventDefault();const m=new FormData(h.target),g=m.get("description"),y=typeof g=="string"?g:"",v=!!m.get("sendLogs"),w=To(16);n({description:y,sendLogs:v,rageshakeRequestId:w,roomId:t}).catch(S=>{M.error("Failed to send feedback rageshake",S)}),t&&v&&a(t,w)},[n,t,a]);uR();const l=null,d=o?E.jsxs(E.Fragment,{children:[E.jsx("h4",{children:e("settings.feedback_tab_h4")}),E.jsx(an,{children:e("settings.feedback_tab_body")}),E.jsxs("form",{onSubmit:c,children:[E.jsx(yt,{children:E.jsx(Tn,{className:Yle.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(yt,{children:[E.jsx(Tn,{id:"sendLogs",name:"sendLogs",label:e("settings.feedback_tab_send_logs_label"),type:"checkbox",defaultChecked:!0}),E.jsx(Bt,{type:"submit",disabled:r,children:e(r?"submitting":"action.submit")})]}),E.jsxs(yt,{children:[s&&E.jsx(Bf,{error:s}),i&&E.jsx(an,{children:e("settings.feedback_tab_thank_you")})]})]})]}):null;return E.jsxs("div",{children:[l,d]})};var $w={exports:{}},JKe=$w.exports,az;function QKe(){return az||(az=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(JKe,function(){var e=function(){},n="undefined",r=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(v,w){var S=v[w];if(typeof S.bind=="function")return S.bind(v);try{return Function.prototype.bind.call(S,v)}catch{return function(){return Function.prototype.apply.apply(S,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&r?c:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<i.length;w++){var S=i[w];this[S]=w<v?e:this.methodFactory(S,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function h(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function m(v,w,S){return l(v)||h.apply(this,arguments)}function g(v,w){var S=this,R,x,T,I="loglevel";typeof v=="string"?I+=":"+v:typeof v=="symbol"&&(I=void 0);function k(U){var $=(i[U]||"silent").toUpperCase();if(!(typeof window===n||!I)){try{window.localStorage[I]=$;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+$+";"}catch{}}}function A(){var U;if(!(typeof window===n||!I)){try{U=window.localStorage[I]}catch{}if(typeof U===n)try{var $=window.document.cookie,K=encodeURIComponent(I),Y=$.indexOf(K+"=");Y!==-1&&(U=/^([^;]+)/.exec($.slice(Y+K.length+1))[1])}catch{}return S.levels[U]===void 0&&(U=void 0),U}}function O(){if(!(typeof window===n||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function D(U){var $=U;if(typeof $=="string"&&S.levels[$.toUpperCase()]!==void 0&&($=S.levels[$.toUpperCase()]),typeof $=="number"&&$>=0&&$<=S.levels.SILENT)return $;throw new TypeError("log.setLevel() called with invalid level: "+U)}S.name=v,S.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},S.methodFactory=w||m,S.getLevel=function(){return T??x??R},S.setLevel=function(U,$){return T=D(U),$!==!1&&k(T),d.call(S)},S.setDefaultLevel=function(U){x=D(U),A()||S.setLevel(U,!1)},S.resetLevel=function(){T=null,O(),d.call(S)},S.enableAll=function(U){S.setLevel(S.levels.TRACE,U)},S.disableAll=function(U){S.setLevel(S.levels.SILENT,U)},S.rebuild=function(){if(o!==S&&(R=D(o.getLevel())),d.call(S),o===S)for(var U in s)s[U].rebuild()},R=D(o?o.getLevel():"WARN");var N=A();N!=null&&(T=D(N)),d.call(S)}o=new g,o.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var S=s[w];return S||(S=s[w]=new g(w,o.methodFactory)),S};var y=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return s},o.default=o,o})}($w)),$w.exports}var ZKe=QKe();const eze=cl(ZKe);var tze=(t,e,n)=>new Promise((r,i)=>{var s=c=>{try{a(n.next(c))}catch(l){i(l)}},o=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);a((n=n.apply(t,e)).next())});function nze(t){return typeof t>"u"?!1:rze(t)||ize(t)}function rze(t){var e;return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&t.hasOwnProperty("track")&&typeof((e=t.publication)==null?void 0:e.track)<"u":!1}function ize(t){return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&t.hasOwnProperty("publication")&&typeof t.publication<"u":!1}function sze(t){return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&typeof t.publication>"u":!1}function oze(t){if(typeof t=="string"||typeof t=="number")return`${t}`;if(sze(t))return`${t.participant.identity}_${t.source}_placeholder`;if(nze(t))return`${t.participant.identity}_${t.publication.source}_${t.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${t}`)}var aze=[ue.ConnectionStateChanged,ue.RoomMetadataChanged,ue.ActiveSpeakersChanged,ue.ConnectionQualityChanged,ue.ParticipantConnected,ue.ParticipantDisconnected,ue.ParticipantPermissionsChanged,ue.ParticipantMetadataChanged,ue.ParticipantNameChanged,ue.ParticipantAttributesChanged,ue.TrackMuted,ue.TrackUnmuted,ue.TrackPublished,ue.TrackUnpublished,ue.TrackStreamStateChanged,ue.TrackSubscriptionFailed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionStatusChanged],cze=[...aze,ue.LocalTrackPublished,ue.LocalTrackUnpublished];ce.TrackPublished,ce.TrackUnpublished,ce.TrackMuted,ce.TrackUnmuted,ce.TrackStreamStateChanged,ce.TrackSubscribed,ce.TrackUnsubscribed,ce.TrackSubscriptionPermissionChanged,ce.TrackSubscriptionFailed,ce.LocalTrackPublished,ce.LocalTrackUnpublished;var lze=[ce.ConnectionQualityChanged,ce.IsSpeakingChanged,ce.ParticipantMetadataChanged,ce.ParticipantPermissionsChanged,ce.TrackMuted,ce.TrackUnmuted,ce.TrackPublished,ce.TrackUnpublished,ce.TrackStreamStateChanged,ce.TrackSubscriptionFailed,ce.TrackSubscriptionPermissionChanged,ce.TrackSubscriptionStatusChanged];[...lze,ce.LocalTrackPublished,ce.LocalTrackUnpublished];var uze=eze.getLogger("lk-components-js");uze.setDefaultLevel("WARN");function dze(t,...e){return new Wn(r=>{const i=()=>{r.next(t)};return e.forEach(o=>{t.on(o,i)}),()=>{e.forEach(o=>{t.off(o,i)})}}).pipe(dn(t))}function fze(t,e){return new Wn(r=>{const i=(...o)=>{r.next(o)};return t.on(e,i),()=>{t.off(e,i)}})}function cz(t,e,n=!0){const r=new Wn(s=>{xu.getLocalDevices(t,n).then(o=>{s.next(o),s.complete()}).catch(o=>{e?.(o),s.next([]),s.complete()})}),i=new Wn(s=>{var o;const a=()=>tze(this,null,function*(){try{const c=yield xu.getLocalDevices(t,n);s.next(c)}catch(c){e?.(c)}});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");(o=navigator?.mediaDevices)==null||o.addEventListener("devicechange",a)}return()=>{var c;(c=navigator?.mediaDevices)==null||c.removeEventListener("devicechange",a)}});return mp(r,i)}function Y8(t,...e){return new Wn(r=>{const i=()=>{r.next(t)};return e.forEach(o=>{t.on(o,i)}),()=>{e.forEach(o=>{t.off(o,i)})}}).pipe(dn(t))}function X8(t){return Y8(t,ce.TrackMuted,ce.TrackUnmuted,ce.ParticipantPermissionsChanged,ce.TrackPublished,ce.TrackUnpublished,ce.LocalTrackPublished,ce.LocalTrackUnpublished,ce.MediaDevicesError,ce.TrackSubscriptionStatusChanged).pipe(Re(n=>{const{isMicrophoneEnabled:r,isCameraEnabled:i,isScreenShareEnabled:s}=n,o=n.getTrackPublication(he.Source.Microphone),a=n.getTrackPublication(he.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:r,isScreenShareEnabled:s,cameraTrack:a,microphoneTrack:o,participant:n}}))}function hze(t,e={}){var n;let r;const i=new Wn(c=>(r=c,()=>a.unsubscribe())).pipe(dn(Array.from(t.remoteParticipants.values()))),s=(n=e.additionalRoomEvents)!=null?n:cze,o=Array.from(new Set([ue.ParticipantConnected,ue.ParticipantDisconnected,ue.ConnectionStateChanged,...s])),a=dze(t,...o).subscribe(c=>r?.next(Array.from(c.remoteParticipants.values())));return t.remoteParticipants.size>0&&r?.next(Array.from(t.remoteParticipants.values())),i}const sg=new ii,Jle=new ii,Qle=new ii,VL=new ii;let lz=!1;const Zle=()=>{lz||(lz=!0,window.controls.onAudioPlaybackStarted?.())};window.controls={canEnterPip(){return sg.observed},enablePip(){if(!sg.observed)throw new Error("No call is running");sg.next(!0)},disablePip(){if(!sg.observed)throw new Error("No call is running");sg.next(!1)},setAvailableAudioDevices(t){M.info("setAvailableAudioDevices called from native:",t),Jle.next(t)},setAudioDevice(t){M.info("setAudioDevice called from native",t),Qle.next(t)},setAudioEnabled(t){if(M.info("setAudioEnabled called from native:",t),!VL.observed)throw new Error("Output controls are disabled. No setAudioEnabled$ observer");VL.next(t)},setOutputEnabled(t){this.setAudioEnabled(t)},setAvailableOutputDevices(t){this.setAvailableAudioDevices(t)},setOutputDevice(t){this.setAudioDevice(t)}};const b3=Symbol("nothing");function pze(t){return e=>Gqe(()=>{let n=b3;return e.pipe(vGe(r=>n=r),fGe(()=>{n!==b3&&t(n)}))})}function qL(t,e){return n=>n.pipe(ql(e,t),dn(t))}const uz=Symbol("switch");function mze(t,e){return n=>mp(n.pipe(Re((r,i)=>t(r,i)?uz:r),gGe(r=>r!==uz)),e)}function Bw(t){let e=b3;if(t.subscribe(n=>e=n).unsubscribe(),e===b3)throw new Error("Not a state Observable");return e}function dz(...t){return Xt(t,(...e)=>e.every(n=>n))}function z1(t){return e=>e.pipe(Tle(t),wle(([,n])=>n?t.pipe(es(r=>!r)):Ct(null)),Re(([n])=>n))}function eue(t){return new _s(t)}const fz="earpiece-id",tue=va==="ios"?eue(!0):Dle.value$;function mR(t,e,n,r){const i=a=>r.error("Error creating MediaDeviceObserver",a),s=cz(t,i,!1),o=cz(t,i,!0);return n.behavior(e.pipe(Ot(a=>a?s.pipe(mze((c,l)=>l===0&&c.every(d=>!d.label),o)):s)),[])}function J8(t){return new Map(t.map((e,n)=>[e.deviceId,e.label?{type:"name",name:e.label}:{type:"number",number:n+1}]))}function Q8(t,e){return Xt([t,e],(n,r)=>{if(n.size)return r!==void 0&&n.has(r)||n.size===1&&n.has("")?r:n.keys().next().value})}class gze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices AudioInput]"),this.availableRaw$=mR("audioinput",this.usingNames$,this.scope,this.logger),this.available$=this.scope.behavior(this.availableRaw$.pipe(Re(J8))),this.selected$=this.scope.behavior(Q8(this.available$,WK.value$).pipe(Re(r=>r===void 0?void 0:{id:r,hardwareDeviceChange$:this.availableRaw$.pipe(Re(i=>i.find(s=>s.deviceId===r)?.groupId),jw(),es(([i,s])=>i!==s),Re(()=>{}))}))),this.available$.subscribe(r=>{this.logger.info("[audio-input] available devices:",r)})}select(e){WK.setValue(e)}}class vze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices AudioOutput]"),this.available$=this.scope.behavior(mR("audiooutput",this.usingNames$,this.scope,this.logger).pipe(Re(r=>{let i=J8(r);return i.size&&!i.has("")&&!i.has("default")&&i.set("",{type:"default",name:r[0]?.label||null}),!!window.GestureEvent&&(i=new Map),i}))),this.selected$=this.scope.behavior(Q8(this.available$,YK.value$).pipe(Re(r=>r===void 0?void 0:{id:r,virtualEarpiece:!1}))),this.available$.subscribe(r=>{this.logger.info("[audio-output] available devices:",r)})}select(e){YK.setValue(e)}}class yze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices ControlledAudioOutput]"),this.availableRaw$=mR("audiooutput",this.usingNames$,this.scope,this.logger),this.available$=this.scope.behavior(Xt([Jle.pipe(dn([])),tue],(r,i)=>{const s=new Map(r.map(({id:o,name:a,isEarpiece:c,isSpeaker:l})=>{let d;return c?d={type:"earpiece"}:l?d={type:"speaker"}:d={type:"name",name:a},[o,d]}));return i&&r.some(o=>o.forEarpiece)&&s.set(fz,{type:"earpiece"}),s})),this.deviceSelection$=new ii,this.selected$=this.scope.behavior(Xt([this.available$,H_(Qle.pipe(dn(void 0)),this.deviceSelection$)],(r,i)=>{const s=i??r.keys().next().value;return s===void 0?void 0:{id:s,virtualEarpiece:s===fz}})),this.selected$.subscribe(r=>{r!==void 0&&(this.logger.info("[controlled-output] onAudioDeviceSelect called:",r),window.controls.onAudioDeviceSelect?.(r.id),window.controls.onOutputDeviceSelect?.(r.id))}),this.available$.subscribe(r=>{this.logger.info("[controlled-output] available devices:",r)}),this.availableRaw$.subscribe(r=>{this.logger.info("[controlled-output] available raw devices:",r)})}select(e){this.deviceSelection$.next(e)}}class bze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices VideoInput]"),this.available$=this.scope.behavior(mR("videoinput",this.usingNames$,this.scope,this.logger).pipe(Re(J8))),this.selected$=this.scope.behavior(Q8(this.available$,XK.value$).pipe(Re(r=>r===void 0?void 0:{id:r}))),this.available$.subscribe(r=>{this.logger.info("[video-input] available devices:",r)})}select(e){XK.setValue(e)}}class _ze{constructor(e){this.scope=e,this.deviceNamesRequest$=new ii,this.usingNames$=this.scope.behavior(this.deviceNamesRequest$.pipe(Re(()=>!0)),!1),this.audioInput=new gze(this.usingNames$,this.scope),this.audioOutput=Br().controlledAudioDevices?new yze(this.usingNames$,this.scope):new vze(this.usingNames$,this.scope),this.videoInput=new bze(this.usingNames$,this.scope)}requestDeviceNames(){this.deviceNamesRequest$.next()}}function Sze(t,e,n){if(!n)return _.useState(e)[0];const[r]=_.useState(()=>new _s(n)),[i]=_.useState(()=>e(r)),s=_.useRef(!0);return t(()=>{if(s.current){s.current=!1;return}r.next(n)},n),i}function Z8(t,e){return Sze(_.useEffect,t,e)}var Eze=t=>t+1|0,wze=()=>{const t=_.useState(0)[1];return _.useRef(()=>t(Eze)).current},nue=typeof window>"u"?_.useEffect:_.useLayoutEffect,hz=t=>t[1]?.next?t[1]:{next:t[1],error:t[2],complete:t[3]};function Cze(t,e){const n=_.useRef(e),r=_.useRef(),i=_.useRef();return nue(()=>{n.current=e,r.current=hz(e)}),t(()=>{const s=n.current[0];r.current||(r.current=hz(n.current));const o=s.subscribe({next:a=>{s===n.current[0]&&r.current.next?.(a)},error:a=>{s===n.current[0]&&(r.current.error?r.current.error(a):console.error(a))},complete:()=>{s===n.current[0]&&r.current.complete?.()}});return i.current=o,()=>{o.unsubscribe()}},[e[0]]),i}function Tze(t,e,n,r){return Cze(_.useEffect,[t,e,n,r])}function ai(t){const e=wze(),n=_.useRef(t),r=_.useRef(),i=_.useRef(!1),s=_.useRef(!1),[o,a]=_.useState(()=>{let c;return t.subscribe({next:l=>{s.current=!0,c=l},error:l=>{r.current=l}}).unsubscribe(),c});if(nue(()=>{n.current=t}),_.useEffect(()=>{r.current=null;const c=n.current;let l=o;const d=c.subscribe({next:h=>{c===n.current&&(i.current?a(()=>h):l=h)},error:h=>{c===n.current&&(r.current=h,e())}});return i.current||l!==o&&a(()=>l),i.current=!0,()=>{d.unsubscribe()}},[t]),r.current)throw r.current;if(s.current)return _.useDebugValue(o),o;throw new Error("Observable did not synchronously emit a value.")}function Rze(t){const[e]=_.useState(()=>new _s(t)),[n]=_.useState(()=>({get current(){return e.value},set current(r){e.next(r)}}));return[n,e]}const rue=_.createContext(void 0);function Wu(){const t=_.use(rue);if(t===void 0)throw new Error("useMediaDevices must be used within a MediaDevices context provider");return t}const Ize=()=>{const t=Wu(),e=ai(t.audioOutput.selected$),n=ai(t.audioOutput.available$);return e?.id?n.get(e.id)?.type==="earpiece":!1},iue=()=>{const t=Wu(),n=ai(t.audioOutput.selected$)?.virtualEarpiece??!1;return{pan:_.useMemo(()=>n?1:0,[n]),volume:_.useMemo(()=>n?.1:1,[n])}},kze=()=>{const{t}=We(),[e,n]=Gn(Ale),[r,i]=Gn(Ple),[s,o]=Gn(H8),a=(d,h)=>{h(d.target.checked)},[c,l]=Gn($8);return E.jsxs("div",{children:[E.jsx(an,{children:t("settings.preferences_tab.introduction")}),E.jsx(yt,{children:E.jsx(Tn,{id:"showHandRaisedTimer",label:t("settings.preferences_tab.show_hand_raised_timer_label"),description:t("settings.preferences_tab.show_hand_raised_timer_description"),type:"checkbox",checked:e,onChange:d=>a(d,n)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"showReactions",label:t("settings.preferences_tab.reactions_show_label"),description:t("settings.preferences_tab.reactions_show_description"),type:"checkbox",checked:r,onChange:d=>a(d,i)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"playReactionSound",label:t("settings.preferences_tab.reactions_play_sound_label"),description:t("settings.preferences_tab.reactions_play_sound_description"),type:"checkbox",checked:s,onChange:d=>a(d,o)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"developerSettingsTab",type:"checkbox",checked:c,label:t("settings.preferences_tab.developer_mode_label"),description:t("settings.preferences_tab.developer_mode_label_description"),onChange:d=>l(d.target.checked)})})]})};function sue(t,[e,n]){return Math.min(n,Math.max(e,t))}function yg(t,e,{checkForDefaultPrevented:n=!0}={}){return function(i){if(t?.(i),n===!1||!i.defaultPrevented)return e?.(i)}}function pz(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function oue(...t){return e=>{let n=!1;const r=t.map(i=>{const s=pz(i,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():pz(t[i],null)}}}}function Rf(...t){return _.useCallback(oue(...t),t)}function aue(t,e=[]){let n=[];function r(s,o){const a=_.createContext(o),c=n.length;n=[...n,o];const l=h=>{const{scope:m,children:g,...y}=h,v=m?.[t]?.[c]||a,w=_.useMemo(()=>y,Object.values(y));return E.jsx(v.Provider,{value:w,children:g})};l.displayName=s+"Provider";function d(h,m){const g=m?.[t]?.[c]||a,y=_.useContext(g);if(y)return y;if(o!==void 0)return o;throw new Error(`\`${h}\` must be used within \`${s}\``)}return[l,d]}const i=()=>{const s=n.map(o=>_.createContext(o));return function(a){const c=a?.[t]||s;return _.useMemo(()=>({[`__scope${t}`]:{...a,[t]:c}}),[a,c])}};return i.scopeName=t,[r,xze(i,...e)]}function xze(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(s){const o=r.reduce((a,{useScope:c,scopeName:l})=>{const h=c(s)[`__scope${l}`];return{...a,...h}},{});return _.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}var Aze=m_[" useInsertionEffect ".trim().toString()]||up;function Pze({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){const[i,s,o]=Lze({defaultProp:e,onChange:n}),a=t!==void 0,c=a?t:i;{const d=_.useRef(t!==void 0);_.useEffect(()=>{const h=d.current;h!==a&&console.warn(`${r} is changing from ${h?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const l=_.useCallback(d=>{if(a){const h=Oze(d)?d(t):d;h!==t&&o.current?.(h)}else s(d)},[a,t,s,o]);return[c,l]}function Lze({defaultProp:t,onChange:e}){const[n,r]=_.useState(t),i=_.useRef(n),s=_.useRef(e);return Aze(()=>{s.current=e},[e]),_.useEffect(()=>{i.current!==n&&(s.current?.(n),i.current=n)},[n,i]),[n,r,s]}function Oze(t){return typeof t=="function"}var Mze=_.createContext(void 0);function Dze(t){const e=_.useContext(Mze);return t||e||"ltr"}function Nze(t){const e=_.useRef({value:t,previous:t});return _.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}function Uze(t){const[e,n]=_.useState(void 0);return up(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;o=l.inlineSize,a=l.blockSize}else o=t.offsetWidth,a=t.offsetHeight;n({width:o,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}function GL(t){const e=jze(t),n=_.forwardRef((r,i)=>{const{children:s,...o}=r,a=_.Children.toArray(s),c=a.find($ze);if(c){const l=c.props.children,d=a.map(h=>h===c?_.Children.count(l)>1?_.Children.only(null):_.isValidElement(l)?l.props.children:null:h);return E.jsx(e,{...o,ref:i,children:_.isValidElement(l)?_.cloneElement(l,void 0,d):null})}return E.jsx(e,{...o,ref:i,children:s})});return n.displayName=`${t}.Slot`,n}function jze(t){const e=_.forwardRef((n,r)=>{const{children:i,...s}=n;if(_.isValidElement(i)){const o=Hze(i),a=Bze(s,i.props);return i.type!==_.Fragment&&(a.ref=r?oue(r,o):o),_.cloneElement(i,a)}return _.Children.count(i)>1?_.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Fze=Symbol("radix.slottable");function $ze(t){return _.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Fze}function Bze(t,e){const n={...e};for(const r in e){const i=t[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...a)=>{const c=s(...a);return i(...a),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...t,...n}}function Hze(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Vze=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],q_=Vze.reduce((t,e)=>{const n=GL(`Primitive.${e}`),r=_.forwardRef((i,s)=>{const{asChild:o,...a}=i,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function qze(t){const e=t+"CollectionProvider",[n,r]=aue(e),[i,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),o=v=>{const{scope:w,children:S}=v,R=Ce.useRef(null),x=Ce.useRef(new Map).current;return E.jsx(i,{scope:w,itemMap:x,collectionRef:R,children:S})};o.displayName=e;const a=t+"CollectionSlot",c=GL(a),l=Ce.forwardRef((v,w)=>{const{scope:S,children:R}=v,x=s(a,S),T=Rf(w,x.collectionRef);return E.jsx(c,{ref:T,children:R})});l.displayName=a;const d=t+"CollectionItemSlot",h="data-radix-collection-item",m=GL(d),g=Ce.forwardRef((v,w)=>{const{scope:S,children:R,...x}=v,T=Ce.useRef(null),I=Rf(w,T),k=s(d,S);return Ce.useEffect(()=>(k.itemMap.set(T,{ref:T,...x}),()=>void k.itemMap.delete(T))),E.jsx(m,{[h]:"",ref:I,children:R})});g.displayName=d;function y(v){const w=s(t+"CollectionConsumer",v);return Ce.useCallback(()=>{const R=w.collectionRef.current;if(!R)return[];const x=Array.from(R.querySelectorAll(`[${h}]`));return Array.from(w.itemMap.values()).sort((k,A)=>x.indexOf(k.ref.current)-x.indexOf(A.ref.current))},[w.collectionRef,w.itemMap])}return[{Provider:o,Slot:l,ItemSlot:g},y,r]}var cue=["PageUp","PageDown"],lue=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],uue={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},i0="Slider",[KL,Gze,Kze]=qze(i0),[due,zat]=aue(i0,[Kze]),[zze,gR]=due(i0),fue=_.forwardRef((t,e)=>{const{name:n,min:r=0,max:i=100,step:s=1,orientation:o="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:l=[r],value:d,onValueChange:h=()=>{},onValueCommit:m=()=>{},inverted:g=!1,form:y,...v}=t,w=_.useRef(new Set),S=_.useRef(0),x=o==="horizontal"?Wze:Yze,[T=[],I]=Pze({prop:d,defaultProp:l,onChange:U=>{[...w.current][S.current]?.focus(),h(U)}}),k=_.useRef(T);function A(U){const $=eWe(T,U);N(U,$)}function O(U){N(U,S.current)}function D(){const U=k.current[S.current];T[S.current]!==U&&m(T)}function N(U,$,{commit:K}={commit:!1}){const Y=iWe(s),G=sWe(Math.round((U-r)/s)*s+r,Y),F=sue(G,[r,i]);I((q=[])=>{const z=Qze(q,F,$);if(rWe(z,c*s)){S.current=z.indexOf(F);const W=String(z)!==String(q);return W&&K&&m(z),W?z:q}else return q})}return E.jsx(zze,{scope:t.__scopeSlider,name:n,disabled:a,min:r,max:i,valueIndexToChangeRef:S,thumbs:w.current,values:T,orientation:o,form:y,children:E.jsx(KL.Provider,{scope:t.__scopeSlider,children:E.jsx(KL.Slot,{scope:t.__scopeSlider,children:E.jsx(x,{"aria-disabled":a,"data-disabled":a?"":void 0,...v,ref:e,onPointerDown:yg(v.onPointerDown,()=>{a||(k.current=T)}),min:r,max:i,inverted:g,onSlideStart:a?void 0:A,onSlideMove:a?void 0:O,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&N(r,0,{commit:!0}),onEndKeyDown:()=>!a&&N(i,T.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:$})=>{if(!a){const G=cue.includes(U.key)||U.shiftKey&&lue.includes(U.key)?10:1,F=S.current,q=T[F],z=s*G*$;N(q+z,F,{commit:!0})}}})})})})});fue.displayName=i0;var[hue,pue]=due(i0,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Wze=_.forwardRef((t,e)=>{const{min:n,max:r,dir:i,inverted:s,onSlideStart:o,onSlideMove:a,onSlideEnd:c,onStepKeyDown:l,...d}=t,[h,m]=_.useState(null),g=Rf(e,x=>m(x)),y=_.useRef(void 0),v=Dze(i),w=v==="ltr",S=w&&!s||!w&&s;function R(x){const T=y.current||h.getBoundingClientRect(),I=[0,T.width],A=e9(I,S?[n,r]:[r,n]);return y.current=T,A(x-T.left)}return E.jsx(hue,{scope:t.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width",children:E.jsx(mue,{dir:v,"data-orientation":"horizontal",...d,ref:g,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{const T=R(x.clientX);o?.(T)},onSlideMove:x=>{const T=R(x.clientX);a?.(T)},onSlideEnd:()=>{y.current=void 0,c?.()},onStepKeyDown:x=>{const I=uue[S?"from-left":"from-right"].includes(x.key);l?.({event:x,direction:I?-1:1})}})})}),Yze=_.forwardRef((t,e)=>{const{min:n,max:r,inverted:i,onSlideStart:s,onSlideMove:o,onSlideEnd:a,onStepKeyDown:c,...l}=t,d=_.useRef(null),h=Rf(e,d),m=_.useRef(void 0),g=!i;function y(v){const w=m.current||d.current.getBoundingClientRect(),S=[0,w.height],x=e9(S,g?[r,n]:[n,r]);return m.current=w,x(v-w.top)}return E.jsx(hue,{scope:t.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:E.jsx(mue,{"data-orientation":"vertical",...l,ref:h,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:v=>{const w=y(v.clientY);s?.(w)},onSlideMove:v=>{const w=y(v.clientY);o?.(w)},onSlideEnd:()=>{m.current=void 0,a?.()},onStepKeyDown:v=>{const S=uue[g?"from-bottom":"from-top"].includes(v.key);c?.({event:v,direction:S?-1:1})}})})}),mue=_.forwardRef((t,e)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:i,onSlideEnd:s,onHomeKeyDown:o,onEndKeyDown:a,onStepKeyDown:c,...l}=t,d=gR(i0,n);return E.jsx(q_.span,{...l,ref:e,onKeyDown:yg(t.onKeyDown,h=>{h.key==="Home"?(o(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):cue.concat(lue).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:yg(t.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),d.thumbs.has(m)?m.focus():r(h)}),onPointerMove:yg(t.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&i(h)}),onPointerUp:yg(t.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),s(h))})})}),gue="SliderTrack",vue=_.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,i=gR(gue,n);return E.jsx(q_.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...r,ref:e})});vue.displayName=gue;var zL="SliderRange",yue=_.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,i=gR(zL,n),s=pue(zL,n),o=_.useRef(null),a=Rf(e,o),c=i.values.length,l=i.values.map(m=>Sue(m,i.min,i.max)),d=c>1?Math.min(...l):0,h=100-Math.max(...l);return E.jsx(q_.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...r,ref:a,style:{...t.style,[s.startEdge]:d+"%",[s.endEdge]:h+"%"}})});yue.displayName=zL;var WL="SliderThumb",bue=_.forwardRef((t,e)=>{const n=Gze(t.__scopeSlider),[r,i]=_.useState(null),s=Rf(e,a=>i(a)),o=_.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return E.jsx(Xze,{...t,ref:s,index:o})}),Xze=_.forwardRef((t,e)=>{const{__scopeSlider:n,index:r,name:i,...s}=t,o=gR(WL,n),a=pue(WL,n),[c,l]=_.useState(null),d=Rf(e,R=>l(R)),h=c?o.form||!!c.closest("form"):!0,m=Uze(c),g=o.values[r],y=g===void 0?0:Sue(g,o.min,o.max),v=Zze(r,o.values.length),w=m?.[a.size],S=w?tWe(w,y,a.direction):0;return _.useEffect(()=>{if(c)return o.thumbs.add(c),()=>{o.thumbs.delete(c)}},[c,o.thumbs]),E.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${y}% + ${S}px)`},children:[E.jsx(KL.ItemSlot,{scope:t.__scopeSlider,children:E.jsx(q_.span,{role:"slider","aria-label":t["aria-label"]||v,"aria-valuemin":o.min,"aria-valuenow":g,"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:d,style:g===void 0?{display:"none"}:t.style,onFocus:yg(t.onFocus,()=>{o.valueIndexToChangeRef.current=r})})}),h&&E.jsx(_ue,{name:i??(o.name?o.name+(o.values.length>1?"[]":""):void 0),form:o.form,value:g},r)]})});bue.displayName=WL;var Jze="RadioBubbleInput",_ue=_.forwardRef(({__scopeSlider:t,value:e,...n},r)=>{const i=_.useRef(null),s=Rf(i,r),o=Nze(e);return _.useEffect(()=>{const a=i.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==e&&d){const h=new Event("input",{bubbles:!0});d.call(a,e),a.dispatchEvent(h)}},[o,e]),E.jsx(q_.input,{style:{display:"none"},...n,ref:s,defaultValue:e})});_ue.displayName=Jze;function Qze(t=[],e,n){const r=[...t];return r[n]=e,r.sort((i,s)=>i-s)}function Sue(t,e,n){const s=100/(n-e)*(t-e);return sue(s,[0,100])}function Zze(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function eWe(t,e){if(t.length===1)return 0;const n=t.map(i=>Math.abs(i-e)),r=Math.min(...n);return n.indexOf(r)}function tWe(t,e,n){const r=t/2,s=e9([0,50],[0,r]);return(r-s(e)*n)*n}function nWe(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}function rWe(t,e){if(e>0){const n=nWe(t);return Math.min(...n)>=e}return!0}function e9(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function iWe(t){return(String(t).split(".")[1]||"").length}function sWe(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}var oWe=fue,aWe=vue,cWe=yue,lWe=bue;const uWe="_slider_15go1_8",dWe="_track_15go1_14",fWe="_highlight_15go1_31",hWe="_handle_15go1_43",SE={slider:uWe,track:dWe,highlight:fWe,handle:hWe},Eue=({className:t,label:e,value:n,onValueChange:r,onValueCommit:i,min:s,max:o,step:a,disabled:c})=>{const l=_.useCallback(([h])=>r(h),[r]),d=_.useCallback(([h])=>i?.(h),[i]);return E.jsxs(oWe,{className:Oe(t,SE.slider),value:[n],onValueChange:l,onValueCommit:d,min:s,max:o,step:a,disabled:c,children:[E.jsx(aWe,{className:SE.track,children:E.jsx(cWe,{className:SE.highlight})}),E.jsx(qi,{placement:"top",label:Math.round(n*100).toString()+"%",children:E.jsx(lWe,{className:SE.handle,"aria-label":e})})]})},pWe="_selection_1akwb_1",mWe="_title_1akwb_5",gWe="_separator_1akwb_10",vWe="_options_1akwb_14",yWe="_secondary_1akwb_20",W1={selection:pWe,title:mWe,separator:gWe,options:vWe,secondary:yWe},Ux=({device:t,title:e,numberedLabel:n})=>{const{t:r}=We(),i=_.useId(),s=ai(t.available$),o=ai(t.selected$)?.id,a=_.useCallback(c=>{t.select(c.target.value)},[t]);return s.size<=1?null:E.jsxs("div",{className:W1.selection,children:[E.jsx(gl,{type:"body",weight:"semibold",size:"sm",as:"h4",className:W1.title,children:e}),E.jsx(QM,{className:W1.separator}),E.jsx("div",{className:W1.options,children:[...s].map(([c,l])=>{let d;switch(l.type){case"name":d=l.name;break;case"number":d=n(l.number);break;case"default":d=l.name===null?r("settings.devices.default"):E.jsxs(Ys,{i18nKey:"settings.devices.default_named",name:l.name,children:["Default"," ",E.jsxs("span",{className:W1.secondary,children:["(",{name:l.name},")"]})]});break;case"speaker":d=r("settings.devices.loudspeaker");break;case"earpiece":d=r("settings.devices.handset");break}return E.jsx(RMe,{name:i,control:E.jsx(hMe,{checked:c===o,onChange:a,value:c}),children:E.jsx(gMe,{children:d})},c)})})]})};var vp=typeof self<"u"?self:{};function Sh(){throw Error("Invalid UTF8")}function mz(t,e){return e=String.fromCharCode.apply(null,e),t==null?e:t+e}let EE,jx;const bWe=typeof TextDecoder<"u";let _We;const SWe=typeof TextEncoder<"u";function wue(t){if(SWe)t=(_We||=new TextEncoder).encode(t);else{let n=0;const r=new Uint8Array(3*t.length);for(let i=0;i<t.length;i++){var e=t.charCodeAt(i);if(e<128)r[n++]=e;else{if(e<2048)r[n++]=e>>6|192;else{if(e>=55296&&e<=57343){if(e<=56319&&i<t.length){const s=t.charCodeAt(++i);if(s>=56320&&s<=57343){e=1024*(e-55296)+s-56320+65536,r[n++]=e>>18|240,r[n++]=e>>12&63|128,r[n++]=e>>6&63|128,r[n++]=63&e|128;continue}i--}e=65533}r[n++]=e>>12|224,r[n++]=e>>6&63|128}r[n++]=63&e|128}}t=n===r.length?r:r.subarray(0,n)}return t}var t9,_3;e:{for(var gz=["CLOSURE_FLAGS"],Fx=vp,$x=0;$x<gz.length;$x++)if((Fx=Fx[gz[$x]])==null){_3=null;break e}_3=Fx}var Wb,vz=_3&&_3[610401301];t9=vz!=null&&vz;const yz=vp.navigator;function YL(t){return!!t9&&!!Wb&&Wb.brands.some(({brand:e})=>e&&e.indexOf(t)!=-1)}function ia(t){var e;return(e=vp.navigator)&&(e=e.userAgent)||(e=""),e.indexOf(t)!=-1}function Bd(){return!!t9&&!!Wb&&Wb.brands.length>0}function Bx(){return Bd()?YL("Chromium"):(ia("Chrome")||ia("CriOS"))&&!(!Bd()&&ia("Edge"))||ia("Silk")}function n9(t){return n9[" "](t),t}Wb=yz&&yz.userAgentData||null,n9[" "]=function(){};var EWe=!Bd()&&(ia("Trident")||ia("MSIE"));!ia("Android")||Bx(),Bx(),ia("Safari")&&(Bx()||!Bd()&&ia("Coast")||!Bd()&&ia("Opera")||!Bd()&&ia("Edge")||(Bd()?YL("Microsoft Edge"):ia("Edg/"))||Bd()&&YL("Opera"));var Cue={},by=null;function wWe(t){const e=t.length;let n=3*e/4;n%3?n=Math.floor(n):"=.".indexOf(t[e-1])!=-1&&(n="=.".indexOf(t[e-2])!=-1?n-2:n-1);const r=new Uint8Array(n);let i=0;return function(s,o){function a(l){for(;c<s.length;){const d=s.charAt(c++),h=by[d];if(h!=null)return h;if(!/^[\s\xa0]*$/.test(d))throw Error("Unknown base64 encoding at char: "+d)}return l}Tue();let c=0;for(;;){const l=a(-1),d=a(0),h=a(64),m=a(64);if(m===64&&l===-1)break;o(l<<2|d>>4),h!=64&&(o(d<<4&240|h>>2),m!=64&&o(h<<6&192|m))}}(t,function(s){r[i++]=s}),i!==n?r.subarray(0,i):r}function Tue(){if(!by){by={};var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),e=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=t.concat(e[n].split(""));Cue[n]=r;for(let i=0;i<r.length;i++){const s=r[i];by[s]===void 0&&(by[s]=i)}}}}var Rue=typeof Uint8Array<"u",Iue=!EWe&&typeof btoa=="function";function bz(t){if(!Iue){var e;e===void 0&&(e=0),Tue(),e=Cue[e];var n=Array(Math.floor(t.length/3)),r=e[64]||"";let c=0,l=0;for(;c<t.length-2;c+=3){var i=t[c],s=t[c+1],o=t[c+2],a=e[i>>2];i=e[(3&i)<<4|s>>4],s=e[(15&s)<<2|o>>6],o=e[63&o],n[l++]=a+i+s+o}switch(a=0,o=r,t.length-c){case 2:o=e[(15&(a=t[c+1]))<<2]||r;case 1:t=t[c],n[l]=e[t>>2]+e[(3&t)<<4|a>>4]+o+r}return n.join("")}for(e="",n=0,r=t.length-10240;n<r;)e+=String.fromCharCode.apply(null,t.subarray(n,n+=10240));return e+=String.fromCharCode.apply(null,n?t.subarray(n):t),btoa(e)}const _z=/[-_.]/g,CWe={"-":"+",_:"/",".":"="};function TWe(t){return CWe[t]||""}function kue(t){if(!Iue)return wWe(t);_z.test(t)&&(t=t.replace(_z,TWe)),t=atob(t);const e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}function G_(t){return Rue&&t!=null&&t instanceof Uint8Array}var Cv={};function yp(){return RWe||=new Tu(null,Cv)}function r9(t){xue(Cv);var e=t.g;return(e=e==null||G_(e)?e:typeof e=="string"?kue(e):null)==null?e:t.g=e}var Tu=class{h(){return new Uint8Array(r9(this)||0)}constructor(t,e){if(xue(e),this.g=t,t!=null&&t.length===0)throw Error("ByteString should be constructed with non-empty values")}};let RWe,IWe;function xue(t){if(t!==Cv)throw Error("illegal external caller")}function Aue(t,e){t.__closure__error__context__984382||(t.__closure__error__context__984382={}),t.__closure__error__context__984382.severity=e}function XL(t){return Aue(t=Error(t),"warning"),t}var vR=typeof Symbol=="function"&&typeof Symbol()=="symbol",kWe=new Set;function K_(t,e,n=!1,r=!1){return t=typeof Symbol=="function"&&typeof Symbol()=="symbol"?r&&Symbol.for&&t?Symbol.for(t):t!=null?Symbol(t):Symbol():e,n&&kWe.add(t),t}var xWe=K_("jas",void 0,!0,!0),Sz=K_(void 0,"0di"),Hx=K_(void 0,"2ex"),Y1=K_(void 0,"1oa",!0),Tv=K_(void 0,Symbol(),!0);const ze=vR?xWe:"Ga",Pue={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},Lue=Object.defineProperties;function yR(t,e){vR||ze in t||Lue(t,Pue),t[ze]|=e}function $r(t,e){vR||ze in t||Lue(t,Pue),t[ze]=e}function s0(t){return yR(t,34),t}function AWe(t,e){$r(e,-30975&(0|t))}function JL(t,e){$r(e,-30941&(34|t))}function i9(){return typeof BigInt=="function"}function Js(t){return Array.prototype.slice.call(t)}var s9,z_={},Oue={};function Ez(t){return!(!t||typeof t!="object"||t.Ia!==Oue)}function o9(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&t.constructor===Object}function a9(t,e){if(t!=null){if(typeof t=="string")t=t?new Tu(t,Cv):yp();else if(t.constructor!==Tu)if(G_(t))t=t.length?new Tu(new Uint8Array(t),Cv):yp();else{if(!e)throw Error();t=void 0}}return t}function S3(t){return!(!Array.isArray(t)||t.length)&&!!(1&(0|t[ze]))}const wz=[];function Hf(t){if(2&t)throw Error()}$r(wz,55),s9=Object.freeze(wz);let Cz=class Mue{constructor(e,n,r){this.l=0,this.g=e,this.h=n,this.m=r}next(){if(this.l<this.g.length){const e=this.g[this.l++];return{done:!1,value:this.h?this.h.call(this.m,e):e}}return{done:!0,value:void 0}}[Symbol.iterator](){return new Mue(this.g,this.h,this.m)}};function c9(t){return Tv?t[Tv]:void 0}var PWe=Object.freeze({});function bR(t){return t.Qa=!0,t}var LWe=bR(t=>typeof t=="number"),Tz=bR(t=>typeof t=="string"),OWe=bR(t=>typeof t=="boolean"),_R=typeof vp.BigInt=="function"&&typeof vp.BigInt(0)=="bigint",QL=bR(t=>_R?t>=DWe&&t<=UWe:t[0]==="-"?Rz(t,MWe):Rz(t,NWe));const MWe=Number.MIN_SAFE_INTEGER.toString(),DWe=_R?BigInt(Number.MIN_SAFE_INTEGER):void 0,NWe=Number.MAX_SAFE_INTEGER.toString(),UWe=_R?BigInt(Number.MAX_SAFE_INTEGER):void 0;function Rz(t,e){if(t.length>e.length)return!1;if(t.length<e.length||t===e)return!0;for(let n=0;n<t.length;n++){const r=t[n],i=e[n];if(r>i)return!1;if(r<i)return!0}}const jWe=typeof Uint8Array.prototype.slice=="function";let Due,An=0,br=0;function Iz(t){const e=t>>>0;An=e,br=(t-e)/4294967296>>>0}function Rv(t){if(t<0){Iz(-t);const[e,n]=f9(An,br);An=e>>>0,br=n>>>0}else Iz(t)}function l9(t){const e=Due||=new DataView(new ArrayBuffer(8));e.setFloat32(0,+t,!0),br=0,An=e.getUint32(0,!0)}function u9(t,e){const n=4294967296*e+(t>>>0);return Number.isSafeInteger(n)?n:Yb(t,e)}function d9(t,e){const n=2147483648&e;return n&&(e=~e>>>0,(t=1+~t>>>0)==0&&(e=e+1>>>0)),typeof(t=u9(t,e))=="number"?n?-t:t:n?"-"+t:t}function Yb(t,e){if(t>>>=0,(e>>>=0)<=2097151)var n=""+(4294967296*e+t);else i9()?n=""+(BigInt(e)<<BigInt(32)|BigInt(t)):(t=(16777215&t)+6777216*(n=16777215&(t>>>24|e<<8))+6710656*(e=e>>16&65535),n+=8147497*e,e*=2,t>=1e7&&(n+=t/1e7>>>0,t%=1e7),n>=1e7&&(e+=n/1e7>>>0,n%=1e7),n=e+kz(n)+kz(t));return n}function kz(t){return t=String(t),"0000000".slice(t.length)+t}function SR(t){if(t.length<16)Rv(Number(t));else if(i9())t=BigInt(t),An=Number(t&BigInt(4294967295))>>>0,br=Number(t>>BigInt(32)&BigInt(4294967295));else{const e=+(t[0]==="-");br=An=0;const n=t.length;for(let r=e,i=(n-e)%6+e;i<=n;r=i,i+=6){const s=Number(t.slice(r,i));br*=1e6,An=1e6*An+s,An>=4294967296&&(br+=Math.trunc(An/4294967296),br>>>=0,An>>>=0)}if(e){const[r,i]=f9(An,br);An=r,br=i}}}function f9(t,e){return e=~e,t?t=1+~t:e+=1,[t,e]}const h9=typeof BigInt=="function"?BigInt.asIntN:void 0,FWe=typeof BigInt=="function"?BigInt.asUintN:void 0,Gg=Number.isSafeInteger,ER=Number.isFinite,E3=Math.trunc;function Vf(t){return t==null||typeof t=="number"?t:t==="NaN"||t==="Infinity"||t==="-Infinity"?Number(t):void 0}function Nue(t){return t==null||typeof t=="boolean"?t:typeof t=="number"?!!t:void 0}const $We=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function wR(t){switch(typeof t){case"bigint":return!0;case"number":return ER(t);case"string":return $We.test(t);default:return!1}}function o0(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return ER(t)?0|t:void 0}function Uue(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return ER(t)?t>>>0:void 0}function xz(t){if(t[0]==="-")return!1;const e=t.length;return e<20||e===20&&Number(t.substring(0,6))<184467}function p9(t){return t=E3(t),Gg(t)||(Rv(t),t=d9(An,br)),t}function m9(t){var e=E3(Number(t));if(Gg(e))return String(e);if((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),e=t.length,!(t[0]==="-"?e<20||e===20&&Number(t.substring(0,7))>-922337:e<19||e===19&&Number(t.substring(0,6))<922337))if(SR(t),t=An,2147483648&(e=br))if(i9())t=""+(BigInt(0|e)<<BigInt(32)|BigInt(t>>>0));else{const[n,r]=f9(t,e);t="-"+Yb(n,r)}else t=Yb(t,e);return t}function w3(t){return t==null?t:typeof t=="bigint"?(QL(t)?t=Number(t):(t=h9(64,t),t=QL(t)?Number(t):String(t)),t):wR(t)?typeof t=="number"?p9(t):m9(t):void 0}function BWe(t){if(t==null)return t;var e=typeof t;if(e==="bigint")return String(FWe(64,t));if(wR(t)){if(e==="string")return e=E3(Number(t)),Gg(e)&&e>=0?t=String(e):((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),xz(t)||(SR(t),t=Yb(An,br))),t;if(e==="number")return(t=E3(t))>=0&&Gg(t)?t:function(n){if(n<0){Rv(n);var r=Yb(An,br);return n=Number(r),Gg(n)?n:r}return xz(r=String(n))?r:(Rv(n),u9(An,br))}(t)}}function jue(t){if(typeof t!="string")throw Error();return t}function a0(t){if(t!=null&&typeof t!="string")throw Error();return t}function Iv(t){return t==null||typeof t=="string"?t:void 0}function g9(t,e,n,r){if(t!=null&&typeof t=="object"&&t.W===z_)return t;if(!Array.isArray(t))return n?2&r?((t=e[Sz])||(s0((t=new e).u),t=e[Sz]=t),e=t):e=new e:e=void 0,e;let i=n=0|t[ze];return i===0&&(i|=32&r),i|=2&r,i!==n&&$r(t,i),new e(t)}function HWe(t,e,n){if(e)e:{if(!wR(e=t))throw XL("int64");switch(typeof e){case"string":e=m9(e);break e;case"bigint":if(t=e=h9(64,e),Tz(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(LWe(t)&&!Number.isSafeInteger(t))throw Error(String(t));e=_R?BigInt(e):OWe(e)?e?"1":"0":Tz(e)?e.trim()||"0":String(e);break e;default:e=p9(e)}}else e=w3(t);return typeof(n=(t=e)==null?n?0:void 0:t)=="string"&&Gg(e=+n)?e:n}const VWe={};let qWe=function(){try{return n9(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),Vx=class{constructor(){this.g=new Map}get(e){return this.g.get(e)}set(e,n){return this.g.set(e,n),this.size=this.g.size,this}delete(e){return e=this.g.delete(e),this.size=this.g.size,e}clear(){this.g.clear(),this.size=this.g.size}has(e){return this.g.has(e)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(e,n){return this.g.forEach(e,n)}[Symbol.iterator](){return this.entries()}};const GWe=qWe?(Object.setPrototypeOf(Vx.prototype,Map.prototype),Object.defineProperties(Vx.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),Vx):class extends Map{constructor(){super()}};function Az(t){return t}function qx(t){if(2&t.L)throw Error("Cannot mutate an immutable Map")}var Ca=class extends GWe{constructor(t,e,n=Az,r=Az){super();let i=0|t[ze];i|=64,$r(t,i),this.L=i,this.S=e,this.R=n,this.Y=this.S?KWe:r;for(let s=0;s<t.length;s++){const o=t[s],a=n(o[0],!1,!0);let c=o[1];e?c===void 0&&(c=null):c=r(o[1],!1,!0,void 0,void 0,i),super.set(a,c)}}na(t=Pz){if(this.size!==0)return this.X(t)}X(t=Pz){const e=[],n=super.entries();for(var r;!(r=n.next()).done;)(r=r.value)[0]=t(r[0]),r[1]=t(r[1]),e.push(r);return e}clear(){qx(this),super.clear()}delete(t){return qx(this),super.delete(this.R(t,!0,!1))}entries(){var t=this.ma();return new Cz(t,zWe,this)}keys(){return this.Ha()}values(){var t=this.ma();return new Cz(t,Ca.prototype.get,this)}forEach(t,e){super.forEach((n,r)=>{t.call(e,this.get(r),r,this)})}set(t,e){return qx(this),(t=this.R(t,!0,!1))==null?this:e==null?(super.delete(t),this):super.set(t,this.Y(e,!0,!0,this.S,!1,this.L))}Na(t){const e=this.R(t[0],!1,!0);t=t[1],t=this.S?t===void 0?null:t:this.Y(t,!1,!0,void 0,!1,this.L),super.set(e,t)}has(t){return super.has(this.R(t,!1,!1))}get(t){t=this.R(t,!1,!1);const e=super.get(t);if(e!==void 0){var n=this.S;return n?((n=this.Y(e,!1,!0,n,this.ra,this.L))!==e&&super.set(t,n),n):e}}ma(){return Array.from(super.keys())}Ha(){return super.keys()}[Symbol.iterator](){return this.entries()}};function KWe(t,e,n,r,i,s){return t=g9(t,r,n,s),i&&(t=TR(t)),t}function Pz(t){return t}function zWe(t){return[t,this.get(t)]}let WWe,Fue,YWe;function Lz(){return WWe||=new Ca(s0([]),void 0,void 0,void 0,VWe)}function v9(t,e,n,r,i){if(t!=null){if(Array.isArray(t))t=S3(t)?void 0:i&&2&(0|t[ze])?t:y9(t,e,n,r!==void 0,i);else if(o9(t)){const s={};for(let o in t)s[o]=v9(t[o],e,n,r,i);t=s}else t=e(t,r);return t}}function y9(t,e,n,r,i){const s=r||n?0|t[ze]:0,o=r?!!(32&s):void 0;r=Js(t);for(let a=0;a<r.length;a++)r[a]=v9(r[a],e,n,o,i);return n&&((t=c9(t))&&(r[Tv]=Js(t)),n(s,r)),r}function XWe(t){return v9(t,$ue,void 0,void 0,!1)}function $ue(t){return t.W===z_?t.toJSON():t instanceof Ca?t.na(XWe):function(e){switch(typeof e){case"number":return isFinite(e)?e:String(e);case"bigint":return QL(e)?Number(e):String(e);case"boolean":return e?1:0;case"object":if(e)if(Array.isArray(e)){if(S3(e))return}else{if(G_(e))return bz(e);if(e instanceof Tu){const n=e.g;return n==null?"":typeof n=="string"?n:e.g=bz(n)}if(e instanceof Ca)return e.na()}}return e}(t)}function Bue(t){return y9(t,$ue,void 0,void 0,!1)}function lf(t,e,n){return t=Hue(t,e[0],e[1],n?1:2),e!==Fue&&n&&yR(t,16384),t}function Hue(t,e,n,r){if(t==null){var i=96;n?(t=[n],i|=512):t=[],e&&(i=-33521665&i|(1023&e)<<15)}else{if(!Array.isArray(t))throw Error("narr");if(2048&(i=0|t[ze]))throw Error("farr");if(64&i)return t;if(r===1||r===2||(i|=64),n&&(i|=512,n!==t[0]))throw Error("mid");e:{if(r=(n=t).length){const s=r-1;if(o9(n[s])){if((e=s-(512&(i|=256)?0:-1))>=1024)throw Error("pvtlmt");i=-33521665&i|(1023&e)<<15;break e}}if(e){if((e=Math.max(e,r-(512&i?0:-1)))>1024)throw Error("spvt");i=-33521665&i|(1023&e)<<15}}}return $r(t,i),t}function ZL(t,e,n=JL){if(t!=null){if(Rue&&t instanceof Uint8Array)return e?t:new Uint8Array(t);if(Array.isArray(t)){var r=0|t[ze];return 2&r?t:(e&&=r===0||!!(32&r)&&!(64&r||!(16&r)),e?($r(t,-12293&(34|r)),t):y9(t,ZL,4&r?JL:n,!0,!0))}return t.W===z_?t=2&(r=0|(n=t.u)[ze])?t:new t.constructor(CR(n,r,!0)):t instanceof Ca&&!(2&t.L)&&(n=s0(t.X(ZL)),t=new Ca(n,t.S,t.R,t.Y)),t}}function CR(t,e,n){const r=n||2&e?JL:AWe,i=!!(32&e);return t=function(s,o,a){const c=Js(s);var l=c.length;const d=256&o?c[l-1]:void 0;for(l+=d?-1:0,o=512&o?1:0;o<l;o++)c[o]=a(c[o]);if(d){o=c[o]={};for(const h in d)o[h]=a(d[h])}return(s=c9(s))&&(c[Tv]=Js(s)),c}(t,e,s=>ZL(s,i,r)),yR(t,32|(n?2:0)),t}function TR(t){const e=t.u,n=0|e[ze];return 2&n?new t.constructor(CR(e,n,!1)):t}function kv(t,e){return Yu(t=t.u,0|t[ze],e)}function Yu(t,e,n,r){if(n===-1)return null;var i=n+(512&e?0:-1);const s=t.length-1;return i>=s&&256&e?t[s][n]:r&&256&e&&(e=t[s][n])!=null?(t[i]!=null&&Hx!=null&&((i=(t=IWe??={})[Hx]||0)>=4||(t[Hx]=i+1,Aue(t=Error(),"incident"),function(o){vp.setTimeout(()=>{throw o},0)}(t))),e):i<=s?t[i]:void 0}function Fn(t,e,n){const r=t.u;let i=0|r[ze];return Hf(i),ur(r,i,e,n),t}function ur(t,e,n,r){const i=512&e?0:-1,s=n+i;var o=t.length-1;return s>=o&&256&e?(t[o][n]=r,e):s<=o?(t[s]=r,256&e&&n in(t=t[o])&&delete t[n],e):(r!==void 0&&(n>=(o=e>>15&1023||536870912)?r!=null&&(t[o+i]={[n]:r},$r(t,e|=256)):t[s]=r),e)}function Hw(t,e){let n=0|(t=t.u)[ze];const r=Yu(t,n,e),i=Vf(r);return i!=null&&i!==r&&ur(t,n,e,i),i}function Vue(t){let e=0|(t=t.u)[ze];const n=Yu(t,e,1),r=a9(n,!0);return r!=null&&r!==n&&ur(t,e,1,r),r}function Fh(){return PWe===void 0?2:4}function $h(t,e,n,r,i){const s=t.u,o=2&(t=0|s[ze])?1:r;i=!!i;let a=0|(r=b9(s,t,e))[ze];if(!(4&a)){4&a&&(r=Js(r),a=Ru(a,t),t=ur(s,t,e,r));let c=0,l=0;for(;c<r.length;c++){const d=n(r[c]);d!=null&&(r[l++]=d)}l<c&&(r.length=l),a=_9(a,t),n=-4097&(20|a),a=n&=-8193,$r(r,a),2&a&&Object.freeze(r)}return o===1||o===4&&32&a?gu(a)||(i=a,a|=2,a!==i&&$r(r,a),Object.freeze(r)):(o===2&&gu(a)&&(r=Js(r),a=Ru(a,t),a=uf(a,t,i),$r(r,a),t=ur(s,t,e,r)),gu(a)||(e=a,a=uf(a,t,i),a!==e&&$r(r,a))),r}function b9(t,e,n,r){return t=Yu(t,e,n,r),Array.isArray(t)?t:s9}function _9(t,e){return t===0&&(t=Ru(t,e)),1|t}function gu(t){return!!(2&t)&&!!(4&t)||!!(2048&t)}function que(t){t=Js(t);for(let e=0;e<t.length;e++){const n=t[e]=Js(t[e]);Array.isArray(n[1])&&(n[1]=s0(n[1]))}return t}function eO(t,e,n,r){let i=0|(t=t.u)[ze];Hf(i),ur(t,i,e,(r==="0"?Number(n)===0:n===r)?void 0:n)}function c0(t,e,n,r,i){Hf(e);var s=!(!(64&e)&&16384&e);const o=(i=b9(t,e,n,i))!==s9;if(s||!o){let a=s=o?0|i[ze]:0;(!o||2&a||gu(a)||4&a&&!(32&a))&&(i=Js(i),a=Ru(a,e),e=ur(t,e,n,i)),a=-13&_9(a,e),a=uf(r?-17&a:16|a,e,!0),a!==s&&$r(i,a)}return i}function Gx(t,e){var n=Ode;return E9(S9(t=t.u),t,0|t[ze],n)===e?e:-1}function S9(t){if(vR)return t[Y1]??(t[Y1]=new Map);if(Y1 in t)return t[Y1];const e=new Map;return Object.defineProperty(t,Y1,{value:e}),e}function Gue(t,e,n,r){const i=S9(t),s=E9(i,t,e,n);return s!==r&&(s&&(e=ur(t,e,s)),i.set(n,r)),e}function E9(t,e,n,r){let i=t.get(r);if(i!=null)return i;i=0;for(let s=0;s<r.length;s++){const o=r[s];Yu(e,n,o)!=null&&(i!==0&&(n=ur(e,n,i)),i=o)}return t.set(r,i),i}function w9(t,e,n,r){let i,s=0|t[ze];if((r=Yu(t,s,n,r))!=null&&r.W===z_)return(e=TR(r))!==r&&ur(t,s,n,e),e.u;if(Array.isArray(r)){const o=0|r[ze];i=2&o?lf(CR(r,o,!1),e,!0):64&o?r:lf(i,e,!0)}else i=lf(void 0,e,!0);return i!==r&&ur(t,s,n,i),i}function Kue(t,e,n,r){let i=0|(t=t.u)[ze];return(e=g9(r=Yu(t,i,n,r),e,!1,i))!==r&&e!=null&&ur(t,i,n,e),e}function zt(t,e,n,r=!1){if((e=Kue(t,e,n,r))==null)return e;if(!(2&(r=0|(t=t.u)[ze]))){const i=TR(e);i!==e&&ur(t,r,n,e=i)}return e}function zue(t,e,n,r,i,s,o){t=t.u;var a=!!(2&e);const c=a?1:i;s=!!s,o&&=!a;var l=0|(i=b9(t,e,r))[ze];if(!(a=!!(4&l))){var d=i,h=e;const m=!!(2&(l=_9(l,e)));m&&(h|=2);let g=!m,y=!0,v=0,w=0;for(;v<d.length;v++){const S=g9(d[v],n,!1,h);if(S instanceof n){if(!m){const R=!!(2&(0|S.u[ze]));g&&=!R,y&&=R}d[w++]=S}}w<v&&(d.length=w),l|=4,l=y?16|l:-17&l,$r(d,l=g?8|l:-9&l),m&&Object.freeze(d)}if(o&&!(8&l||!i.length&&(c===1||c===4&&32&l))){for(gu(l)&&(i=Js(i),l=Ru(l,e),e=ur(t,e,r,i)),n=i,o=l,d=0;d<n.length;d++)(l=n[d])!==(h=TR(l))&&(n[d]=h);o|=8,$r(n,o=n.length?-17&o:16|o),l=o}return c===1||c===4&&32&l?gu(l)||(e=l,(l|=!i.length||16&l&&(!a||32&l)?2:2048)!==e&&$r(i,l),Object.freeze(i)):(c===2&&gu(l)&&($r(i=Js(i),l=uf(l=Ru(l,e),e,s)),e=ur(t,e,r,i)),gu(l)||(r=l,(l=uf(l,e,s))!==r&&$r(i,l))),i}function $u(t,e,n){const r=0|t.u[ze];return zue(t,r,e,n,Fh(),!1,!(2&r))}function Ye(t,e,n,r){return r==null&&(r=void 0),Fn(t,n,r)}function Xy(t,e,n,r){r==null&&(r=void 0);e:{let i=0|(t=t.u)[ze];if(Hf(i),r==null){const s=S9(t);if(E9(s,t,i,n)!==e)break e;s.set(n,0)}else i=Gue(t,i,n,e);ur(t,i,e,r)}}function Ru(t,e){return-2049&(t=32|(2&e?2|t:-3&t))}function uf(t,e,n){return 32&e&&n||(t&=-33),t}function C3(t,e,n,r){const i=0|t.u[ze];Hf(i),t=zue(t,i,n,e,2,!0),r=r??new n,t.push(r),t[ze]=2&(0|r.u[ze])?-9&t[ze]:-17&t[ze]}function fa(t,e){return o0(kv(t,e))}function Ta(t,e){return Iv(kv(t,e))}function Tr(t,e){return Hw(t,e)??0}function Xb(t,e,n){if(n!=null&&typeof n!="boolean")throw t=typeof n,Error(`Expected boolean but got ${t!="object"?t:n?Array.isArray(n)?"array":t:"null"}: ${n}`);Fn(t,e,n)}function sl(t,e,n){if(n!=null){if(typeof n!="number"||!ER(n))throw XL("int32");n|=0}Fn(t,e,n)}function Ve(t,e,n){if(n!=null&&typeof n!="number")throw Error(`Value of float/double field must be a number, found ${typeof n}: ${n}`);Fn(t,e,n)}function T3(t,e,n){{const o=t.u;let a=0|o[ze];if(Hf(a),n==null)ur(o,a,e);else{var r=t=0|n[ze],i=gu(t),s=i||Object.isFrozen(n);for(i||(t=0),s||(n=Js(n),r=0,t=uf(t=Ru(t,a),a,!0),s=!1),t|=21,i=0;i<n.length;i++){const c=n[i],l=jue(c);Object.is(c,l)||(s&&(n=Js(n),r=0,t=uf(t=Ru(t,a),a,!0),s=!1),n[i]=l)}t!==r&&(s&&(n=Js(n),t=uf(t=Ru(t,a),a,!0)),$r(n,t)),ur(o,a,e,n)}}}function RR(t,e,n){Hf(0|t.u[ze]),$h(t,e,Iv,2,!0).push(jue(n))}function Wue(t,e){return Error(`Invalid wire type: ${t} (at position ${e})`)}function C9(){return Error("Failed to read varint, encoding is invalid.")}function Yue(t,e){return Error(`Tried to read past the end of the data ${e} > ${t}`)}function T9(t){if(typeof t=="string")return{buffer:kue(t),N:!1};if(Array.isArray(t))return{buffer:new Uint8Array(t),N:!1};if(t.constructor===Uint8Array)return{buffer:t,N:!1};if(t.constructor===ArrayBuffer)return{buffer:new Uint8Array(t),N:!1};if(t.constructor===Tu)return{buffer:r9(t)||new Uint8Array(0),N:!0};if(t instanceof Uint8Array)return{buffer:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),N:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}function R9(t,e){let n,r=0,i=0,s=0;const o=t.h;let a=t.g;do n=o[a++],r|=(127&n)<<s,s+=7;while(s<32&&128&n);for(s>32&&(i|=(127&n)>>4),s=3;s<32&&128&n;s+=7)n=o[a++],i|=(127&n)<<s;if(Qh(t,a),n<128)return e(r>>>0,i>>>0);throw C9()}function I9(t){let e=0,n=t.g;const r=n+10,i=t.h;for(;n<r;){const s=i[n++];if(e|=s,(128&s)==0)return Qh(t,n),!!(127&e)}throw C9()}function If(t){const e=t.h;let n=t.g,r=e[n++],i=127&r;if(128&r&&(r=e[n++],i|=(127&r)<<7,128&r&&(r=e[n++],i|=(127&r)<<14,128&r&&(r=e[n++],i|=(127&r)<<21,128&r&&(r=e[n++],i|=r<<28,128&r&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++])))))throw C9();return Qh(t,n),i}function Bu(t){return If(t)>>>0}function tO(t){var e=t.h;const n=t.g,r=e[n],i=e[n+1],s=e[n+2];return e=e[n+3],Qh(t,t.g+4),(r<<0|i<<8|s<<16|e<<24)>>>0}function nO(t){var e=tO(t);t=2*(e>>31)+1;const n=e>>>23&255;return e&=8388607,n==255?e?NaN:t*(1/0):n==0?1401298464324817e-60*t*e:t*Math.pow(2,n-150)*(e+8388608)}function JWe(t){return If(t)}function Kx(t,e,{ba:n=!1}={}){t.ba=n,e&&(e=T9(e),t.h=e.buffer,t.m=e.N,t.j=0,t.l=t.h.length,t.g=t.j)}function Qh(t,e){if(t.g=e,e>t.l)throw Yue(t.l,e)}function Xue(t,e){if(e<0)throw Error(`Tried to read a negative byte length: ${e}`);const n=t.g,r=n+e;if(r>t.l)throw Yue(e,t.l-n);return t.g=r,n}function Jue(t,e){if(e==0)return yp();var n=Xue(t,e);return t.ba&&t.m?n=t.h.subarray(n,n+e):(t=t.h,n=n===(e=n+e)?new Uint8Array(0):jWe?t.slice(n,e):new Uint8Array(t.subarray(n,e))),n.length==0?yp():new Tu(n,Cv)}Ca.prototype.toJSON=void 0,Ca.prototype.Ia=Oue;var Oz=[];function Que(t){var e=t.g;if(e.g==e.l)return!1;t.l=t.g.g;var n=Bu(t.g);if(e=n>>>3,!((n&=7)>=0&&n<=5))throw Wue(n,t.l);if(e<1)throw Error(`Invalid field number: ${e} (at position ${t.l})`);return t.m=e,t.h=n,!0}function Vw(t){switch(t.h){case 0:t.h!=0?Vw(t):I9(t.g);break;case 1:Qh(t=t.g,t.g+8);break;case 2:if(t.h!=2)Vw(t);else{var e=Bu(t.g);Qh(t=t.g,t.g+e)}break;case 5:Qh(t=t.g,t.g+4);break;case 3:for(e=t.m;;){if(!Que(t))throw Error("Unmatched start-group tag: stream EOF");if(t.h==4){if(t.m!=e)throw Error("Unmatched end-group tag");break}Vw(t)}break;default:throw Wue(t.h,t.l)}}function W_(t,e,n){const r=t.g.l,i=Bu(t.g),s=t.g.g+i;let o=s-r;if(o<=0&&(t.g.l=s,n(e,t,void 0,void 0,void 0),o=s-t.g.g),o)throw Error(`Message parsing ended unexpectedly. Expected to read ${i} bytes, instead read ${i-o} bytes, either the data ended unexpectedly or the message misreported its own length`);return t.g.g=s,t.g.l=r,e}function k9(t){var e=Bu(t.g),n=Xue(t=t.g,e);if(t=t.h,bWe){var r,i=t;(r=jx)||(r=jx=new TextDecoder("utf-8",{fatal:!0})),e=n+e,i=n===0&&e===i.length?i:i.subarray(n,e);try{var s=r.decode(i)}catch(a){if(EE===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),EE=!0}catch{EE=!1}}throw!EE&&(jx=void 0),a}}else{e=(s=n)+e,n=[];let a,c=null;for(;s<e;){var o=t[s++];o<128?n.push(o):o<224?s>=e?Sh():(a=t[s++],o<194||(192&a)!=128?(s--,Sh()):n.push((31&o)<<6|63&a)):o<240?s>=e-1?Sh():(a=t[s++],(192&a)!=128||o===224&&a<160||o===237&&a>=160||(192&(r=t[s++]))!=128?(s--,Sh()):n.push((15&o)<<12|(63&a)<<6|63&r)):o<=244?s>=e-2?Sh():(a=t[s++],(192&a)!=128||a-144+(o<<28)>>30!=0||(192&(r=t[s++]))!=128||(192&(i=t[s++]))!=128?(s--,Sh()):(o=(7&o)<<18|(63&a)<<12|(63&r)<<6|63&i,o-=65536,n.push(55296+(o>>10&1023),56320+(1023&o)))):Sh(),n.length>=8192&&(c=mz(c,n),n.length=0)}s=mz(c,n)}return s}function Zue(t){const e=Bu(t.g);return Jue(t.g,e)}function IR(t,e,n){var r=Bu(t.g);for(r=t.g.g+r;t.g.g<r;)n.push(e(t.g))}var wE=[];function QWe(t){return t}let Kg;function dc(t,e,n){e.g?e.m(t,e.g,e.h,n):e.m(t,e.h,n)}var He=class{constructor(t,e){this.u=Hue(t,e)}toJSON(){const t=!Kg;try{return t&&(Kg=Bue),ede(this)}finally{t&&(Kg=void 0)}}l(){var t=MYe;return t.g?t.l(this,t.g,t.h,!0):t.l(this,t.h,t.defaultValue,!0)}clone(){const t=this.u;return new this.constructor(CR(t,0|t[ze],!1))}N(){return!!(2&(0|this.u[ze]))}};function ede(t){var e=t.u;{e=(t=Kg(e))!==e;let l=t.length;if(l){var n=t[l-1],r=o9(n);r?l--:n=void 0;var i=t;if(r){e:{var s,o=n,a=!1;if(o)for(let d in o)isNaN(+d)?(s??={})[d]=o[d]:(r=o[d],Array.isArray(r)&&(S3(r)||Ez(r)&&r.size===0)&&(r=null),r==null&&(a=!0),r!=null&&((s??={})[d]=r));if(a||(s=o),s)for(let d in s){a=s;break e}a=null}o=a==null?n!=null:a!==n}for(;l>0&&((s=i[l-1])==null||S3(s)||Ez(s)&&s.size===0);l--)var c=!0;(i!==t||o||c)&&(e?(c||o||a)&&(i.length=l):i=Array.prototype.slice.call(i,0,l),a&&i.push(a)),c=i}else c=t}return c}function Mz(t){return t?/^\d+$/.test(t)?(SR(t),new rO(An,br)):null:ZWe||=new rO(0,0)}He.prototype.W=z_,He.prototype.toString=function(){try{return Kg=QWe,ede(this).toString()}finally{Kg=void 0}};var rO=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let ZWe;function Dz(t){return t?/^-?\d+$/.test(t)?(SR(t),new iO(An,br)):null:eYe||=new iO(0,0)}var iO=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let eYe;function zg(t,e,n){for(;n>0||e>127;)t.g.push(127&e|128),e=(e>>>7|n<<25)>>>0,n>>>=7;t.g.push(e)}function l0(t,e){for(;e>127;)t.g.push(127&e|128),e>>>=7;t.g.push(e)}function kR(t,e){if(e>=0)l0(t,e);else{for(let n=0;n<9;n++)t.g.push(127&e|128),e>>=7;t.g.push(1)}}function Jb(t,e){t.g.push(e>>>0&255),t.g.push(e>>>8&255),t.g.push(e>>>16&255),t.g.push(e>>>24&255)}function xv(t,e){e.length!==0&&(t.l.push(e),t.h+=e.length)}function Lo(t,e,n){l0(t.g,8*e+n)}function x9(t,e){return Lo(t,e,2),e=t.g.end(),xv(t,e),e.push(t.h),e}function A9(t,e){var n=e.pop();for(n=t.h+t.g.length()-n;n>127;)e.push(127&n|128),n>>>=7,t.h++;e.push(n),t.h++}function xR(t,e,n){Lo(t,e,2),l0(t.g,n.length),xv(t,t.g.end()),xv(t,n)}function R3(t,e,n,r){n!=null&&(e=x9(t,e),r(n,t),A9(t,e))}function fc(){const t=class{constructor(){throw Error()}};return Object.setPrototypeOf(t,t.prototype),t}var P9=fc(),tde=fc(),L9=fc(),O9=fc(),nde=fc(),rde=fc(),M9=fc(),ide=fc(),sde=fc(),u0=class{constructor(e,n,r){this.g=e,this.h=n,e=P9,this.l=!!e&&r===e||!1}};function AR(t,e){return new u0(t,e,P9)}function ode(t,e,n,r,i){R3(t,n,ude(e,r),i)}const tYe=AR(function(t,e,n,r,i){return t.h===2&&(W_(t,w9(e,r,n),i),!0)},ode),nYe=AR(function(t,e,n,r,i){return t.h===2&&(W_(t,w9(e,r,n,!0),i),!0)},ode);var PR=Symbol(),D9=Symbol(),Nz=Symbol(),Uz=Symbol();let ade,cde;function Fp(t,e,n,r){var i=r[t];if(i)return i;(i={}).Pa=r,i.V=function(h){switch(typeof h){case"boolean":return Fue||=[0,void 0,!0];case"number":return h>0?void 0:h===0?YWe||=[0,void 0]:[-h,void 0];case"string":return[0,h];case"object":return h}}(r[0]);var s=r[1];let o=1;s&&s.constructor===Object&&(i.ga=s,typeof(s=r[++o])=="function"&&(i.la=!0,ade??=s,cde??=r[o+1],s=r[o+=2]));const a={};for(;s&&Array.isArray(s)&&s.length&&typeof s[0]=="number"&&s[0]>0;){for(var c=0;c<s.length;c++)a[s[c]]=s;s=r[++o]}for(c=1;s!==void 0;){let h;typeof s=="number"&&(c+=s,s=r[++o]);var l=void 0;if(s instanceof u0?h=s:(h=tYe,o--),h?.l){s=r[++o],l=r;var d=o;typeof s=="function"&&(s=s(),l[d]=s),l=s}for(d=c+1,typeof(s=r[++o])=="number"&&s<0&&(d-=s,s=r[++o]);c<d;c++){const m=a[c];l?n(i,c,h,l,m):e(i,c,h,m)}}return r[t]=i}function lde(t){return Array.isArray(t)?t[0]instanceof u0?t:[nYe,t]:[t,void 0]}function ude(t,e){return t instanceof He?t.u:Array.isArray(t)?lf(t,e,!1):void 0}function N9(t,e,n,r){const i=n.g;t[e]=r?(s,o,a)=>i(s,o,a,r):i}function U9(t,e,n,r,i){const s=n.g;let o,a;t[e]=(c,l,d)=>s(c,l,d,a||=Fp(D9,N9,U9,r).V,o||=j9(r),i)}function j9(t){let e=t[Nz];if(e!=null)return e;const n=Fp(D9,N9,U9,t);return e=n.la?(r,i)=>ade(r,i,n):(r,i)=>{const s=0|r[ze];for(;Que(i)&&i.h!=4;){var o=i.m,a=n[o];if(a==null){var c=n.ga;c&&(c=c[o])&&(c=rYe(c))!=null&&(a=n[o]=c)}a!=null&&a(i,r,o)||(o=(a=i).l,Vw(a),a.fa?a=void 0:(c=a.g.g-o,a.g.g=o,a=Jue(a.g,c)),o=r,a&&((c=o[Tv])?c.push(a):o[Tv]=[a]))}return 16384&s&&s0(r),!0},t[Nz]=e}function rYe(t){const e=(t=lde(t))[0].g;if(t=t[1]){const n=j9(t),r=Fp(D9,N9,U9,t).V;return(i,s,o)=>e(i,s,o,r,n)}return e}function LR(t,e,n){t[e]=n.h}function OR(t,e,n,r){let i,s;const o=n.h;t[e]=(a,c,l)=>o(a,c,l,s||=Fp(PR,LR,OR,r).V,i||=dde(r))}function dde(t){let e=t[Uz];if(!e){const n=Fp(PR,LR,OR,t);e=(r,i)=>fde(r,i,n),t[Uz]=e}return e}function fde(t,e,n){for(var r=0|t[ze],i=512&r?0:-1,s=t.length,o=512&r?1:0,a=s+(256&r?-1:0);o<a;o++){const c=t[o];if(c==null)continue;const l=o-i,d=jz(n,l);d&&d(e,c,l)}if(256&r){r=t[s-1];for(const c in r)i=+c,Number.isNaN(i)||(s=r[i])!=null&&(a=jz(n,i))&&a(e,s,i)}if(t=c9(t))for(xv(e,e.g.end()),n=0;n<t.length;n++)xv(e,r9(t[n])||new Uint8Array(0))}function jz(t,e){var n=t[e];if(n)return n;if((n=t.ga)&&(n=n[e])){var r=(n=lde(n))[0].h;if(n=n[1]){const i=dde(n),s=Fp(PR,LR,OR,n).V;n=t.la?cde(s,i):(o,a,c)=>r(o,a,c,s,i)}else n=r;return t[e]=n}}function d0(t,e){if(Array.isArray(e)){var n=0|e[ze];if(4&n)return e;for(var r=0,i=0;r<e.length;r++){const s=t(e[r]);s!=null&&(e[i++]=s)}return i<r&&(e.length=i),$r(e,-12289&(5|n)),2&n&&Object.freeze(e),e}}function Ts(t,e,n){return new u0(t,e,n)}function f0(t,e,n){return new u0(t,e,n)}function Rs(t,e,n){ur(t,0|t[ze],e,n)}var iYe=AR(function(t,e,n,r,i){return t.h===2&&(t=W_(t,lf([void 0,void 0],r,!0),i),Hf(r=0|e[ze]),(i=Yu(e,r,n))instanceof Ca?(2&i.L)!=0?((i=i.X()).push(t),ur(e,r,n,i)):i.Na(t):Array.isArray(i)?(2&(0|i[ze])&&ur(e,r,n,i=que(i)),i.push(t)):ur(e,r,n,[t]),!0)},function(t,e,n,r,i){if(e instanceof Ca)e.forEach((s,o)=>{R3(t,n,lf([o,s],r,!1),i)});else if(Array.isArray(e))for(let s=0;s<e.length;s++){const o=e[s];Array.isArray(o)&&R3(t,n,lf(o,r,!1),i)}});function hde(t,e,n){if(e=function(r){if(r==null)return r;const i=typeof r;if(i==="bigint")return String(h9(64,r));if(wR(r)){if(i==="string")return m9(r);if(i==="number")return p9(r)}}(e),e!=null&&(typeof e=="string"&&Dz(e),e!=null))switch(Lo(t,n,0),typeof e){case"number":t=t.g,Rv(e),zg(t,An,br);break;case"bigint":n=BigInt.asUintN(64,e),n=new iO(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),zg(t.g,n.h,n.g);break;default:n=Dz(e),zg(t.g,n.h,n.g)}}function pde(t,e,n){(e=o0(e))!=null&&e!=null&&(Lo(t,n,0),kR(t.g,e))}function mde(t,e,n){(e=Nue(e))!=null&&(Lo(t,n,0),t.g.g.push(e?1:0))}function gde(t,e,n){(e=Iv(e))!=null&&xR(t,n,wue(e))}function vde(t,e,n,r,i){R3(t,n,ude(e,r),i)}function yde(t,e,n){(e=e==null||typeof e=="string"||G_(e)||e instanceof Tu?e:void 0)!=null&&xR(t,n,T9(e).buffer)}function bde(t,e,n){return(t.h===5||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,nO,e):e.push(nO(t.g)),!0)}var tu=Ts(function(t,e,n){if(t.h!==1)return!1;var r=t.g;t=tO(r);const i=tO(r);r=2*(i>>31)+1;const s=i>>>20&2047;return t=4294967296*(1048575&i)+t,Rs(e,n,s==2047?t?NaN:r*(1/0):s==0?5e-324*r*t:r*Math.pow(2,s-1075)*(t+4503599627370496)),!0},function(t,e,n){(e=Vf(e))!=null&&(Lo(t,n,1),t=t.g,(n=Due||=new DataView(new ArrayBuffer(8))).setFloat64(0,+e,!0),An=n.getUint32(0,!0),br=n.getUint32(4,!0),Jb(t,An),Jb(t,br))},fc()),Hr=Ts(function(t,e,n){return t.h===5&&(Rs(e,n,nO(t.g)),!0)},function(t,e,n){(e=Vf(e))!=null&&(Lo(t,n,5),t=t.g,l9(e),Jb(t,An))},M9),sYe=f0(bde,function(t,e,n){if((e=d0(Vf,e))!=null)for(let o=0;o<e.length;o++){var r=t,i=n,s=e[o];s!=null&&(Lo(r,i,5),r=r.g,l9(s),Jb(r,An))}},M9),F9=f0(bde,function(t,e,n){if((e=d0(Vf,e))!=null&&e.length){Lo(t,n,2),l0(t.g,4*e.length);for(let r=0;r<e.length;r++)n=t.g,l9(e[r]),Jb(n,An)}},M9),kf=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,R9(t.g,d9)),!0)},hde,rde),zx=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=R9(t.g,d9))===0?void 0:t),!0)},hde,rde),oYe=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,R9(t.g,u9)),!0)},function(t,e,n){if((e=BWe(e))!=null&&(typeof e=="string"&&Mz(e),e!=null))switch(Lo(t,n,0),typeof e){case"number":t=t.g,Rv(e),zg(t,An,br);break;case"bigint":n=BigInt.asUintN(64,e),n=new rO(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),zg(t.g,n.h,n.g);break;default:n=Mz(e),zg(t.g,n.h,n.g)}},fc()),Er=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,If(t.g)),!0)},pde,O9),MR=f0(function(t,e,n){return(t.h===0||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,If,e):e.push(If(t.g)),!0)},function(t,e,n){if((e=d0(o0,e))!=null&&e.length){n=x9(t,n);for(let r=0;r<e.length;r++)kR(t.g,e[r]);A9(t,n)}},O9),bg=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=If(t.g))===0?void 0:t),!0)},pde,O9),er=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,I9(t.g)),!0)},mde,tde),Wg=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=I9(t.g))===!1?void 0:t),!0)},mde,tde),Qi=f0(function(t,e,n){return t.h===2&&(t=k9(t),c0(e,0|e[ze],n,!1).push(t),!0)},function(t,e,n){if((e=d0(Iv,e))!=null)for(let o=0;o<e.length;o++){var r=t,i=n,s=e[o];s!=null&&xR(r,i,wue(s))}},L9),Hd=Ts(function(t,e,n){return t.h===2&&(Rs(e,n,(t=k9(t))===""?void 0:t),!0)},gde,L9),fn=Ts(function(t,e,n){return t.h===2&&(Rs(e,n,k9(t)),!0)},gde,L9),ni=function(t,e,n=P9){return new u0(t,e,n)}(function(t,e,n,r,i){return t.h===2&&(r=lf(void 0,r,!0),c0(e,0|e[ze],n,!0).push(r),W_(t,r,i),!0)},function(t,e,n,r,i){if(Array.isArray(e))for(let s=0;s<e.length;s++)vde(t,e[s],n,r,i)}),gn=AR(function(t,e,n,r,i,s){return t.h===2&&(Gue(e,0|e[ze],s,n),W_(t,e=w9(e,r,n),i),!0)},vde),_de=Ts(function(t,e,n){return t.h===2&&(Rs(e,n,Zue(t)),!0)},yde,ide),aYe=f0(function(t,e,n){return(t.h===0||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,Bu,e):e.push(Bu(t.g)),!0)},function(t,e,n){if((e=d0(Uue,e))!=null)for(let o=0;o<e.length;o++){var r=t,i=n,s=e[o];s!=null&&(Lo(r,i,0),l0(r.g,s))}},nde),cYe=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=Bu(t.g))===0?void 0:t),!0)},function(t,e,n){(e=Uue(e))!=null&&e!=null&&(Lo(t,n,0),l0(t.g,e))},nde),Ra=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,If(t.g)),!0)},function(t,e,n){(e=o0(e))!=null&&(e=parseInt(e,10),Lo(t,n,0),kR(t.g,e))},sde);class lYe{constructor(e,n){this.h=e,this.g=n,this.l=zt,this.m=Ye,this.defaultValue=void 0}}function hc(t,e){return new lYe(t,e)}function qf(t,e){return(n,r)=>{if(wE.length){const s=wE.pop();s.o(r),Kx(s.g,n,r),n=s}else n=new class{constructor(s,o){if(Oz.length){const a=Oz.pop();Kx(a,s,o),s=a}else s=new class{constructor(a,c){this.h=null,this.m=!1,this.g=this.l=this.j=0,Kx(this,a,c)}clear(){this.h=null,this.m=!1,this.g=this.l=this.j=0,this.ba=!1}}(s,o);this.g=s,this.l=this.g.g,this.h=this.m=-1,this.o(o)}o({fa:s=!1}={}){this.fa=s}}(n,r);try{const s=new t,o=s.u;j9(e)(o,n);var i=s}finally{n.g.clear(),n.m=-1,n.h=-1,wE.length<100&&wE.push(n)}return i}}function DR(t){return function(){const e=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const o=this.g;return this.g=[],o}}}};fde(this.u,e,Fp(PR,LR,OR,t)),xv(e,e.g.end());const n=new Uint8Array(e.h),r=e.l,i=r.length;let s=0;for(let o=0;o<i;o++){const a=r[o];n.set(a,s),s+=a.length}return e.l=[n],n}}var Fz=class extends He{constructor(t){super(t)}},$z=[0,Hd,Ts(function(t,e,n){return t.h===2&&(Rs(e,n,(t=Zue(t))===yp()?void 0:t),!0)},function(t,e,n){if(e!=null){if(e instanceof He){const r=e.Ra;return void(r&&(e=r(e),e!=null&&xR(t,n,T9(e).buffer)))}if(Array.isArray(e))return}yde(t,e,n)},ide)];let Wx,Bz=globalThis.trustedTypes;function Hz(t){Wx===void 0&&(Wx=function(){let n=null;if(!Bz)return n;try{const r=i=>i;n=Bz.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}());var e=Wx;return new class{constructor(n){this.g=n}toString(){return this.g+""}}(e?e.createScriptURL(t):t)}function uYe(t,...e){if(e.length===0)return Hz(t[0]);let n=t[0];for(let r=0;r<e.length;r++)n+=encodeURIComponent(e[r])+t[r+1];return Hz(n)}var Sde=[0,Er,Ra,er,-1,MR,Ra,-1],dYe=class extends He{constructor(t){super(t)}},Ede=[0,er,fn,er,Ra,-1,f0(function(t,e,n){return(t.h===0||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,JWe,e):e.push(If(t.g)),!0)},function(t,e,n){if((e=d0(o0,e))!=null&&e.length){n=x9(t,n);for(let r=0;r<e.length;r++)kR(t.g,e[r]);A9(t,n)}},sde),fn,-1,[0,er,-1],Ra,er,-1],wde=[0,fn,-2],Vz=class extends He{constructor(t){super(t)}},Cde=[0],Tde=[0,Er,er,1,er,-3],xo=class extends He{constructor(t){super(t,2)}},Vr={};Vr[336783863]=[0,fn,er,-1,Er,[0,[1,2,3,4,5,6,7,8],gn,Cde,gn,Ede,gn,wde,gn,Tde,gn,Sde,gn,[0,fn,-2],gn,[0,fn,Ra],gn,[0,Ra,fn]],[0,fn],er,[0,[1,3],[2,4],gn,[0,MR],-1,gn,[0,Qi],-1,ni,[0,fn,-1]],fn];var qz=[0,zx,-1,Wg,-3,zx,MR,Hd,bg,zx,-1,Wg,bg,Wg,-2,Hd];function Oo(t,e){eO(t,2,a0(e),"")}function $n(t,e){RR(t,3,e)}function $t(t,e){RR(t,4,e)}var Ss=class extends He{constructor(t){super(t,500)}o(t){return Ye(this,0,7,t)}},Jy=[-1,{}],Gz=[0,fn,1,Jy],Kz=[0,fn,Qi,Jy];function Mo(t,e){C3(t,1,Ss,e)}function zn(t,e){RR(t,10,e)}function Zt(t,e){RR(t,15,e)}var ro=class extends He{constructor(t){super(t,500)}o(t){return Ye(this,0,1001,t)}},Rde=[-500,ni,[-500,Hd,-1,Qi,-3,[-2,Vr,er],ni,$z,bg,-1,Gz,Kz,ni,[0,Hd,Wg],Hd,qz,bg,Qi,987,Qi],4,ni,[-500,fn,-1,[-1,{}],998,fn],ni,[-500,fn,Qi,-1,[-2,{},er],997,Qi,-1],bg,ni,[-500,fn,Qi,Jy,998,Qi],Qi,bg,Gz,Kz,ni,[0,Hd,-1,Jy],Qi,-2,qz,Hd,-1,Wg,[0,Wg,cYe],978,Jy,ni,$z];ro.prototype.g=DR(Rde);var fYe=qf(ro,Rde),hYe=class extends He{constructor(t){super(t)}},Ide=class extends He{constructor(e){super(e)}g(){return $u(this,hYe,1)}},kde=[0,ni,[0,Er,Hr,fn,-1]],NR=qf(Ide,kde),pYe=class extends He{constructor(t){super(t)}},mYe=class extends He{constructor(e){super(e)}},Yx=class extends He{constructor(t){super(t)}h(){return zt(this,pYe,2)}g(){return $u(this,mYe,5)}},xde=qf(class extends He{constructor(t){super(t)}},[0,Qi,MR,F9,[0,Ra,[0,Er,-3],[0,Hr,-3],[0,Er,-1,[0,ni,[0,Er,-2]]],ni,[0,Hr,-1,fn,Hr]],fn,-1,kf,ni,[0,Er,Hr],Qi,kf]),Ade=class extends He{constructor(t){super(t)}},Yg=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,Hr,-4]]),Pde=class extends He{constructor(t){super(t)}},Y_=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,Hr,-4]]),gYe=class extends He{constructor(t){super(t)}},vYe=[0,Er,-1,F9,Ra],Lde=class extends He{constructor(t){super(t)}};Lde.prototype.g=DR([0,Hr,-4,kf]);var yYe=class extends He{constructor(t){super(t)}},bYe=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,1,Er,fn,kde],kf]),zz=class extends He{constructor(t){super(t)}},_Ye=class extends He{constructor(t){super(t)}oa(){const t=Vue(this);return t??yp()}},SYe=class extends He{constructor(t){super(t)}},Ode=[1,2],EYe=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,Ode,gn,[0,F9],gn,[0,_de],Er,fn],kf]),$9=class extends He{constructor(t){super(t)}},Mde=[0,fn,Er,Hr,Qi,-1],Wz=class extends He{constructor(t){super(t)}},wYe=[0,er,-1],Yz=class extends He{constructor(t){super(t)}},qw=[1,2,3,4,5],I3=class extends He{constructor(t){super(t)}g(){return Vue(this)!=null}h(){return Ta(this,2)!=null}},rr=class extends He{constructor(t){super(t)}g(){return Nue(kv(this,2))??!1}},Dde=[0,_de,fn,[0,Er,kf,-1],[0,oYe,kf]],xr=[0,Dde,er,[0,qw,gn,Tde,gn,Ede,gn,Sde,gn,Cde,gn,wde],Ra],UR=class extends He{constructor(t){super(t)}},B9=[0,xr,Hr,-1,Er],CYe=hc(502141897,UR);Vr[502141897]=B9;var TYe=qf(class extends He{constructor(t){super(t)}},[0,[0,Ra,-1,sYe,aYe],vYe]),Nde=class extends He{constructor(t){super(t)}},Ude=class extends He{constructor(t){super(t)}},H9=[0,xr,Hr,[0,xr],er],jde=[0,xr,B9,H9,Hr,[0,[0,Dde]]],RYe=hc(508968150,Ude);Vr[508968150]=jde,Vr[508968149]=H9;var Fde=class extends He{constructor(t){super(t)}},IYe=hc(513916220,Fde);Vr[513916220]=[0,xr,jde,Er];var Vm=class extends He{constructor(t){super(t)}h(){return zt(this,$9,2)}g(){Fn(this,2)}},$de=[0,xr,Mde];Vr[478825465]=$de;var kYe=class extends He{constructor(t){super(t)}},Bde=class extends He{constructor(e){super(e)}},V9=class extends He{constructor(e){super(e)}},q9=class extends He{constructor(t){super(t)}},Hde=class extends He{constructor(t){super(t)}},Xz=[0,xr,[0,xr],$de,-1],Vde=[0,xr,Hr,Er],G9=[0,xr,Hr],qde=[0,xr,Vde,G9,Hr],xYe=hc(479097054,Hde);Vr[479097054]=[0,xr,qde,Xz],Vr[463370452]=Xz,Vr[464864288]=Vde;var AYe=hc(462713202,q9);Vr[462713202]=qde,Vr[474472470]=G9;var PYe=class extends He{constructor(t){super(t)}},Gde=class extends He{constructor(t){super(t)}},Kde=class extends He{constructor(t){super(t)}},zde=class extends He{constructor(t){super(t)}},K9=[0,xr,Hr,-1,Er],sO=[0,xr,Hr,er];zde.prototype.g=DR([0,xr,G9,[0,xr],B9,H9,K9,sO]);var Wde=class extends He{constructor(t){super(t)}},LYe=hc(456383383,Wde);Vr[456383383]=[0,xr,Mde];var Yde=class extends He{constructor(t){super(t)}},OYe=hc(476348187,Yde);Vr[476348187]=[0,xr,wYe];var Xde=class extends He{constructor(t){super(t)}},Jz=class extends He{constructor(t){super(t)}},Jde=[0,Ra,-1],MYe=hc(458105876,class extends He{constructor(t){super(t)}g(){var t=this.u;const e=0|t[ze],n=2&e;return t=function(r,i,s){var o=Jz;const a=2&i;let c=!1;if(s==null){if(a)return Lz();s=[]}else if(s.constructor===Ca){if((2&s.L)==0||a)return s;s=s.X()}else Array.isArray(s)?c=!!(2&(0|s[ze])):s=[];if(a){if(!s.length)return Lz();c||(c=!0,s0(s))}else c&&(c=!1,s=que(s));return c||(64&(0|s[ze])?s[ze]&=-33:32&i&&yR(s,32)),ur(r,i,2,o=new Ca(s,o,HWe,void 0)),o}(t,e,Yu(t,e,2)),!n&&Jz&&(t.ra=!0),t}});Vr[458105876]=[0,Jde,iYe,[!0,kf,[0,fn,-1,Qi]]];var z9=class extends He{constructor(t){super(t)}},Qde=hc(458105758,z9);Vr[458105758]=[0,xr,fn,Jde];var Zde=class extends He{constructor(t){super(t)}},DYe=hc(443442058,Zde);Vr[443442058]=[0,xr,fn,Er,Hr,Qi,-1,er,Hr],Vr[514774813]=K9;var efe=class extends He{constructor(t){super(t)}},NYe=hc(516587230,efe);function oO(t,e){return e=e?e.clone():new $9,t.displayNamesLocale!==void 0?Fn(e,1,a0(t.displayNamesLocale)):t.displayNamesLocale===void 0&&Fn(e,1),t.maxResults!==void 0?sl(e,2,t.maxResults):"maxResults"in t&&Fn(e,2),t.scoreThreshold!==void 0?Ve(e,3,t.scoreThreshold):"scoreThreshold"in t&&Fn(e,3),t.categoryAllowlist!==void 0?T3(e,4,t.categoryAllowlist):"categoryAllowlist"in t&&Fn(e,4),t.categoryDenylist!==void 0?T3(e,5,t.categoryDenylist):"categoryDenylist"in t&&Fn(e,5),e}function W9(t,e=-1,n=""){return{categories:t.map(r=>({index:fa(r,1)??0??-1,score:Tr(r,2)??0,categoryName:Ta(r,3)??""??"",displayName:Ta(r,4)??""??""})),headIndex:e,headName:n}}function tfe(t){var e=$h(t,3,Vf,Fh()),n=$h(t,2,o0,Fh()),r=$h(t,1,Iv,Fh()),i=$h(t,9,Iv,Fh());const s={categories:[],keypoints:[]};for(let o=0;o<e.length;o++)s.categories.push({score:e[o],index:n[o]??-1,categoryName:r[o]??"",displayName:i[o]??""});if((e=zt(t,Yx,4)?.h())&&(s.boundingBox={originX:fa(e,1)??0,originY:fa(e,2)??0,width:fa(e,3)??0,height:fa(e,4)??0,angle:0}),zt(t,Yx,4)?.g().length)for(const o of zt(t,Yx,4).g())s.keypoints.push({x:Hw(o,1)??0,y:Hw(o,2)??0,score:Hw(o,4)??0,label:Ta(o,3)??""});return s}function jR(t){const e=[];for(const n of $u(t,Pde,1))e.push({x:Tr(n,1)??0,y:Tr(n,2)??0,z:Tr(n,3)??0,visibility:Tr(n,4)??0});return e}function Qy(t){const e=[];for(const n of $u(t,Ade,1))e.push({x:Tr(n,1)??0,y:Tr(n,2)??0,z:Tr(n,3)??0,visibility:Tr(n,4)??0});return e}function Qz(t){return Array.from(t,e=>e>127?e-256:e)}function Zz(t,e){if(t.length!==e.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${t.length} vs. ${e.length}).`);let n=0,r=0,i=0;for(let s=0;s<t.length;s++)n+=t[s]*e[s],r+=t[s]*t[s],i+=e[s]*e[s];if(r<=0||i<=0)throw Error("Cannot compute cosine similarity on embedding with 0 norm.");return n/Math.sqrt(r*i)}let CE;Vr[516587230]=[0,xr,K9,sO,Hr],Vr[518928384]=sO;const UYe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);async function nfe(){if(CE===void 0)try{await WebAssembly.instantiate(UYe),CE=!0}catch{CE=!1}return CE}async function X1(t,e=uYe``){const n=await nfe()?"wasm_internal":"wasm_nosimd_internal";return{wasmLoaderPath:`${e}/${t}_${n}.js`,wasmBinaryPath:`${e}/${t}_${n}.wasm`}}var Ph=class{};function rfe(){var t=navigator;return typeof OffscreenCanvas<"u"&&(!function(e=navigator){return(e=e.userAgent).includes("Safari")&&!e.includes("Chrome")}(t)||!!((t=t.userAgent.match(/Version\/([\d]+).*Safari/))&&t.length>=1&&Number(t[1])>=17))}async function eW(t){if(typeof importScripts!="function"){const e=document.createElement("script");return e.src=t.toString(),e.crossOrigin="anonymous",new Promise((n,r)=>{e.addEventListener("load",()=>{n()},!1),e.addEventListener("error",i=>{r(i)},!1),document.body.appendChild(e)})}importScripts(t.toString())}function ife(t){return t.videoWidth!==void 0?[t.videoWidth,t.videoHeight]:t.naturalWidth!==void 0?[t.naturalWidth,t.naturalHeight]:t.displayWidth!==void 0?[t.displayWidth,t.displayHeight]:[t.width,t.height]}function Ke(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(e=t.i.stringToNewUTF8(e)),t.i._free(e)}function tW(t,e,n){if(!t.i.canvas)throw Error("No OpenGL canvas configured.");if(n?t.i._bindTextureToStream(n):t.i._bindTextureToCanvas(),!(n=t.i.canvas.getContext("webgl2")||t.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[r,i]=ife(e);return!t.l||r===t.i.canvas.width&&i===t.i.canvas.height||(t.i.canvas.width=r,t.i.canvas.height=i),[r,i]}function nW(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const r=new Uint32Array(e.length);for(let i=0;i<e.length;i++)r[i]=t.i.stringToNewUTF8(e[i]);e=t.i._malloc(4*r.length),t.i.HEAPU32.set(r,e>>2),n(e);for(const i of r)t.i._free(i);t.i._free(e)}function Ic(t,e,n){t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=n}function Cd(t,e,n){let r=[];t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=(i,s,o)=>{s?(n(r,o),r=[]):r.push(i)}}Ph.forVisionTasks=function(t){return X1("vision",t)},Ph.forTextTasks=function(t){return X1("text",t)},Ph.forGenAiExperimentalTasks=function(t){return X1("genai_experimental",t)},Ph.forGenAiTasks=function(t){return X1("genai",t)},Ph.forAudioTasks=function(t){return X1("audio",t)},Ph.isSimdSupported=function(){return nfe()};async function jYe(t,e,n,r){return t=await(async(i,s,o,a,c)=>{if(s&&await eW(s),!self.ModuleFactory||o&&(await eW(o),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((s=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(s.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new i(c,a)})(t,n.wasmLoaderPath,n.assetLoaderPath,e,{locateFile:i=>i.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&i.endsWith(".data")?n.assetBinaryPath.toString():i}),await t.o(r),t}function Xx(t,e){const n=zt(t.baseOptions,I3,1)||new I3;typeof e=="string"?(Fn(n,2,a0(e)),Fn(n,1)):e instanceof Uint8Array&&(Fn(n,1,a9(e,!1)),Fn(n,2)),Ye(t.baseOptions,0,1,n)}function rW(t){try{const e=t.G.length;if(e===1)throw Error(t.G[0].message);if(e>1)throw Error("Encountered multiple errors: "+t.G.map(n=>n.message).join(", "))}finally{t.G=[]}}function je(t,e){t.B=Math.max(t.B,e)}function FR(t,e){t.A=new Ss,Oo(t.A,"PassThroughCalculator"),$n(t.A,"free_memory"),$t(t.A,"free_memory_unused_out"),zn(e,"free_memory"),Mo(e,t.A)}function Av(t,e){$n(t.A,e),$t(t.A,e+"_unused_out")}function $R(t){t.g.addBoolToStream(!0,"free_memory",t.B)}var Gw=class{constructor(t){this.g=t,this.G=[],this.B=0,this.g.setAutoRenderToScreen(!1)}l(t,e=!0){if(e){const n=t.baseOptions||{};if(t.baseOptions?.modelAssetBuffer&&t.baseOptions?.modelAssetPath)throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!(zt(this.baseOptions,I3,1)?.g()||zt(this.baseOptions,I3,1)?.h()||t.baseOptions?.modelAssetBuffer||t.baseOptions?.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(r,i){let s=zt(r.baseOptions,Yz,3);if(!s){var o=s=new Yz,a=new Vz;Xy(o,4,qw,a)}"delegate"in i&&(i.delegate==="GPU"?(i=s,o=new dYe,Xy(i,2,qw,o)):(i=s,o=new Vz,Xy(i,4,qw,o))),Ye(r.baseOptions,0,3,s)}(this,n),n.modelAssetPath)return fetch(n.modelAssetPath.toString()).then(r=>{if(r.ok)return r.arrayBuffer();throw Error(`Failed to fetch model: ${n.modelAssetPath} (${r.status})`)}).then(r=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(r),!0,!1,!1),Xx(this,"/model.dat"),this.m(),this.I()});if(n.modelAssetBuffer instanceof Uint8Array)Xx(this,n.modelAssetBuffer);else if(n.modelAssetBuffer)return async function(r){const i=[];for(var s=0;;){const{done:o,value:a}=await r.read();if(o)break;i.push(a),s+=a.length}if(i.length===0)return new Uint8Array(0);if(i.length===1)return i[0];r=new Uint8Array(s),s=0;for(const o of i)r.set(o,s),s+=o.length;return r}(n.modelAssetBuffer).then(r=>{Xx(this,r),this.m(),this.I()})}return this.m(),this.I(),Promise.resolve()}I(){}da(){let t;if(this.g.da(e=>{t=fYe(e)}),!t)throw Error("Failed to retrieve CalculatorGraphConfig");return t}setGraph(t,e){this.g.attachErrorListener((n,r)=>{this.G.push(Error(r))}),this.g.La(),this.g.setGraph(t,e),this.A=void 0,rW(this)}finishProcessing(){this.g.finishProcessing(),rW(this)}close(){this.A=void 0,this.g.closeGraph()}};function Iu(t,e){if(!t)throw Error(`Unable to obtain required WebGL resource: ${e}`);return t}Gw.prototype.close=Gw.prototype.close,function(t,e){t=t.split(".");var n,r=vp;for((t[0]in r)||r.execScript===void 0||r.execScript("var "+t[0]);t.length&&(n=t.shift());)t.length||e===void 0?r=r[n]&&r[n]!==Object.prototype[n]?r[n]:r[n]={}:r[n]=e}("TaskRunner",Gw);class FYe{constructor(e,n,r,i){this.g=e,this.h=n,this.m=r,this.l=i}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function iW(t,e,n){const r=t.g;if(n=Iu(r.createShader(n),"Failed to create WebGL shader"),r.shaderSource(n,e),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${r.getShaderInfoLog(n)}`);return r.attachShader(t.h,n),n}function sW(t,e){const n=t.g,r=Iu(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const i=Iu(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(t.O),n.vertexAttribPointer(t.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const s=Iu(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,s),n.enableVertexAttribArray(t.I),n.vertexAttribPointer(t.I,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(e?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new FYe(n,r,i,s)}function Y9(t,e){if(t.g){if(e!==t.g)throw Error("Cannot change GL context once initialized")}else t.g=e}function X9(t,e,n,r){return Y9(t,e),t.h||(t.m(),t.C()),n?(t.s||(t.s=sW(t,!0)),n=t.s):(t.v||(t.v=sW(t,!1)),n=t.v),e.useProgram(t.h),n.bind(),t.l(),t=r(),n.g.bindVertexArray(null),t}function BR(t,e,n){return Y9(t,e),t=Iu(e.createTexture(),"Failed to create texture"),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n??e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,n??e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),t}function HR(t,e,n){Y9(t,e),t.A||(t.A=Iu(e.createFramebuffer(),"Failed to create framebuffe.")),e.bindFramebuffer(e.FRAMEBUFFER,t.A),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}function J9(t){t.g?.bindFramebuffer(t.g.FRAMEBUFFER,null)}var Q9=class{G(){return`
213
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function y3(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var j_=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,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=Ef(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(v){e={error:v}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else o.remove(this);var d=this.initialTeardown;if(Rn(d))try{d()}catch(v){s=v instanceof Nx?v.errors:[v]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var m=Ef(h),g=m.next();!g.done;g=m.next()){var y=g.value;try{$K(y)}catch(v){s=s??[],v instanceof Nx?s=Ea(Ea([],Sa(s)),Sa(v.errors)):s.push(v)}}}catch(v){r={error:v}}finally{try{g&&!g.done&&(i=m.return)&&i.call(m)}finally{if(r)throw r.error}}}if(s)throw new Nx(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)$K(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&y3(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&y3(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),ile=j_.EMPTY;function sle(t){return t instanceof j_||t&&"closed"in t&&Rn(t.remove)&&Rn(t.add)&&Rn(t.unsubscribe)}function $K(t){Rn(t)?t():t.unsubscribe()}var iqe={Promise:void 0},sqe={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,Ea([t,e],Sa(n)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function ole(t){sqe.setTimeout(function(){throw t})}function wv(){}function Nw(t){t()}var M8=function(t){cc(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,sle(n)&&n.add(r)):r.destination=cqe,r}return e.create=function(n,r,i){return new FL(n,r,i)},e.prototype.next=function(n){this.isStopped||this._next(n)},e.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(j_),oqe=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){yE(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){yE(r)}else yE(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){yE(n)}},t}(),FL=function(t){cc(e,t);function e(n,r,i){var s=t.call(this)||this,o;return Rn(n)||!n?o={next:n??void 0,error:r??void 0,complete:i??void 0}:o=n,s.destination=new oqe(o),s}return e}(M8);function yE(t){ole(t)}function aqe(t){throw t}var cqe={closed:!0,next:wv,error:aqe,complete:wv},D8=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function $f(t){return t}function lqe(t){return t.length===0?$f:t.length===1?t[0]:function(n){return t.reduce(function(r,i){return i(r)},n)}}var Wn=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var i=this,s=dqe(e)?e:new FL(e,n,r);return Nw(function(){var o=i,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?i._subscribe(s):i._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=BK(n),new n(function(i,s){var o=new FL({next:function(a){try{e(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[D8]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return lqe(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=BK(e),new e(function(r,i){var s;n.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},t.create=function(e){return new t(e)},t}();function BK(t){var e;return(e=t??iqe.Promise)!==null&&e!==void 0?e:Promise}function uqe(t){return t&&Rn(t.next)&&Rn(t.error)&&Rn(t.complete)}function dqe(t){return t&&t instanceof M8||uqe(t)&&sle(t)}function fqe(t){return Rn(t?.lift)}function Lr(t){return function(e){if(fqe(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Yn(t,e,n,r,i){return new hqe(t,e,n,r,i)}var hqe=function(t){cc(e,t);function e(n,r,i,s,o,a){var c=t.call(this,n)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(l){try{r(l)}catch(d){n.error(d)}}:t.prototype._next,c._error=s?function(l){try{s(l)}catch(d){n.error(d)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=i?function(){try{i()}catch(l){n.error(l)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e}(M8),pqe=rle(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),ii=function(t){cc(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new HK(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new pqe},e.prototype.next=function(n){var r=this;Nw(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=Ef(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(n)}}catch(l){i={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(n){var r=this;Nw(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var i=r.observers;i.length;)i.shift().error(n)}})},e.prototype.complete=function(){var n=this;Nw(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.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 n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?ile:(this.currentObservers=null,a.push(n),new j_(function(){r.currentObservers=null,y3(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?n.error(s):o&&n.complete()},e.prototype.asObservable=function(){var n=new Wn;return n.source=this,n},e.create=function(n,r){return new HK(n,r)},e}(Wn),HK=function(t){cc(e,t);function e(n,r){var i=t.call(this)||this;return i.destination=n,i.source=r,i}return e.prototype.next=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,n)},e.prototype.error=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&i!==void 0?i:ile},e}(ii),_s=function(t){cc(e,t);function e(n){var r=t.call(this)||this;return r._value=n,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(n){var r=t.prototype._subscribe.call(this,n);return!r.closed&&n.next(this._value),r},e.prototype.getValue=function(){var n=this,r=n.hasError,i=n.thrownError,s=n._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(n){t.prototype.next.call(this,this._value=n)},e}(ii),mqe={now:function(){return Date.now()}},gqe=function(t){cc(e,t);function e(n,r){return t.call(this)||this}return e.prototype.schedule=function(n,r){return this},e}(j_),VK={setInterval:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,Ea([t,e],Sa(n)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},vqe=function(t){cc(e,t);function e(n,r){var i=t.call(this,n,r)||this;return i.scheduler=n,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(n,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=n;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(n,r,i){return i===void 0&&(i=0),VK.setInterval(n.flush.bind(n,this),i)},e.prototype.recycleAsyncId=function(n,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&VK.clearInterval(r)},e.prototype.execute=function(n,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(n,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(n,r){var i=!1,s;try{this.work(n)}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 n=this,r=n.id,i=n.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,y3(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(gqe),qK=function(){function t(e,n){n===void 0&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(e,n,r){return n===void 0&&(n=0),new this.schedulerActionCtor(this,e).schedule(r,n)},t.now=mqe.now,t}(),yqe=function(t){cc(e,t);function e(n,r){r===void 0&&(r=qK.now);var i=t.call(this,n,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(n){var r=this.actions;if(this._active){r.push(n);return}var i;this._active=!0;do if(i=n.execute(n.state,n.delay))break;while(n=r.shift());if(this._active=!1,i){for(;n=r.shift();)n.unsubscribe();throw i}},e}(qK),lR=new yqe(vqe),bqe=lR,vg=new Wn(function(t){return t.complete()});function ale(t){return t&&Rn(t.schedule)}function N8(t){return t[t.length-1]}function U8(t){return Rn(N8(t))?t.pop():void 0}function F_(t){return ale(N8(t))?t.pop():void 0}function _qe(t,e){return typeof N8(t)=="number"?t.pop():e}var j8=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function cle(t){return Rn(t?.then)}function lle(t){return Rn(t[D8])}function ule(t){return Symbol.asyncIterator&&Rn(t?.[Symbol.asyncIterator])}function dle(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Sqe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var fle=Sqe();function hle(t){return Rn(t?.[fle])}function ple(t){return yM(this,arguments,function(){var n,r,i,s;return $T(this,function(o){switch(o.label){case 0:n=t.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,Eu(n.read())];case 3:return r=o.sent(),i=r.value,s=r.done,s?[4,Eu(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,Eu(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function mle(t){return Rn(t?.getReader)}function zi(t){if(t instanceof Wn)return t;if(t!=null){if(lle(t))return Eqe(t);if(j8(t))return wqe(t);if(cle(t))return Cqe(t);if(ule(t))return gle(t);if(hle(t))return Tqe(t);if(mle(t))return Rqe(t)}throw dle(t)}function Eqe(t){return new Wn(function(e){var n=t[D8]();if(Rn(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function wqe(t){return new Wn(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Cqe(t){return new Wn(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,ole)})}function Tqe(t){return new Wn(function(e){var n,r;try{for(var i=Ef(t),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()})}function gle(t){return new Wn(function(e){Iqe(t,e).catch(function(n){return e.error(n)})})}function Rqe(t){return gle(ple(t))}function Iqe(t,e){var n,r,i,s;return vM(this,void 0,void 0,function(){var o,a;return $T(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=bM(t),c.label=1;case 1:return[4,n.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),i={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.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 cf(t,e,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!i)return s}function vle(t,e){return e===void 0&&(e=0),Lr(function(n,r){n.subscribe(Yn(r,function(i){return cf(r,t,function(){return r.next(i)},e)},function(){return cf(r,t,function(){return r.complete()},e)},function(i){return cf(r,t,function(){return r.error(i)},e)}))})}function yle(t,e){return e===void 0&&(e=0),Lr(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function kqe(t,e){return zi(t).pipe(yle(e),vle(e))}function xqe(t,e){return zi(t).pipe(yle(e),vle(e))}function Aqe(t,e){return new Wn(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Pqe(t,e){return new Wn(function(n){var r;return cf(n,e,function(){r=t[fle](),cf(n,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){n.error(a);return}o?n.complete():n.next(s)},0,!0)}),function(){return Rn(r?.return)&&r.return()}})}function ble(t,e){if(!t)throw new Error("Iterable cannot be null");return new Wn(function(n){cf(n,e,function(){var r=t[Symbol.asyncIterator]();cf(n,e,function(){r.next().then(function(i){i.done?n.complete():n.next(i.value)})},0,!0)})})}function Lqe(t,e){return ble(ple(t),e)}function Oqe(t,e){if(t!=null){if(lle(t))return kqe(t,e);if(j8(t))return Aqe(t,e);if(cle(t))return xqe(t,e);if(ule(t))return ble(t,e);if(hle(t))return Pqe(t,e);if(mle(t))return Lqe(t,e)}throw dle(t)}function $_(t,e){return e?Oqe(t,e):zi(t)}function Ct(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t);return $_(t,n)}function Mqe(t){return t instanceof Date&&!isNaN(t)}function Re(t,e){return Lr(function(n,r){var i=0;n.subscribe(Yn(r,function(s){r.next(t.call(e,s,i++))}))})}var Dqe=Array.isArray;function Nqe(t,e){return Dqe(e)?t.apply(void 0,Ea([],Sa(e))):t(e)}function F8(t){return Re(function(e){return Nqe(t,e)})}var Uqe=Array.isArray,jqe=Object.getPrototypeOf,Fqe=Object.prototype,$qe=Object.keys;function _le(t){if(t.length===1){var e=t[0];if(Uqe(e))return{args:e,keys:null};if(Bqe(e)){var n=$qe(e);return{args:n.map(function(r){return e[r]}),keys:n}}}return{args:t,keys:null}}function Bqe(t){return t&&typeof t=="object"&&jqe(t)===Fqe}function Sle(t,e){return t.reduce(function(n,r,i){return n[r]=e[i],n},{})}function Xt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t),r=U8(t),i=_le(t),s=i.args,o=i.keys;if(s.length===0)return $_([],n);var a=new Wn(Hqe(s,n,o?function(c){return Sle(o,c)}:$f));return r?a.pipe(F8(r)):a}function Hqe(t,e,n){return n===void 0&&(n=$f),function(r){GK(e,function(){for(var i=t.length,s=new Array(i),o=i,a=i,c=function(d){GK(e,function(){var h=$_(t[d],e),m=!1;h.subscribe(Yn(r,function(g){s[d]=g,m||(m=!0,a--),a||r.next(n(s.slice()))},function(){--o||r.complete()}))},r)},l=0;l<i;l++)c(l)},r)}}function GK(t,e,n){t?cf(n,t,e):e()}function Vqe(t,e,n,r,i,s,o,a){var c=[],l=0,d=0,h=!1,m=function(){h&&!c.length&&!l&&e.complete()},g=function(v){return l<r?y(v):c.push(v)},y=function(v){l++;var w=!1;zi(n(v,d++)).subscribe(Yn(e,function(S){e.next(S)},function(){w=!0},void 0,function(){if(w)try{l--;for(var S=function(){var R=c.shift();o||y(R)};c.length&&l<r;)S();m()}catch(R){e.error(R)}}))};return t.subscribe(Yn(e,g,function(){h=!0,m()})),function(){}}function B_(t,e,n){return n===void 0&&(n=1/0),Rn(e)?B_(function(r,i){return Re(function(s,o){return e(r,s,i,o)})(zi(t(r,i)))},n):(typeof e=="number"&&(n=e),Lr(function(r,i){return Vqe(r,i,t,n)}))}function Ele(t){return t===void 0&&(t=1/0),B_($f,t)}function qqe(){return Ele(1)}function mp(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return qqe()($_(t,F_(t)))}function Gqe(t){return new Wn(function(e){zi(t()).subscribe(e)})}function Kqe(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=U8(t),r=_le(t),i=r.args,s=r.keys,o=new Wn(function(a){var c=i.length;if(!c){a.complete();return}for(var l=new Array(c),d=c,h=c,m=function(y){var v=!1;zi(i[y]).subscribe(Yn(a,function(w){v||(v=!0,h--),l[y]=w},function(){return d--},void 0,function(){(!d||!v)&&(h||a.next(s?Sle(s,l):l),a.complete())}))},g=0;g<c;g++)m(g)});return n?o.pipe(F8(n)):o}var zqe=["addListener","removeListener"],Wqe=["addEventListener","removeEventListener"],Yqe=["on","off"];function Zo(t,e,n,r){if(Rn(n)&&(r=n,n=void 0),r)return Zo(t,e,n).pipe(F8(r));var i=Sa(Qqe(t)?Wqe.map(function(a){return function(c){return t[a](e,c,n)}}):Xqe(t)?zqe.map(KK(t,e)):Jqe(t)?Yqe.map(KK(t,e)):[],2),s=i[0],o=i[1];if(!s&&j8(t))return B_(function(a){return Zo(a,e,n)})(zi(t));if(!s)throw new TypeError("Invalid event target");return new Wn(function(a){var c=function(){for(var l=[],d=0;d<arguments.length;d++)l[d]=arguments[d];return a.next(1<l.length?l:l[0])};return s(c),function(){return o(c)}})}function KK(t,e){return function(n){return function(r){return t[n](e,r)}}}function Xqe(t){return Rn(t.addListener)&&Rn(t.removeListener)}function Jqe(t){return Rn(t.on)&&Rn(t.off)}function Qqe(t){return Rn(t.addEventListener)&&Rn(t.removeEventListener)}function du(t,e,n){t===void 0&&(t=0),n===void 0&&(n=bqe);var r=-1;return e!=null&&(ale(e)?n=e:r=e),new Wn(function(i){var s=Mqe(t)?+t-n.now():t;s<0&&(s=0);var o=0;return n.schedule(function(){i.closed||(i.next(o++),0<=r?this.schedule(void 0,r):i.complete())},s)})}function Zqe(t,e){return e===void 0&&(e=lR),du(t,t,e)}function H_(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t),r=_qe(t,1/0),i=t;return i.length?i.length===1?zi(i[0]):Ele(r)($_(i,n)):vg}var $L=new Wn(wv),eGe=Array.isArray;function tGe(t){return t.length===1&&eGe(t[0])?t[0]:t}function es(t,e){return Lr(function(n,r){var i=0;n.subscribe(Yn(r,function(s){return t.call(e,s,i++)&&r.next(s)}))})}function nGe(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t=tGe(t),t.length===1?zi(t[0]):new Wn(rGe(t))}function rGe(t){return function(e){for(var n=[],r=function(s){n.push(zi(t[s]).subscribe(Yn(e,function(o){if(n){for(var a=0;a<n.length;a++)a!==s&&n[a].unsubscribe();n=null}e.next(o)})))},i=0;n&&!e.closed&&i<t.length;i++)r(i)}}function wle(t){return Lr(function(e,n){var r=!1,i=null,s=null,o=!1,a=function(){if(s?.unsubscribe(),s=null,r){r=!1;var l=i;i=null,n.next(l)}o&&n.complete()},c=function(){s=null,o&&n.complete()};e.subscribe(Yn(n,function(l){r=!0,i=l,s||zi(t(l)).subscribe(s=Yn(n,a,c))},function(){o=!0,(!r||!s||s.closed)&&n.complete()}))})}function iGe(t,e,n,r,i){return function(s,o){var a=n,c=e,l=0;s.subscribe(Yn(o,function(d){var h=l++;c=a?t(c,d,h):(a=!0,d),o.next(c)},i))}}function Uw(t){return t<=0?function(){return vg}:Lr(function(e,n){var r=0;e.subscribe(Yn(n,function(i){++r<=t&&(n.next(i),t<=r&&n.complete())}))})}function sGe(){return Lr(function(t,e){t.subscribe(Yn(e,wv))})}function oGe(t){return Re(function(){return t})}function aGe(t,e){return B_(function(n,r){return zi(t(n,r)).pipe(Uw(1),oGe(n))})}function cGe(t,e){e===void 0&&(e=lR);var n=du(t,e);return aGe(function(){return n})}function Kc(t,e){return e===void 0&&(e=$f),t=t??lGe,Lr(function(n,r){var i,s=!0;n.subscribe(Yn(r,function(o){var a=e(o);(s||!t(i,a))&&(s=!1,i=a,r.next(o))}))})}function lGe(t,e){return t===e}function uGe(t,e){return Kc(function(n,r){return n[t]===r[t]})}function dGe(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(n){return mp(n,Ct.apply(void 0,Ea([],Sa(t))))}}function fGe(t){return Lr(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function jw(){return Lr(function(t,e){var n,r=!1;t.subscribe(Yn(e,function(i){var s=n;n=i,r&&e.next([s,i]),r=!0}))})}function ql(t,e){return Lr(iGe(t,e,arguments.length>=2,!0))}function hGe(t){return es(function(e,n){return t<=n})}function pGe(t){return Lr(function(e,n){var r=!1,i=0;e.subscribe(Yn(n,function(s){return(r||(r=!t(s,i++)))&&n.next(s)}))})}function dn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=F_(t);return Lr(function(r,i){(n?mp(t,r,n):mp(t,r)).subscribe(i)})}function Ot(t,e){return Lr(function(n,r){var i=null,s=0,o=!1,a=function(){return o&&!i&&r.complete()};n.subscribe(Yn(r,function(c){i?.unsubscribe();var l=0,d=s++;zi(t(c,d)).subscribe(i=Yn(r,function(h){return r.next(e?e(c,h,d,l++):h)},function(){i=null,a()}))},function(){o=!0,a()}))})}function zK(){return Ot($f)}function mGe(t,e){return Lr(function(n,r){var i=e;return Ot(function(s,o){return t(i,s,o)},function(s,o){return i=o,o})(n).subscribe(r),function(){i=null}})}function Cle(t){return Lr(function(e,n){zi(t).subscribe(Yn(n,function(){return n.complete()},wv)),!n.closed&&e.subscribe(n)})}function gGe(t,e){return e===void 0&&(e=!1),Lr(function(n,r){var i=0;n.subscribe(Yn(r,function(s){var o=t(s,i++);(o||e)&&r.next(s),!o&&r.complete()}))})}function vGe(t,e,n){var r=Rn(t)||e||n?{next:t,error:e,complete:n}:t;return r?Lr(function(i,s){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var a=!0;i.subscribe(Yn(s,function(c){var l;(l=r.next)===null||l===void 0||l.call(r,c),s.next(c)},function(){var c;a=!1,(c=r.complete)===null||c===void 0||c.call(r),s.complete()},function(c){var l;a=!1,(l=r.error)===null||l===void 0||l.call(r,c),s.error(c)},function(){var c,l;a&&((c=r.unsubscribe)===null||c===void 0||c.call(r)),(l=r.finalize)===null||l===void 0||l.call(r)}))}):$f}function yGe(t,e){return Lr(function(n,r){var i=e??{},s=i.leading,o=s===void 0?!0:s,a=i.trailing,c=a===void 0?!1:a,l=!1,d=null,h=null,m=!1,g=function(){h?.unsubscribe(),h=null,c&&(w(),m&&r.complete())},y=function(){h=null,m&&r.complete()},v=function(S){return h=zi(t(S)).subscribe(Yn(r,g,y))},w=function(){if(l){l=!1;var S=d;d=null,r.next(S),!m&&v(S)}};n.subscribe(Yn(r,function(S){l=!0,d=S,!(h&&!h.closed)&&(o?w():v(S))},function(){m=!0,!(c&&l&&h&&!h.closed)&&r.complete()}))})}function BL(t,e,n){e===void 0&&(e=lR);var r=du(t,e);return yGe(function(){return r},n)}function Tle(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=U8(t);return Lr(function(r,i){for(var s=t.length,o=new Array(s),a=t.map(function(){return!1}),c=!1,l=function(h){zi(t[h]).subscribe(Yn(i,function(m){o[h]=m,!c&&!a[h]&&(a[h]=!0,(c=a.every($f))&&(a=null))},wv))},d=0;d<s;d++)l(d);r.subscribe(Yn(i,function(h){if(c){var m=Ea([h],Sa(o));i.next(n?n.apply(void 0,Ea([],Sa(m))):m)}}))})}function Qe(t){const e=_.useCallback(r=>{const i=t.subscribe(r);return()=>i.unsubscribe()},[t]),n=_.useCallback(()=>t.value,[t]);return _.useSyncExternalStore(e,n)}class li{constructor(e,n){this.defaultValue=n,this.setValue=s=>{this._value$.next(s),localStorage.setItem(this.key,JSON.stringify(s))},this.getValue=()=>this._value$.getValue(),this.key=`matrix-setting-${e}`;const r=localStorage.getItem(this.key);let i=n;if(r!==null)try{i=JSON.parse(r)}catch(s){M.warn(`Invalid value stored for setting ${e}: ${r}.`,s)}this._value$=new _s(i),this.value$=this._value$}}function Gn(t){return[Qe(t.value$),t.setValue]}const Rle=new li("opt-in-analytics",null),uR=()=>{const t=Gn(Rle);return Ut.instance.isEnabled()?t:[!1,null]},$8=new li("developer-settings-tab",!1),Ile=new li("duplicate-tiles",0),kle=new li("show-non-member-tiles",!1),B8=new li("debug-tile-layout",!1),Gb=new li("show-connection-stats",!1),WK=new li("audio-input",void 0),YK=new li("audio-output",void 0),XK=new li("video-input",void 0),xle=new li("background-blur",!1),Ale=new li("hand-raised-show-timer",!1),Ple=new li("reactions-show",!0),H8=new li("reactions-play-sound",!0),Lle=new li("sound-effect-volume",.5),Ole=new li("new-membership-manager",!0),V8=new li("experimental-to-device-transport",!0),Mle=new li("mute-all-audio",!1),JK=new li("always-show-self",!0),Dle=new li("always-show-iphone-earpiece",!1);var dR=(t=>(t[t.Guest=0]="Guest",t[t.Registered=1]="Registered",t))(dR||{});const Fc=class Fc{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 WVe,this.eventSignup=new XVe,this.eventCallStarted=new YVe,this.eventLogin=new JVe,this.eventMuteMicrophone=new QVe,this.eventMuteCamera=new ZVe,this.eventUndecryptableToDevice=new eqe,this.eventQualitySurvey=new tqe,this.eventCallDisconnected=new nqe,this.eventCallConnectDuration=new rqe;let n,r;n=Br().posthogApiKey??void 0,r=Br().posthogApiHost??void 0,n&&r?(this.posthog.init(n,{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):(M.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 Fc(CVe)),this.internalInstance}static resetInstance(){this.internalInstance=null}registerSuperProperties(e){this.enabled&&this.posthog.register(e)}static getPlatformProperties(){return{appVersion:"embedded-v0.16.3",matrixBackend:ut?"embedded":"jssdk",callBackend:"livekit",cryptoVersion:ut?void 0:window.matrixclient?.getCrypto()?.getVersion()}}capture(e,n,r){this.enabled&&this.posthog.capture(e,{...n},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 n=await this.getAnalyticsId();try{if(!n&&!ut){const r=e();await this.setAccountAnalyticsId(r),n=await this.hashedEcAnalyticsId(r)}}catch(r){M.log("Unable to identify user for tracking"+r?.toString())}n?this.posthog.identify(n):M.info("No analyticsID is available. Should not try to setup posthog")}}async getAnalyticsId(){const e=window.matrixclient;let n;return ut?n=Br().posthogUserId:n=(await e.getAccountDataFromServer(Fc.ANALYTICS_EVENT_TYPE))?.id??null,n?await this.hashedEcAnalyticsId(n):null}async hashedEcAnalyticsId(e){const n=window.matrixclient,r="ec"+e+n.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(!ut){const n=window.matrixclient,r=await n.getAccountDataFromServer(Fc.ANALYTICS_EVENT_TYPE);await n.setAccountData(Fc.ANALYTICS_EVENT_TYPE,Object.assign({id:e},r))}}getAnonymity(){return this.anonymity}logout(){this.enabled&&this.posthog.reset(),this.optInListener?.unsubscribe(),this.optInListener=null,this.setAnonymity(0)}onLoginStatusChanged(){this.maybeIdentifyUser().catch(()=>M.log("Could not identify user on login status change"))}updateSuperProperties(){this.platformSuperProperties=Fc.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(Fc.getRandomAnalyticsId),await this.identificationPromise,this.userRegisteredInThisSession()&&this.eventSignup.track()),this.anonymity!==0&&this.updateSuperProperties())}trackEvent({eventName:e,...n},r){const i=()=>{this.anonymity==0||this.anonymity==1||this.capture(e,n,r)};this.identificationPromise?this.identificationPromise.then(i,s=>{M.error("Failed to identify user for tracking",s)}):i()}startListeningToSettingsChanges(){this.optInListener??=Rle.value$.subscribe(e=>{this.setAnonymity(e?2:0),this.maybeIdentifyUser().catch(()=>M.log("Could not identify user"))})}setRegistrationType(e){this.registrationType=e,!(this.anonymity==0||this.anonymity==1)&&this.updateSuperProperties()}};Fc.ANALYTICS_EVENT_TYPE="im.vector.analytics",Fc.internalInstance=null;let Ut=Fc;const bGe=2*60*1e3;class _Ge{async forceFlush(){}onStart(e){try{switch(e.name){case"matrix.groupCallMembership":this.onGroupCallMembershipStart(e);return;case"matrix.groupCallMembership.summaryReport":this.onSummaryReportStart(e);return}}catch(n){M.debug(n)}}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(n){return M.warn("Invalid prev call data",e,"error:",n),null}}set prevCall(e){localStorage.setItem("matrix-prev-call",JSON.stringify(e))}onGroupCallMembershipStart(e){const n=this.prevCall,r=e.attributes["matrix.confId"];if(n!==null&&r===n.callId){const i=xG(e.startTime)-n.hangupTs;i<=bGe&&Ut.instance.trackEvent({eventName:"Rejoin",callId:n.callId,rejoinDuration:i})}}onGroupCallMembershipEnd(e){this.prevCall={callId:e.attributes["matrix.confId"],hangupTs:xG(e.endTime)}}onSummaryReportStart(e){const n=e.events.find(r=>r.name==="matrix.stats.summary");if(n!==void 0){const r=n.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"]}`,c=`${r["matrix.stats.summary.maxPacketLoss"]}`,l=`${r["matrix.stats.summary.peerConnections"]}`,d=`${r["matrix.stats.summary.percentageConcealedAudio"]}`,h=`${r["matrix.stats.summary.opponentUsersInCall"]}`,m=`${r["matrix.stats.summary.opponentDevicesInCall"]}`,g=`${r["matrix.stats.summary.diffDevicesToPeerConnections"]}`,y=`${r["matrix.stats.summary.ratioPeerConnectionToDevices"]}`;Ut.instance.trackEvent({eventName:"MediaReceived",callId:e.attributes["matrix.confId"],mediaReceived:i,audioReceived:o,videoReceived:s,maxJitter:a,maxPacketLoss:c,peerConnections:l,percentageConcealedAudio:d,opponentUsersInCall:h,opponentDevicesInCall:m,diffDevicesToPeerConnections:g,ratioPeerConnectionToDevices:y},{send_instantly:!0})}}}async shutdown(){return Promise.resolve()}}const QK=t=>Object.entries(t).map(([e,n])=>({key:e,type:typeof n,value:n}));class SGe{constructor(){this.spans=[]}async forceFlush(){}onStart(e){this.spans.push(e)}onEnd(){}dump(){const e=Date.now()*1e3,n=new Map;for(const s of this.spans){const o=s.spanContext().traceId;let a=n.get(o);a===void 0&&(a=[],n.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:[...n.entries()].map(([s,o])=>({traceID:s,warnings:null,processes:i,spans:o.map(a=>{const c=a.spanContext(),l=wx(a.startTime),d=a.duration[0]===-1?e-l:wx(a.duration);return{traceID:s,spanID:c.spanId,operationName:a.name,processID:r,warnings:null,startTime:l,duration:d,references:a.parentSpanContext?.spanId===void 0?[]:[{refType:"CHILD_OF",traceID:s,spanID:a.parentSpanContext?.spanId}],tags:QK(a.attributes),logs:a.events.map(h=>({timestamp:wx(h.time),fields:[...QK(h.attributes??{}),{key:"event",type:"string",value:h.name}]}))}})}))})}async shutdown(){}}const EGe="element-call";let K1;class fR{static globalInit(){(!K1||K1.isOtlpEnabled!==!1)&&(M.info("(Re)starting OpenTelemetry debug reporting"),K1?.dispose(),K1=new fR(void 0,Nle()))}static get instance(){return K1}constructor(e,n){const r=[];e?(M.info("Enabling OTLP collector with URL "+e),this.otlpExporter=new VBe({url:e}),r.push(new W$e(this.otlpExporter))):M.info("OTLP collector disabled"),n&&(this.rageshakeProcessor=new SGe,r.push(this.rageshakeProcessor)),r.push(new _Ge),this._provider=new zBe({resource:ace({[Jae]:EGe}),spanProcessors:r}),yx.trace.setGlobalTracerProvider(this._provider),this._tracer=yx.trace.getTracer("my-element-call-otl-tracer")}dispose(){yx.trace.disable(),this._provider?.shutdown().catch(e=>{M.error("Failed to shutdown OpenTelemetry",e)})}get isOtlpEnabled(){return!!this.otlpExporter}get tracer(){return this._tracer}get provider(){return this._provider}}const ZK=async t=>{const{gzip:e}=await lb(async()=>{const{gzip:r}=await import("./pako.esm-Bt8vjcgE.js");return{gzip:r}},[],import.meta.url),n=new TextEncoder().encode(t);return new Blob([e(n)])};async function wGe(t,e){e.append("crypto_version",t.getVersion());const n=await t.getOwnDeviceKeys(),r=[`curve25519:${n.curve25519}`,`ed25519:${n.ed25519}`];e.append("device_keys",r.join(", "));const i=await t.getCrossSigningStatus();e.append("cross_signing_ready",String(await t.isCrossSigningReady())),e.append("cross_signing_key",await t.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 CGe(t,e,n){const r=t.secretStorage;n.append("secret_storage_ready",String(await e.isSecretStorageReady())),n.append("secret_storage_key_in_account",String(await r.hasKey())),n.append("session_backup_key_in_secret_storage",String(!!await t.isKeyBackupKeyStored()));const i=await e.getSessionBackupPrivateKey();n.append("session_backup_key_cached",String(!!i)),n.append("session_backup_key_well_formed",String(i instanceof Uint8Array))}function Nle(){return Br().rageshakeSubmitUrl??void 0}function hR(t=Nle){const{client:e}=jp(),[{sending:n,sent:r,error:i},s]=_.useState({sending:!1,sent:!1,error:void 0});return{submitRageshake:_.useCallback(async a=>{const c=t();if(!c)throw new Error("No rageshake URL is configured");if(!n)try{s({sending:!0,sent:!1,error:void 0});let l="UNKNOWN";window.navigator&&window.navigator.userAgent&&(l=window.navigator.userAgent);let d="UNKNOWN";try{d=String(window.matchMedia("(pointer: coarse)").matches)}catch(y){M.warn("Could not get coarse pointer for rageshake submit.",y)}let h=a.rageshakeRequestId?`Rageshake ${a.rageshakeRequestId}`:"";a.description&&(h+=`: ${a.description}`);const m=new FormData;if(m.append("text",h??"User did not supply any additional text."),m.append("app","matrix-video-chat"),m.append("version","embedded-v0.16.3"),m.append("user_agent",l),m.append("installed_pwa","false"),m.append("touch_input",d),m.append("call_backend","livekit"),m.append("hostname",window.location.hostname),e){const y=e.getUserId(),v=e.getUser(y);m.append("display_name",v?.displayName??""),m.append("user_id",e.credentials.userId??""),m.append("device_id",e.deviceId??""),a.roomId&&m.append("room_id",a.roomId);const w=e.getCrypto();w&&(await wGe(w,m),await CGe(e,w,m))}if(a.label&&m.append("label",a.label),navigator.storage&&navigator.storage.persisted)try{m.append("storageManager_persisted",String(await navigator.storage.persisted()))}catch(y){M.warn("coulr not get navigator peristed storage",y)}else if(document.hasStorageAccess)try{m.append("storageManager_persisted",String(await document.hasStorageAccess()))}catch(y){M.warn("could not get storage access",y)}if(navigator.storage&&navigator.storage.estimate)try{const y=await navigator.storage.estimate();m.append("storageManager_quota",String(y.quota)),m.append("storageManager_usage",String(y.usage)),y.usageDetails&&Object.keys(y.usageDetails).forEach(v=>{m.append(`storageManager_usage_${v}`,String(y.usageDetails[v]))})}catch(y){M.warn("could not obatain storage estimate",y)}if(a.sendLogs){const y=await Mje();for(const v of y)m.append("compressed-log",await ZK(v.lines),v.id);m.append("file",await ZK(fR.instance.rageshakeProcessor.dump()),"traces.json.gz")}a.rageshakeRequestId&&m.append("group_call_rageshake_request_id",a.rageshakeRequestId);const g=await fetch(c,{method:"POST",body:m});if(g.status!==200)throw new Error(`Failed to submit feedback: receive HTTP ${g.status} ${g.statusText}`);s({sending:!1,sent:!0,error:void 0})}catch(l){s({sending:!1,sent:!1,error:l}),M.error(l)}},[e,n,t]),sending:n,sent:r,error:i,available:!!t()}}function TGe(){const{client:t}=jp();return _.useCallback((n,r)=>{t.sendEvent(n,"org.matrix.rageshake_request",{request_id:r}).catch(i=>{M.error("Failed to send org.matrix.rageshake_request event",i)})},[t])}function RGe(t){const[e,n]=_.useState(!1),r=_.useCallback(()=>n(!1),[n]),{client:i}=jp(),[s,o]=_.useState();return _.useEffect(()=>{if(!i)return;const a=c=>{c.getType()==="org.matrix.rageshake_request"&&t===c.getRoomId()&&i.getUserId()!==c.getSender()&&(o(c.getContent().request_id),n(!0))};return i.on(Le.Event,a),()=>{i.removeListener(Le.Event,a)}},[n,t,i]),{rageshakeRequestId:s??"",roomId:t,open:e,onDismiss:r}}const IGe=({description:t})=>{const{submitRageshake:e,sending:n,sent:r,error:i}=hR(),{t:s}=We(),o=_.useCallback(()=>{e({description:t,sendLogs:!0}).catch(c=>{M.error("Failed to send rageshake",c)})},[e,t]);if(!sn.get().rageshake?.submit_url)return null;let a=null;if(n)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(Bt,{onClick:o,className:TG.wideButton,disabled:n,children:c})}return E.jsx("div",{className:TG.rageshakeControl,children:a})},kGe="_error_17zfc_1",xGe="_icon_17zfc_9",bE={error:kGe,icon:xGe},AGe="_endCall_bwclo_8",PGe={endCall:AGe},Ule=({muted:t,...e})=>{const{t:n}=We(),r=t?Hoe:t8,i=n(t?"unmute_microphone_button_label":"mute_microphone_button_label");return E.jsx(qi,{label:i,children:E.jsx(Bt,{iconOnly:!0,Icon:r,kind:t?"primary":"secondary",...e})})},jle=({muted:t,...e})=>{const{t:n}=We(),r=t?N8e:lae,i=n(t?"start_video_button_label":"stop_video_button_label");return E.jsx(qi,{label:i,children:E.jsx(Bt,{iconOnly:!0,Icon:r,kind:t?"primary":"secondary",...e})})},LGe=({enabled:t,...e})=>{const{t:n}=We(),r=n(t?"stop_screenshare_button_label":"screenshare_button_label");return E.jsx(qi,{label:r,children:E.jsx(Bt,{iconOnly:!0,Icon:A8e,kind:t?"primary":"secondary",...e})})},Fle=({className:t,...e})=>{const{t:n}=We();return E.jsx(qi,{label:n("hangup_button_label"),children:E.jsx(Bt,{className:Oe(t,PGe.endCall),iconOnly:!0,Icon:Ooe,destructive:!0,...e})})},$le=t=>{const{t:e}=We();return E.jsx(qi,{label:e("common.settings"),children:E.jsx(Bt,{iconOnly:!0,Icon:x8e,kind:"secondary",...t})})},OGe="_external_jhjdf_8",MGe={external:OGe};function Ble(t,e){const n=Uee(t),r=Wee(t,{state:e});return[n,r]}const il=({ref:t,to:e,state:n,...r})=>{const[i,s]=Ble(e,n);return E.jsx(l7e,{ref:t,...r,href:i,onClick:s})},Jh=({ref:t,className:e,children:n,...r})=>E.jsx("a",{ref:t,className:Oe(e,MGe.external),target:"_blank",rel:"noreferrer noopener",...r,children:n}),q8=({ref:t,to:e,state:n,...r})=>{const[i,s]=Ble(e,n);return E.jsx(Bt,{as:"a",ref:t,...r,href:i,onClick:s})};function Fw(t,e,n,r){_.useEffect(()=>{if(t)return t.addEventListener(e,n,r),()=>t.removeEventListener(e,n,r)},[t,e,n,r])}function Hle(t,e,n){_.useEffect(()=>(t.on(e,n),()=>{t.off(e,n)}),[t,e,n])}function gp(t,e,n){const r=_.useCallback(i=>(t.on(e,i),()=>{t.off(e,i)}),[t,e]);return _.useSyncExternalStore(r,n)}function G8(t){return gp(t,ei.MembershipsChanged,_.useCallback(()=>t.memberships,[t]))}const Vle=_.createContext(void 0),K8=()=>{const t=_.use(Vle);if(!t)throw new Error("useReactions must be used within a ReactionsProvider");return t},DGe=({children:t,rtcSession:e,vm:n})=>{const r=G8(e),i=r0(),s=i?.state==="valid"&&i.supportedFeatures.reactions,o=e.room,a=o.client.getUserId(),c=o.client.getDeviceId(),l=`${a}:${c}`,d=_.useMemo(()=>r.find(S=>S.sender===a&&S.deviceId===c)?.eventId,[r,a,c]),h=Qe(n.reactions$),m=_.useMemo(()=>l!==void 0?h[l]:void 0,[l,h]),g=Qe(n.handsRaised$),y=_.useMemo(()=>l!==void 0?g[l]:void 0,[l,g]),v=_.useCallback(async()=>{if(!l)return;const S=y?.reactionEventId;if(S)try{await o.client.redactEvent(e.room.roomId,S),M.debug("Redacted raise hand event")}catch(R){throw M.error("Failed to redact reaction event",S,R),R}else try{if(!d)throw new Error("Cannot find own membership event");const R=await o.client.sendEvent(e.room.roomId,Z.Reaction,{"m.relates_to":{rel_type:vn.Annotation,event_id:d,key:"🖐️"}});M.debug("Sent raise hand event",R.event_id)}catch(R){M.error("Failed to send raised hand",R)}},[d,l,y,e,o]),w=_.useCallback(async S=>{if(!(!l||m)){if(!d)throw new Error("Cannot find own membership event");await o.client.sendEvent(e.room.roomId,O8,{"m.relates_to":{rel_type:vn.Reference,event_id:d},emoji:S.emoji,name:S.name})}},[d,m,o,l,e]);return E.jsx(Vle,{value:{supportsReactions:s,toggleRaisedHand:v,sendReaction:w},children:t})},NGe="_raisedButton_unw54_1",UGe="_reactionPopupMenu_unw54_5",jGe="_reactionPopupMenuRoot_unw54_21",FGe="_reactionPopupMenuModal_unw54_21",$Ge="_reactionsMenuSection_unw54_47",BGe="_reactionsMenu_unw54_47",HGe="_reactionButton_unw54_81",VGe="_verticalSeperator_unw54_91",qGe="_alert_unw54_99",Ha={raisedButton:NGe,reactionPopupMenu:UGe,reactionPopupMenuRoot:jGe,reactionPopupMenuModal:FGe,reactionsMenuSection:$Ge,reactionsMenu:BGe,reactionButton:HGe,verticalSeperator:VGe,alert:qGe};function ez(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function GGe(...t){return e=>{let n=!1;const r=t.map(i=>{const s=ez(i,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():ez(t[i],null)}}}}function KGe(t){const e=zGe(t),n=_.forwardRef((r,i)=>{const{children:s,...o}=r,a=_.Children.toArray(s),c=a.find(YGe);if(c){const l=c.props.children,d=a.map(h=>h===c?_.Children.count(l)>1?_.Children.only(null):_.isValidElement(l)?l.props.children:null:h);return E.jsx(e,{...o,ref:i,children:_.isValidElement(l)?_.cloneElement(l,void 0,d):null})}return E.jsx(e,{...o,ref:i,children:s})});return n.displayName=`${t}.Slot`,n}function zGe(t){const e=_.forwardRef((n,r)=>{const{children:i,...s}=n;if(_.isValidElement(i)){const o=JGe(i),a=XGe(s,i.props);return i.type!==_.Fragment&&(a.ref=r?GGe(r,o):o),_.cloneElement(i,a)}return _.Children.count(i)>1?_.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var WGe=Symbol("radix.slottable");function YGe(t){return _.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===WGe}function XGe(t,e){const n={...e};for(const r in e){const i=t[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...a)=>{const c=s(...a);return i(...a),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...t,...n}}function JGe(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var QGe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ZGe=QGe.reduce((t,e)=>{const n=KGe(`Primitive.${e}`),r=_.forwardRef((i,s)=>{const{asChild:o,...a}=i,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{}),eKe=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),tKe="VisuallyHidden",HL=_.forwardRef((t,e)=>E.jsx(ZGe.span,{...t,ref:e,style:{...eKe,...t.style}}));HL.displayName=tKe;const nKe="_modal_lmgdq_8",rKe="_dialog_lmgdq_14",iKe="_content_lmgdq_21",sKe="_drawer_lmgdq_32",oKe="_close_lmgdq_59",aKe="_header_lmgdq_84",cKe="_body_lmgdq_114",lKe="_tabbed_lmgdq_129",uKe="_handle_lmgdq_133",Ms={modal:nKe,dialog:rKe,content:iKe,drawer:sKe,close:oKe,header:aKe,body:cKe,tabbed:lKe,handle:uKe},dKe="_bg_180k3_8",fKe="_animate_180k3_23",hKe="_overlay_180k3_42",Bs={bg:dKe,animate:fKe,overlay:hKe},Up=({title:t,hideHeader:e,children:n,className:r,classNameDrawer:i,classNameModal:s,open:o,onDismiss:a,tabbed:c,...l})=>{const{t:d}=We(),h=YT("(hover: none) or (pointer: coarse)"),m=_.useCallback(g=>{g||a?.()},[a]);if(h)return E.jsx(Hs.Root,{open:o,onOpenChange:m,dismissible:a!==void 0,children:E.jsxs(Hs.Portal,{children:[E.jsx(Hs.Overlay,{className:Oe(Bs.bg)}),E.jsx(Hs.Content,{className:Oe(r,i,Bs.overlay,Ms.modal,Ms.drawer,{[Ms.tabbed]:c}),role:"dialog","aria-describedby":void 0,...l,children:E.jsxs("div",{className:Ms.content,children:[E.jsxs("div",{className:Ms.header,children:[E.jsx("div",{className:Ms.handle}),E.jsx(HL,{asChild:!0,children:E.jsx(Hs.Title,{children:t})})]}),E.jsx("div",{className:Ms.body,children:n})]})})]})});{const g=E.jsx(jM,{asChild:!0,children:E.jsx(gl,{as:"h2",weight:"semibold",size:"md",children:t})}),y=E.jsxs("div",{className:Ms.header,children:[g,a!==void 0&&E.jsx(Pse,{className:Ms.close,"data-testid":"modal_close","aria-label":d("action.close"),children:E.jsx(LT,{width:20,height:20})})]});return E.jsx(MM,{open:o,onOpenChange:m,children:E.jsxs(DM,{children:[E.jsx(NM,{className:Oe(Bs.bg,Bs.animate)}),E.jsx(UM,{asChild:!0,"aria-describedby":void 0,role:"dialog",...l,children:E.jsx(Vse,{className:Oe(r,s,Bs.overlay,Bs.animate,Ms.modal,Ms.dialog,{[Ms.tabbed]:c}),children:E.jsxs("div",{className:Ms.content,children:[e?null:y,e?E.jsx(HL,{asChild:!0,children:g}):null,E.jsx("div",{className:Ms.body,children:n})]})})})]})})}},pKe=({raised:t,open:e,...n})=>{const{t:r}=We();return E.jsx(qi,{label:r("common.reactions"),children:E.jsx(Bt,{className:Oe(t&&Ha.raisedButton),"aria-expanded":e,"aria-haspopup":!0,kind:t||e?"primary":"secondary",iconOnly:!0,Icon:t?Xoe:k8e,...n})})};function mKe({sendReaction:t,toggleRaisedHand:e,isHandRaised:n,canReact:r,errorText:i}){const{t:s}=We(),[o,a]=_.useState(!1),c=_.useMemo(()=>o?qb:qb.slice(0,5),[o]),l=s(n?"action.lower_hand":"action.raise_hand");return E.jsxs(E.Fragment,{children:[i&&E.jsx(Zxe,{className:Ha.alert,type:"critical",title:s("error.generic"),children:i}),E.jsxs("div",{className:Ha.reactionPopupMenu,children:[E.jsx("section",{className:Ha.handRaiseSection,children:E.jsx(qi,{label:l,caption:"H",children:E.jsx(Bt,{kind:n?"primary":"secondary","aria-keyshortcuts":"H","aria-pressed":n,"aria-label":l,onClick:()=>e(),iconOnly:!0,Icon:Xoe})})}),E.jsx("div",{className:Ha.verticalSeperator}),E.jsx("section",{className:Ha.reactionsMenuSection,children:E.jsx("menu",{className:Oe(o&&Ha.reactionsMenuExpanded,Ha.reactionsMenu),children:c.map((d,h)=>E.jsx("li",{children:E.jsx(qi,{label:d.name,caption:h<jL?(h+1).toString():void 0,children:E.jsx(Bt,{kind:"secondary",className:Ha.reactionButton,disabled:!r,onClick:()=>t(d),"aria-keyshortcuts":h<jL?(h+1).toString():void 0,children:d.emoji})})},d.name))})}),E.jsx("section",{style:{marginLeft:"var(--cpd-separator-spacing)"},children:E.jsx(qi,{label:s(o?"action.show_less":"action.show_more"),children:E.jsx(Bt,{iconOnly:!0,"aria-label":s(o?"action.show_less":"action.show_more"),Icon:o?y8e:HMe,kind:"tertiary",onClick:()=>a(!o)})})})]})]})}function gKe({identifier:t,vm:e,...n}){const{t:r}=We(),{toggleRaisedHand:i,sendReaction:s}=K8(),[o,a]=_.useState(!1),[c,l]=_.useState(!1),[d,h]=_.useState(),m=!!Qe(e.handsRaised$)[t],g=!Qe(e.reactions$)[t];_.useEffect(()=>{h(void 0)},[c]);const y=_.useCallback(async w=>{try{a(!0),await s(w),h(void 0),l(!1)}catch(S){h(S instanceof Error?S.message:"Unknown error"),M.error("Failed to send reaction",S)}finally{a(!1)}},[s]),v=_.useCallback(()=>{(async()=>{try{a(!0),await i(),l(!1)}catch(S){h(S instanceof Error?S.message:"Unknown error"),M.error("Failed to raise/lower hand",S)}finally{a(!1)}})()},[i]);return E.jsxs(E.Fragment,{children:[E.jsx(pKe,{disabled:o,onClick:()=>l(w=>!w),raised:!!m,open:c,...n}),E.jsx(Up,{open:c,title:r("action.pick_reaction"),hideHeader:!0,classNameModal:Ha.reactionPopupMenuModal,className:Ha.reactionPopupMenuRoot,onDismiss:()=>l(!1),children:E.jsx(mKe,{errorText:d,isHandRaised:!!m,canReact:!o&&!!g,sendReaction:w=>void y(w),toggleRaisedHand:v})})]})}const Kb=({Icon:t,title:e,rageshake:n,fatal:r,children:i,widget:s})=>{const{t:o}=We(),{confineToRoom:a}=no(),c=_.useCallback(()=>{window.location.href="/"},[]),l=({widget:h})=>{const m=()=>{h.api.transport.send(Ri.Close,{}).catch(g=>{M.error("Failed to send close action",g)}).finally(()=>{h.api.transport.stop()})};return E.jsx(Bt,{kind:"primary",onClick:m,children:o("action.close")})},d=()=>r||location.pathname==="/"?E.jsx(Bt,{kind:"tertiary",className:bE.homeLink,onClick:c,children:o("return_home_button")}):E.jsx(q8,{kind:"tertiary",className:bE.homeLink,to:"/",children:o("return_home_button")});return E.jsxs("div",{className:bE.error,children:[E.jsx(moe,{className:bE.icon,children:E.jsx(t,{"aria-hidden":!0})}),E.jsx(gl,{as:"h1",weight:"semibold",size:"md",children:e}),i,n&&E.jsx(IGe,{description:`***Error View***: ${e}`}),s?E.jsx(l,{widget:s}):!a&&E.jsx(d,{})]})};class qle extends Error{constructor(e,n){super(e),this.richMessage=n}}const vKe=()=>{const{t}=We();return E.jsx(Kb,{widget:ut,Icon:Woe,title:t("error.open_elsewhere"),children:E.jsx("p",{children:t("error.open_elsewhere_description",{brand:"Element Call"})})})};class yKe extends qle{constructor(){super("App opened in another tab",E.jsx(vKe,{}))}}const qg=({className:t,children:e})=>{const{header:n}=no();return E.jsxs("div",{className:Oe(lx.page,t),children:[n==="standard"&&E.jsxs(qu,{children:[E.jsx(jf,{children:E.jsx(fp,{})}),E.jsx(Ff,{})]}),E.jsx("div",{className:lx.container,children:E.jsx("div",{className:lx.content,children:e})})]})},zb=({error:t,widget:e})=>{const{t:n}=We();return _.useEffect(()=>{M.error(t),IT(t)},[t]),E.jsx(qg,{children:t instanceof qle?t.richMessage:E.jsx(Kb,{widget:e,Icon:PT,title:n("error.generic"),rageshake:!0,fatal:!0,children:E.jsx("p",{children:n("error.generic_description")})})})},pR=()=>{const{t}=We();return E.jsx(qg,{children:E.jsx("h1",{children:t("common.loading")})})},z8=_.createContext(void 0);z8.Provider;const r0=()=>_.use(z8);function jp(){let t,e;const n=r0();return n?.state==="valid"&&(t=n.authenticated?.client,e=n.setClient),{client:t,setClient:e}}function W8(){const t=r0();let e,n,r=!1,i=!0,s,o=!1,a;return t?.state==="valid"?(e=t.authenticated?.client,n=t.setClient,r=t.authenticated?.isPasswordlessUser??!1,i=!1,o=e!==void 0,a=t.authenticated?.logout):t?.state==="error"&&(s=t.error,i=!1),{client:e,setClient:n,passwordlessUser:r,loading:i,authenticated:o,logout:a,error:s}}const tz="BroadcastChannel"in window?new BroadcastChannel("load"):null,bKe=({children:t})=>{const e=hl(),[n,r]=_.useState(void 0),i=_.useRef(!1);_.useEffect(()=>{i.current||(i.current=!0,_Ke().then(R=>{r(R),Ut.instance.isEnabled()&&Ut.instance.startListeningToSettingsChanges()}).catch(R=>M.error(R)).finally(()=>i.current=!1))},[]);const s=_.useCallback(async R=>{const x=Kle();!n?.client||!x||(await n.client.setPassword({type:"m.login.password",identifier:{type:"m.id.user",user:x.user_id},user:x.user_id,password:x.tempPassword},R),nz({...x,passwordlessUser:!1}),r({...n,passwordlessUser:!1}))},[n]),o=_.useCallback((R,x)=>{const T=n?.client;T&&T!==R&&T.stopClient(),nz(x),r({widgetApi:null,client:R,passwordlessUser:x.passwordlessUser}),Ut.instance.isEnabled()&&Ut.instance.startListeningToSettingsChanges()},[n?.client]),a=_.useCallback(async()=>{const R=n?.client;R&&(await R.logout(!0),await R.clearStores(),Gle(),r(null),await e("/"),Ut.instance.logout(),Ut.instance.setRegistrationType(dR.Guest))},[e,n?.client]);_.useEffect(()=>{ut||tz?.postMessage({})},[]);const[c,l]=_.useState(void 0);Fw(tz,"message",_.useCallback(()=>{n?.client.stopClient(),l(new yKe)},[n?.client,l]));const[d,h]=_.useState(!1),[m,g]=_.useState(!1),[y,v]=_.useState(!1),w=_.useMemo(()=>c?{state:"error",error:c}:n===void 0?void 0:{state:"valid",authenticated:n===null?void 0:{client:n.client,isPasswordlessUser:n.passwordlessUser,changePassword:s,logout:a},setClient:o,disconnected:d,supportedFeatures:{reactions:m,thumbnails:y}},[c,s,n,a,o,d,m,y]),S=_.useCallback((R,x,T)=>{h(SKe(R,T))},[]);return _.useEffect(()=>{if(n){if(window.matrixclient=n.client,window.passwordlessUser=n.passwordlessUser,Ut.hasInstance()&&Ut.instance.onLoginStatusChanged(),n.client&&n.client.on(Le.Sync,S),n.widgetApi){v(!1);const R=n.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.reaction"),x=n.widgetApi.hasCapability("org.matrix.msc2762.send.event:m.room.redaction"),T=n.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.reaction"),I=n.widgetApi.hasCapability("org.matrix.msc2762.receive.event:m.room.redaction");!R||!T||!x||!I?(M.warn("Widget does not support reactions"),g(!1)):g(!0)}else g(!0),v(!0);return()=>{n.client&&n.client.removeListener(Le.Sync,S)}}},[n,S]),c?E.jsx(zb,{widget:ut,error:c}):E.jsx(z8,{value:w,children:t})};async function _Ke(){if(ut){M.log("Using a matryoshka client");const t=await ut.client;return{widgetApi:ut.api,client:t,passwordlessUser:!1}}else{const{initSPA:t}=await lb(async()=>{const{initSPA:e}=await import("./spa-3dms9gnk.js");return{initSPA:e}},[],import.meta.url);return t(Kle,Gle)}}const Gle=()=>localStorage.removeItem("matrix-auth-store"),nz=t=>localStorage.setItem("matrix-auth-store",JSON.stringify(t)),Kle=()=>{const t=localStorage.getItem("matrix-auth-store");if(t)return JSON.parse(t)},SKe=(t,e)=>t==="ERROR"&&e?.error?.name==="ConnectionError";function V_(t){const[{success:e,loading:n,displayName:r,avatarUrl:i,error:s},o]=_.useState(()=>{let c;return t&&(c=t.getUser(t.getUserId())??void 0),{success:!1,loading:!1,displayName:c?.rawDisplayName,avatarUrl:c?.avatarUrl,error:void 0}});_.useEffect(()=>{const c=(d,{displayName:h,avatarUrl:m})=>{o({success:!1,loading:!1,displayName:h,avatarUrl:m,error:void 0})};let l;if(t){const d=t.getUserId();l=t.getUser(d),l?.on(Ui.DisplayName,c),l?.on(Ui.AvatarUrl,c)}return()=>{l&&(l.removeListener(Ui.DisplayName,c),l.removeListener(Ui.AvatarUrl,c))}},[t]);const a=_.useCallback(async({displayName:c,avatar:l,removeAvatar:d})=>{if(t){o(h=>({...h,loading:!0,error:void 0,success:!1}));try{await t.setDisplayName(c);let h;d?await t.setAvatarUrl(""):l&&({content_uri:h}=await t.uploadContent(l),await t.setAvatarUrl(h)),o(m=>({...m,displayName:c,avatarUrl:d?void 0:h??m.avatarUrl,loading:!1,success:!0}))}catch(h){o(m=>({...m,loading:!1,error:h instanceof Error?h:Error(h),success:!1}))}}else M.error("Client not initialized before calling saveProfile")},[t]);return{loading:n,error:s,displayName:r,avatarUrl:i,saveProfile:a,success:e}}const EKe="_settingsModal_1dkeq_8",wKe="_volumeSlider_1dkeq_20",rz={settingsModal:EKe,volumeSlider:wKe},CKe="_tabContainer_1nnp9_8",TKe="_tabList_1nnp9_14",iz={tabContainer:CKe,tabList:TKe};function RKe({label:t,tab:e,onTabChange:n,tabs:r}){const i=_.useId();return E.jsxs("div",{className:iz.tabContainer,children:[E.jsx(UMe,{role:"tablist","aria-label":t,className:iz.tabList,children:r.map(({key:s,name:o})=>E.jsx(BMe,{"aria-controls":`${i}[${s}]`,onClick:()=>n(s),active:s===e,children:o},s))}),r.map(({key:s,content:o})=>E.jsx("div",{id:`${i}[${s}]`,style:{display:s===e?void 0:"none"},children:o},s))]})}const IKe="_fieldRow_iwncy_8",kKe="_field_iwncy_8",xKe="_rightAlign_iwncy_21",AKe="_inputField_iwncy_33",PKe="_disabled_iwncy_52",LKe="_prefix_iwncy_110",OKe="_checkboxField_iwncy_131",MKe="_checkbox_iwncy_131",DKe="_description_iwncy_168",NKe="_errorMessage_iwncy_197",UKe="_noLabel_iwncy_210",ea={fieldRow:IKe,field:kKe,rightAlign:xKe,inputField:AKe,disabled:PKe,prefix:LKe,checkboxField:OKe,checkbox:MKe,description:DKe,errorMessage:NKe,noLabel:UKe},jKe=(t,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,...t},_.createElement("path",{d:"m20 6-11 11-5-5"})),FKe=_.forwardRef(jKe);class zle extends Error{constructor(e,n){super(n(e,{lng:"en"})),this.translatedMessage=n(e)}}class $Ke extends zle{}const sz=(t,e)=>new $Ke(t,e);function yt({children:t,rightAlign:e,className:n}){return E.jsx("div",{className:Oe(ea.fieldRow,{[ea.rightAlign]:e},n),children:t})}function BKe({children:t,className:e}){return E.jsx("div",{className:Oe(ea.field,e),children:t})}const Tn=({ref:t,id:e,label:n,className:r,type:i,checked:s,prefix:o,suffix:a,description:c,disabled:l,min:d,...h})=>{const m=_.useId();return E.jsxs(BKe,{className:Oe(i==="checkbox"?ea.checkboxField:ea.inputField,{[ea.prefix]:!!o,[ea.disabled]:l},r),children:[o&&E.jsx("span",{children:o}),i==="textarea"?E.jsx("textarea",{id:e,ref:t,disabled:l,"aria-describedby":m,...h}):E.jsx("input",{id:e,ref:t,type:i,checked:s,disabled:l,"aria-describedby":m,min:d,...h}),E.jsxs("label",{htmlFor:e,children:[i==="checkbox"&&E.jsx("div",{className:ea.checkbox,children:E.jsx(FKe,{})}),n]}),a&&E.jsx("span",{children:a}),c&&E.jsx("p",{id:m,className:n?ea.description:Oe(ea.description,ea.noLabel),children:c})]})};Tn.displayName="InputField";const Bf=({error:t})=>E.jsx("p",{className:ea.errorMessage,children:t instanceof zle?t.translatedMessage:t.message}),HKe="_avatarInputField_1ep5q_8",VKe="_avatar_1ep5q_8",qKe="_fileInput_1ep5q_17",GKe="_edit_1ep5q_21",_E={avatarInputField:HKe,avatar:VKe,fileInput:qKe,edit:GKe},Wle=({id:t,label:e,className:n,avatarUrl:r,userId:i,displayName:s,onRemoveAvatar:o,...a})=>{const{t:c}=We(),[l,d]=_.useState(!1),[h,m]=_.useState(void 0),[g,y]=_.useState(!1),v=_.useRef(null);_.useEffect(()=>{const R=v.current,x=T=>{const I=T;I.target.files&&I.target.files.length>0?(m(URL.createObjectURL(I.target.files[0])),d(!1)):m(void 0)};return R.addEventListener("change",x),()=>{R?.removeEventListener("change",x)}});const w=_.useCallback(()=>{v.current.click()},[v]),S=_.useCallback(()=>{d(!0),o()},[o]);return E.jsxs("div",{className:Oe(_E.avatarInputField,n),children:[E.jsx(Op,{id:i,className:_E.avatar,name:s,size:Lp.XL,src:l?void 0:h||r}),E.jsx("input",{id:t,accept:"image/*",ref:v,type:"file",className:_E.fileInput,role:"button","aria-label":e,...a}),E.jsx("div",{className:_E.edit,children:(r||h)&&!l?E.jsxs(qM,{title:c("action.edit"),showTitle:!1,open:g,onOpenChange:y,trigger:E.jsx(Bt,{iconOnly:!0,Icon:Qq,kind:"tertiary",size:"sm","aria-label":c("action.edit")}),children:[E.jsx(yv,{Icon:P8e,label:c("action.upload_file"),onSelect:w}),E.jsx(yv,{Icon:b8e,label:c("action.remove"),kind:"critical",onSelect:S})]}):E.jsx(Bt,{type:"button",iconOnly:!0,Icon:Qq,kind:"tertiary",size:"sm","aria-label":c("action.edit"),onClick:w})})]})};Wle.displayName="AvatarInputField";const KKe="_content_gj715_8",zKe="_avatarFieldRow_gj715_15",oz={content:KKe,avatarFieldRow:zKe},WKe=({client:t})=>{const{t:e}=We(),{error:n,displayName:r,avatarUrl:i,saveProfile:s}=V_(t),o=_.useMemo(()=>t.getUserId(),[t]),a=_.useRef(null),c=_.useRef(!1),l=_.useCallback(()=>{c.current=!0},[]),d=_.useRef(!1),h=_.useCallback(()=>{d.current=!0,c.current=!0},[]);return _.useEffect(()=>{const m=a.current;return()=>{if(c.current){const g=new FormData(m),y=g.get("displayName"),v=g.get("avatar"),w=typeof v=="string"?v.length:v?.size??0,S=typeof y=="string"?y:y?.name??null;if(!S)return;s({displayName:S,avatar:v&&w>0?v:void 0,removeAvatar:d.current&&(!v||w===0)}).catch(R=>{M.error("Failed to save profile",R)})}}},[s]),E.jsxs("form",{onChange:l,ref:a,className:oz.content,children:[E.jsx(yt,{className:oz.avatarFieldRow,children:o&&r&&E.jsx(Wle,{id:"avatar",name:"avatar",label:e("common.avatar"),avatarUrl:i,userId:o,displayName:r,onRemoveAvatar:h})}),E.jsx(yt,{children:E.jsx(Tn,{id:"userId",name:"userId",label:e("common.username"),type:"text",disabled:!0,value:t.getUserId()})}),E.jsx(yt,{children:E.jsx(Tn,{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"})}),n&&E.jsx(yt,{children:E.jsx(Bf,{error:n})})]})},YKe="_feedback_19yh9_8",Yle={feedback:YKe},Xle=()=>E.jsxs(Ys,{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(Jh,{href:"https://element.io/privacy",children:"Privacy Policy"})," ","and our"," ",E.jsx(Jh,{href:"https://element.io/cookie-policy",children:"Cookie Policy"}),"."]}),XKe=({roomId:t})=>{const{t:e}=We(),{submitRageshake:n,sending:r,sent:i,error:s,available:o}=hR(),a=TGe(),c=_.useCallback(h=>{h.preventDefault();const m=new FormData(h.target),g=m.get("description"),y=typeof g=="string"?g:"",v=!!m.get("sendLogs"),w=To(16);n({description:y,sendLogs:v,rageshakeRequestId:w,roomId:t}).catch(S=>{M.error("Failed to send feedback rageshake",S)}),t&&v&&a(t,w)},[n,t,a]);uR();const l=null,d=o?E.jsxs(E.Fragment,{children:[E.jsx("h4",{children:e("settings.feedback_tab_h4")}),E.jsx(an,{children:e("settings.feedback_tab_body")}),E.jsxs("form",{onSubmit:c,children:[E.jsx(yt,{children:E.jsx(Tn,{className:Yle.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(yt,{children:[E.jsx(Tn,{id:"sendLogs",name:"sendLogs",label:e("settings.feedback_tab_send_logs_label"),type:"checkbox",defaultChecked:!0}),E.jsx(Bt,{type:"submit",disabled:r,children:e(r?"submitting":"action.submit")})]}),E.jsxs(yt,{children:[s&&E.jsx(Bf,{error:s}),i&&E.jsx(an,{children:e("settings.feedback_tab_thank_you")})]})]})]}):null;return E.jsxs("div",{children:[l,d]})};var $w={exports:{}},JKe=$w.exports,az;function QKe(){return az||(az=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(JKe,function(){var e=function(){},n="undefined",r=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(v,w){var S=v[w];if(typeof S.bind=="function")return S.bind(v);try{return Function.prototype.bind.call(S,v)}catch{return function(){return Function.prototype.apply.apply(S,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&r?c:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<i.length;w++){var S=i[w];this[S]=w<v?e:this.methodFactory(S,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function h(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function m(v,w,S){return l(v)||h.apply(this,arguments)}function g(v,w){var S=this,R,x,T,I="loglevel";typeof v=="string"?I+=":"+v:typeof v=="symbol"&&(I=void 0);function k(U){var $=(i[U]||"silent").toUpperCase();if(!(typeof window===n||!I)){try{window.localStorage[I]=$;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+$+";"}catch{}}}function A(){var U;if(!(typeof window===n||!I)){try{U=window.localStorage[I]}catch{}if(typeof U===n)try{var $=window.document.cookie,K=encodeURIComponent(I),Y=$.indexOf(K+"=");Y!==-1&&(U=/^([^;]+)/.exec($.slice(Y+K.length+1))[1])}catch{}return S.levels[U]===void 0&&(U=void 0),U}}function O(){if(!(typeof window===n||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function D(U){var $=U;if(typeof $=="string"&&S.levels[$.toUpperCase()]!==void 0&&($=S.levels[$.toUpperCase()]),typeof $=="number"&&$>=0&&$<=S.levels.SILENT)return $;throw new TypeError("log.setLevel() called with invalid level: "+U)}S.name=v,S.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},S.methodFactory=w||m,S.getLevel=function(){return T??x??R},S.setLevel=function(U,$){return T=D(U),$!==!1&&k(T),d.call(S)},S.setDefaultLevel=function(U){x=D(U),A()||S.setLevel(U,!1)},S.resetLevel=function(){T=null,O(),d.call(S)},S.enableAll=function(U){S.setLevel(S.levels.TRACE,U)},S.disableAll=function(U){S.setLevel(S.levels.SILENT,U)},S.rebuild=function(){if(o!==S&&(R=D(o.getLevel())),d.call(S),o===S)for(var U in s)s[U].rebuild()},R=D(o?o.getLevel():"WARN");var N=A();N!=null&&(T=D(N)),d.call(S)}o=new g,o.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var S=s[w];return S||(S=s[w]=new g(w,o.methodFactory)),S};var y=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return s},o.default=o,o})}($w)),$w.exports}var ZKe=QKe();const eze=cl(ZKe);var tze=(t,e,n)=>new Promise((r,i)=>{var s=c=>{try{a(n.next(c))}catch(l){i(l)}},o=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);a((n=n.apply(t,e)).next())});function nze(t){return typeof t>"u"?!1:rze(t)||ize(t)}function rze(t){var e;return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&t.hasOwnProperty("track")&&typeof((e=t.publication)==null?void 0:e.track)<"u":!1}function ize(t){return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&t.hasOwnProperty("publication")&&typeof t.publication<"u":!1}function sze(t){return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&typeof t.publication>"u":!1}function oze(t){if(typeof t=="string"||typeof t=="number")return`${t}`;if(sze(t))return`${t.participant.identity}_${t.source}_placeholder`;if(nze(t))return`${t.participant.identity}_${t.publication.source}_${t.publication.trackSid}`;throw new Error(`Can't generate a id for the given track reference: ${t}`)}var aze=[ue.ConnectionStateChanged,ue.RoomMetadataChanged,ue.ActiveSpeakersChanged,ue.ConnectionQualityChanged,ue.ParticipantConnected,ue.ParticipantDisconnected,ue.ParticipantPermissionsChanged,ue.ParticipantMetadataChanged,ue.ParticipantNameChanged,ue.ParticipantAttributesChanged,ue.TrackMuted,ue.TrackUnmuted,ue.TrackPublished,ue.TrackUnpublished,ue.TrackStreamStateChanged,ue.TrackSubscriptionFailed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionStatusChanged],cze=[...aze,ue.LocalTrackPublished,ue.LocalTrackUnpublished];ce.TrackPublished,ce.TrackUnpublished,ce.TrackMuted,ce.TrackUnmuted,ce.TrackStreamStateChanged,ce.TrackSubscribed,ce.TrackUnsubscribed,ce.TrackSubscriptionPermissionChanged,ce.TrackSubscriptionFailed,ce.LocalTrackPublished,ce.LocalTrackUnpublished;var lze=[ce.ConnectionQualityChanged,ce.IsSpeakingChanged,ce.ParticipantMetadataChanged,ce.ParticipantPermissionsChanged,ce.TrackMuted,ce.TrackUnmuted,ce.TrackPublished,ce.TrackUnpublished,ce.TrackStreamStateChanged,ce.TrackSubscriptionFailed,ce.TrackSubscriptionPermissionChanged,ce.TrackSubscriptionStatusChanged];[...lze,ce.LocalTrackPublished,ce.LocalTrackUnpublished];var uze=eze.getLogger("lk-components-js");uze.setDefaultLevel("WARN");function dze(t,...e){return new Wn(r=>{const i=()=>{r.next(t)};return e.forEach(o=>{t.on(o,i)}),()=>{e.forEach(o=>{t.off(o,i)})}}).pipe(dn(t))}function fze(t,e){return new Wn(r=>{const i=(...o)=>{r.next(o)};return t.on(e,i),()=>{t.off(e,i)}})}function cz(t,e,n=!0){const r=new Wn(s=>{xu.getLocalDevices(t,n).then(o=>{s.next(o),s.complete()}).catch(o=>{e?.(o),s.next([]),s.complete()})}),i=new Wn(s=>{var o;const a=()=>tze(this,null,function*(){try{const c=yield xu.getLocalDevices(t,n);s.next(c)}catch(c){e?.(c)}});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");(o=navigator?.mediaDevices)==null||o.addEventListener("devicechange",a)}return()=>{var c;(c=navigator?.mediaDevices)==null||c.removeEventListener("devicechange",a)}});return mp(r,i)}function Y8(t,...e){return new Wn(r=>{const i=()=>{r.next(t)};return e.forEach(o=>{t.on(o,i)}),()=>{e.forEach(o=>{t.off(o,i)})}}).pipe(dn(t))}function X8(t){return Y8(t,ce.TrackMuted,ce.TrackUnmuted,ce.ParticipantPermissionsChanged,ce.TrackPublished,ce.TrackUnpublished,ce.LocalTrackPublished,ce.LocalTrackUnpublished,ce.MediaDevicesError,ce.TrackSubscriptionStatusChanged).pipe(Re(n=>{const{isMicrophoneEnabled:r,isCameraEnabled:i,isScreenShareEnabled:s}=n,o=n.getTrackPublication(he.Source.Microphone),a=n.getTrackPublication(he.Source.Camera);return{isCameraEnabled:i,isMicrophoneEnabled:r,isScreenShareEnabled:s,cameraTrack:a,microphoneTrack:o,participant:n}}))}function hze(t,e={}){var n;let r;const i=new Wn(c=>(r=c,()=>a.unsubscribe())).pipe(dn(Array.from(t.remoteParticipants.values()))),s=(n=e.additionalRoomEvents)!=null?n:cze,o=Array.from(new Set([ue.ParticipantConnected,ue.ParticipantDisconnected,ue.ConnectionStateChanged,...s])),a=dze(t,...o).subscribe(c=>r?.next(Array.from(c.remoteParticipants.values())));return t.remoteParticipants.size>0&&r?.next(Array.from(t.remoteParticipants.values())),i}const sg=new ii,Jle=new ii,Qle=new ii,VL=new ii;let lz=!1;const Zle=()=>{lz||(lz=!0,window.controls.onAudioPlaybackStarted?.())};window.controls={canEnterPip(){return sg.observed},enablePip(){if(!sg.observed)throw new Error("No call is running");sg.next(!0)},disablePip(){if(!sg.observed)throw new Error("No call is running");sg.next(!1)},setAvailableAudioDevices(t){M.info("setAvailableAudioDevices called from native:",t),Jle.next(t)},setAudioDevice(t){M.info("setAudioDevice called from native",t),Qle.next(t)},setAudioEnabled(t){if(M.info("setAudioEnabled called from native:",t),!VL.observed)throw new Error("Output controls are disabled. No setAudioEnabled$ observer");VL.next(t)},setOutputEnabled(t){this.setAudioEnabled(t)},setAvailableOutputDevices(t){this.setAvailableAudioDevices(t)},setOutputDevice(t){this.setAudioDevice(t)}};const b3=Symbol("nothing");function pze(t){return e=>Gqe(()=>{let n=b3;return e.pipe(vGe(r=>n=r),fGe(()=>{n!==b3&&t(n)}))})}function qL(t,e){return n=>n.pipe(ql(e,t),dn(t))}const uz=Symbol("switch");function mze(t,e){return n=>mp(n.pipe(Re((r,i)=>t(r,i)?uz:r),gGe(r=>r!==uz)),e)}function Bw(t){let e=b3;if(t.subscribe(n=>e=n).unsubscribe(),e===b3)throw new Error("Not a state Observable");return e}function dz(...t){return Xt(t,(...e)=>e.every(n=>n))}function z1(t){return e=>e.pipe(Tle(t),wle(([,n])=>n?t.pipe(es(r=>!r)):Ct(null)),Re(([n])=>n))}function eue(t){return new _s(t)}const fz="earpiece-id",tue=va==="ios"?eue(!0):Dle.value$;function mR(t,e,n,r){const i=a=>r.error("Error creating MediaDeviceObserver",a),s=cz(t,i,!1),o=cz(t,i,!0);return n.behavior(e.pipe(Ot(a=>a?s.pipe(mze((c,l)=>l===0&&c.every(d=>!d.label),o)):s)),[])}function J8(t){return new Map(t.map((e,n)=>[e.deviceId,e.label?{type:"name",name:e.label}:{type:"number",number:n+1}]))}function Q8(t,e){return Xt([t,e],(n,r)=>{if(n.size)return r!==void 0&&n.has(r)||n.size===1&&n.has("")?r:n.keys().next().value})}class gze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices AudioInput]"),this.availableRaw$=mR("audioinput",this.usingNames$,this.scope,this.logger),this.available$=this.scope.behavior(this.availableRaw$.pipe(Re(J8))),this.selected$=this.scope.behavior(Q8(this.available$,WK.value$).pipe(Re(r=>r===void 0?void 0:{id:r,hardwareDeviceChange$:this.availableRaw$.pipe(Re(i=>i.find(s=>s.deviceId===r)?.groupId),jw(),es(([i,s])=>i!==s),Re(()=>{}))}))),this.available$.subscribe(r=>{this.logger.info("[audio-input] available devices:",r)})}select(e){WK.setValue(e)}}class vze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices AudioOutput]"),this.available$=this.scope.behavior(mR("audiooutput",this.usingNames$,this.scope,this.logger).pipe(Re(r=>{let i=J8(r);return i.size&&!i.has("")&&!i.has("default")&&i.set("",{type:"default",name:r[0]?.label||null}),!!window.GestureEvent&&(i=new Map),i}))),this.selected$=this.scope.behavior(Q8(this.available$,YK.value$).pipe(Re(r=>r===void 0?void 0:{id:r,virtualEarpiece:!1}))),this.available$.subscribe(r=>{this.logger.info("[audio-output] available devices:",r)})}select(e){YK.setValue(e)}}class yze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices ControlledAudioOutput]"),this.availableRaw$=mR("audiooutput",this.usingNames$,this.scope,this.logger),this.available$=this.scope.behavior(Xt([Jle.pipe(dn([])),tue],(r,i)=>{const s=new Map(r.map(({id:o,name:a,isEarpiece:c,isSpeaker:l})=>{let d;return c?d={type:"earpiece"}:l?d={type:"speaker"}:d={type:"name",name:a},[o,d]}));return i&&r.some(o=>o.forEarpiece)&&s.set(fz,{type:"earpiece"}),s})),this.deviceSelection$=new ii,this.selected$=this.scope.behavior(Xt([this.available$,H_(Qle.pipe(dn(void 0)),this.deviceSelection$)],(r,i)=>{const s=i??r.keys().next().value;return s===void 0?void 0:{id:s,virtualEarpiece:s===fz}})),this.selected$.subscribe(r=>{r!==void 0&&(this.logger.info("[controlled-output] onAudioDeviceSelect called:",r),window.controls.onAudioDeviceSelect?.(r.id),window.controls.onOutputDeviceSelect?.(r.id))}),this.available$.subscribe(r=>{this.logger.info("[controlled-output] available devices:",r)}),this.availableRaw$.subscribe(r=>{this.logger.info("[controlled-output] available raw devices:",r)})}select(e){this.deviceSelection$.next(e)}}class bze{constructor(e,n){this.usingNames$=e,this.scope=n,this.logger=M.getChild("[MediaDevices VideoInput]"),this.available$=this.scope.behavior(mR("videoinput",this.usingNames$,this.scope,this.logger).pipe(Re(J8))),this.selected$=this.scope.behavior(Q8(this.available$,XK.value$).pipe(Re(r=>r===void 0?void 0:{id:r}))),this.available$.subscribe(r=>{this.logger.info("[video-input] available devices:",r)})}select(e){XK.setValue(e)}}class _ze{constructor(e){this.scope=e,this.deviceNamesRequest$=new ii,this.usingNames$=this.scope.behavior(this.deviceNamesRequest$.pipe(Re(()=>!0)),!1),this.audioInput=new gze(this.usingNames$,this.scope),this.audioOutput=Br().controlledAudioDevices?new yze(this.usingNames$,this.scope):new vze(this.usingNames$,this.scope),this.videoInput=new bze(this.usingNames$,this.scope)}requestDeviceNames(){this.deviceNamesRequest$.next()}}function Sze(t,e,n){if(!n)return _.useState(e)[0];const[r]=_.useState(()=>new _s(n)),[i]=_.useState(()=>e(r)),s=_.useRef(!0);return t(()=>{if(s.current){s.current=!1;return}r.next(n)},n),i}function Z8(t,e){return Sze(_.useEffect,t,e)}var Eze=t=>t+1|0,wze=()=>{const t=_.useState(0)[1];return _.useRef(()=>t(Eze)).current},nue=typeof window>"u"?_.useEffect:_.useLayoutEffect,hz=t=>t[1]?.next?t[1]:{next:t[1],error:t[2],complete:t[3]};function Cze(t,e){const n=_.useRef(e),r=_.useRef(),i=_.useRef();return nue(()=>{n.current=e,r.current=hz(e)}),t(()=>{const s=n.current[0];r.current||(r.current=hz(n.current));const o=s.subscribe({next:a=>{s===n.current[0]&&r.current.next?.(a)},error:a=>{s===n.current[0]&&(r.current.error?r.current.error(a):console.error(a))},complete:()=>{s===n.current[0]&&r.current.complete?.()}});return i.current=o,()=>{o.unsubscribe()}},[e[0]]),i}function Tze(t,e,n,r){return Cze(_.useEffect,[t,e,n,r])}function ai(t){const e=wze(),n=_.useRef(t),r=_.useRef(),i=_.useRef(!1),s=_.useRef(!1),[o,a]=_.useState(()=>{let c;return t.subscribe({next:l=>{s.current=!0,c=l},error:l=>{r.current=l}}).unsubscribe(),c});if(nue(()=>{n.current=t}),_.useEffect(()=>{r.current=null;const c=n.current;let l=o;const d=c.subscribe({next:h=>{c===n.current&&(i.current?a(()=>h):l=h)},error:h=>{c===n.current&&(r.current=h,e())}});return i.current||l!==o&&a(()=>l),i.current=!0,()=>{d.unsubscribe()}},[t]),r.current)throw r.current;if(s.current)return _.useDebugValue(o),o;throw new Error("Observable did not synchronously emit a value.")}function Rze(t){const[e]=_.useState(()=>new _s(t)),[n]=_.useState(()=>({get current(){return e.value},set current(r){e.next(r)}}));return[n,e]}const rue=_.createContext(void 0);function Wu(){const t=_.use(rue);if(t===void 0)throw new Error("useMediaDevices must be used within a MediaDevices context provider");return t}const Ize=()=>{const t=Wu(),e=ai(t.audioOutput.selected$),n=ai(t.audioOutput.available$);return e?.id?n.get(e.id)?.type==="earpiece":!1},iue=()=>{const t=Wu(),n=ai(t.audioOutput.selected$)?.virtualEarpiece??!1;return{pan:_.useMemo(()=>n?1:0,[n]),volume:_.useMemo(()=>n?.1:1,[n])}},kze=()=>{const{t}=We(),[e,n]=Gn(Ale),[r,i]=Gn(Ple),[s,o]=Gn(H8),a=(d,h)=>{h(d.target.checked)},[c,l]=Gn($8);return E.jsxs("div",{children:[E.jsx(an,{children:t("settings.preferences_tab.introduction")}),E.jsx(yt,{children:E.jsx(Tn,{id:"showHandRaisedTimer",label:t("settings.preferences_tab.show_hand_raised_timer_label"),description:t("settings.preferences_tab.show_hand_raised_timer_description"),type:"checkbox",checked:e,onChange:d=>a(d,n)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"showReactions",label:t("settings.preferences_tab.reactions_show_label"),description:t("settings.preferences_tab.reactions_show_description"),type:"checkbox",checked:r,onChange:d=>a(d,i)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"playReactionSound",label:t("settings.preferences_tab.reactions_play_sound_label"),description:t("settings.preferences_tab.reactions_play_sound_description"),type:"checkbox",checked:s,onChange:d=>a(d,o)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"developerSettingsTab",type:"checkbox",checked:c,label:t("settings.preferences_tab.developer_mode_label"),description:t("settings.preferences_tab.developer_mode_label_description"),onChange:d=>l(d.target.checked)})})]})};function sue(t,[e,n]){return Math.min(n,Math.max(e,t))}function yg(t,e,{checkForDefaultPrevented:n=!0}={}){return function(i){if(t?.(i),n===!1||!i.defaultPrevented)return e?.(i)}}function pz(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function oue(...t){return e=>{let n=!1;const r=t.map(i=>{const s=pz(i,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():pz(t[i],null)}}}}function Rf(...t){return _.useCallback(oue(...t),t)}function aue(t,e=[]){let n=[];function r(s,o){const a=_.createContext(o),c=n.length;n=[...n,o];const l=h=>{const{scope:m,children:g,...y}=h,v=m?.[t]?.[c]||a,w=_.useMemo(()=>y,Object.values(y));return E.jsx(v.Provider,{value:w,children:g})};l.displayName=s+"Provider";function d(h,m){const g=m?.[t]?.[c]||a,y=_.useContext(g);if(y)return y;if(o!==void 0)return o;throw new Error(`\`${h}\` must be used within \`${s}\``)}return[l,d]}const i=()=>{const s=n.map(o=>_.createContext(o));return function(a){const c=a?.[t]||s;return _.useMemo(()=>({[`__scope${t}`]:{...a,[t]:c}}),[a,c])}};return i.scopeName=t,[r,xze(i,...e)]}function xze(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(s){const o=r.reduce((a,{useScope:c,scopeName:l})=>{const h=c(s)[`__scope${l}`];return{...a,...h}},{});return _.useMemo(()=>({[`__scope${e.scopeName}`]:o}),[o])}};return n.scopeName=e.scopeName,n}var Aze=m_[" useInsertionEffect ".trim().toString()]||up;function Pze({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){const[i,s,o]=Lze({defaultProp:e,onChange:n}),a=t!==void 0,c=a?t:i;{const d=_.useRef(t!==void 0);_.useEffect(()=>{const h=d.current;h!==a&&console.warn(`${r} is changing from ${h?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const l=_.useCallback(d=>{if(a){const h=Oze(d)?d(t):d;h!==t&&o.current?.(h)}else s(d)},[a,t,s,o]);return[c,l]}function Lze({defaultProp:t,onChange:e}){const[n,r]=_.useState(t),i=_.useRef(n),s=_.useRef(e);return Aze(()=>{s.current=e},[e]),_.useEffect(()=>{i.current!==n&&(s.current?.(n),i.current=n)},[n,i]),[n,r,s]}function Oze(t){return typeof t=="function"}var Mze=_.createContext(void 0);function Dze(t){const e=_.useContext(Mze);return t||e||"ltr"}function Nze(t){const e=_.useRef({value:t,previous:t});return _.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}function Uze(t){const[e,n]=_.useState(void 0);return up(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,a;if("borderBoxSize"in s){const c=s.borderBoxSize,l=Array.isArray(c)?c[0]:c;o=l.inlineSize,a=l.blockSize}else o=t.offsetWidth,a=t.offsetHeight;n({width:o,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}function GL(t){const e=jze(t),n=_.forwardRef((r,i)=>{const{children:s,...o}=r,a=_.Children.toArray(s),c=a.find($ze);if(c){const l=c.props.children,d=a.map(h=>h===c?_.Children.count(l)>1?_.Children.only(null):_.isValidElement(l)?l.props.children:null:h);return E.jsx(e,{...o,ref:i,children:_.isValidElement(l)?_.cloneElement(l,void 0,d):null})}return E.jsx(e,{...o,ref:i,children:s})});return n.displayName=`${t}.Slot`,n}function jze(t){const e=_.forwardRef((n,r)=>{const{children:i,...s}=n;if(_.isValidElement(i)){const o=Hze(i),a=Bze(s,i.props);return i.type!==_.Fragment&&(a.ref=r?oue(r,o):o),_.cloneElement(i,a)}return _.Children.count(i)>1?_.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Fze=Symbol("radix.slottable");function $ze(t){return _.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Fze}function Bze(t,e){const n={...e};for(const r in e){const i=t[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...a)=>{const c=s(...a);return i(...a),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...t,...n}}function Hze(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Vze=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],q_=Vze.reduce((t,e)=>{const n=GL(`Primitive.${e}`),r=_.forwardRef((i,s)=>{const{asChild:o,...a}=i,c=o?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function qze(t){const e=t+"CollectionProvider",[n,r]=aue(e),[i,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),o=v=>{const{scope:w,children:S}=v,R=Ce.useRef(null),x=Ce.useRef(new Map).current;return E.jsx(i,{scope:w,itemMap:x,collectionRef:R,children:S})};o.displayName=e;const a=t+"CollectionSlot",c=GL(a),l=Ce.forwardRef((v,w)=>{const{scope:S,children:R}=v,x=s(a,S),T=Rf(w,x.collectionRef);return E.jsx(c,{ref:T,children:R})});l.displayName=a;const d=t+"CollectionItemSlot",h="data-radix-collection-item",m=GL(d),g=Ce.forwardRef((v,w)=>{const{scope:S,children:R,...x}=v,T=Ce.useRef(null),I=Rf(w,T),k=s(d,S);return Ce.useEffect(()=>(k.itemMap.set(T,{ref:T,...x}),()=>void k.itemMap.delete(T))),E.jsx(m,{[h]:"",ref:I,children:R})});g.displayName=d;function y(v){const w=s(t+"CollectionConsumer",v);return Ce.useCallback(()=>{const R=w.collectionRef.current;if(!R)return[];const x=Array.from(R.querySelectorAll(`[${h}]`));return Array.from(w.itemMap.values()).sort((k,A)=>x.indexOf(k.ref.current)-x.indexOf(A.ref.current))},[w.collectionRef,w.itemMap])}return[{Provider:o,Slot:l,ItemSlot:g},y,r]}var cue=["PageUp","PageDown"],lue=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],uue={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},i0="Slider",[KL,Gze,Kze]=qze(i0),[due,zat]=aue(i0,[Kze]),[zze,gR]=due(i0),fue=_.forwardRef((t,e)=>{const{name:n,min:r=0,max:i=100,step:s=1,orientation:o="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:l=[r],value:d,onValueChange:h=()=>{},onValueCommit:m=()=>{},inverted:g=!1,form:y,...v}=t,w=_.useRef(new Set),S=_.useRef(0),x=o==="horizontal"?Wze:Yze,[T=[],I]=Pze({prop:d,defaultProp:l,onChange:U=>{[...w.current][S.current]?.focus(),h(U)}}),k=_.useRef(T);function A(U){const $=eWe(T,U);N(U,$)}function O(U){N(U,S.current)}function D(){const U=k.current[S.current];T[S.current]!==U&&m(T)}function N(U,$,{commit:K}={commit:!1}){const Y=iWe(s),G=sWe(Math.round((U-r)/s)*s+r,Y),F=sue(G,[r,i]);I((q=[])=>{const z=Qze(q,F,$);if(rWe(z,c*s)){S.current=z.indexOf(F);const W=String(z)!==String(q);return W&&K&&m(z),W?z:q}else return q})}return E.jsx(zze,{scope:t.__scopeSlider,name:n,disabled:a,min:r,max:i,valueIndexToChangeRef:S,thumbs:w.current,values:T,orientation:o,form:y,children:E.jsx(KL.Provider,{scope:t.__scopeSlider,children:E.jsx(KL.Slot,{scope:t.__scopeSlider,children:E.jsx(x,{"aria-disabled":a,"data-disabled":a?"":void 0,...v,ref:e,onPointerDown:yg(v.onPointerDown,()=>{a||(k.current=T)}),min:r,max:i,inverted:g,onSlideStart:a?void 0:A,onSlideMove:a?void 0:O,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&N(r,0,{commit:!0}),onEndKeyDown:()=>!a&&N(i,T.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:$})=>{if(!a){const G=cue.includes(U.key)||U.shiftKey&&lue.includes(U.key)?10:1,F=S.current,q=T[F],z=s*G*$;N(q+z,F,{commit:!0})}}})})})})});fue.displayName=i0;var[hue,pue]=due(i0,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Wze=_.forwardRef((t,e)=>{const{min:n,max:r,dir:i,inverted:s,onSlideStart:o,onSlideMove:a,onSlideEnd:c,onStepKeyDown:l,...d}=t,[h,m]=_.useState(null),g=Rf(e,x=>m(x)),y=_.useRef(void 0),v=Dze(i),w=v==="ltr",S=w&&!s||!w&&s;function R(x){const T=y.current||h.getBoundingClientRect(),I=[0,T.width],A=e9(I,S?[n,r]:[r,n]);return y.current=T,A(x-T.left)}return E.jsx(hue,{scope:t.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width",children:E.jsx(mue,{dir:v,"data-orientation":"horizontal",...d,ref:g,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:x=>{const T=R(x.clientX);o?.(T)},onSlideMove:x=>{const T=R(x.clientX);a?.(T)},onSlideEnd:()=>{y.current=void 0,c?.()},onStepKeyDown:x=>{const I=uue[S?"from-left":"from-right"].includes(x.key);l?.({event:x,direction:I?-1:1})}})})}),Yze=_.forwardRef((t,e)=>{const{min:n,max:r,inverted:i,onSlideStart:s,onSlideMove:o,onSlideEnd:a,onStepKeyDown:c,...l}=t,d=_.useRef(null),h=Rf(e,d),m=_.useRef(void 0),g=!i;function y(v){const w=m.current||d.current.getBoundingClientRect(),S=[0,w.height],x=e9(S,g?[r,n]:[n,r]);return m.current=w,x(v-w.top)}return E.jsx(hue,{scope:t.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:E.jsx(mue,{"data-orientation":"vertical",...l,ref:h,style:{...l.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:v=>{const w=y(v.clientY);s?.(w)},onSlideMove:v=>{const w=y(v.clientY);o?.(w)},onSlideEnd:()=>{m.current=void 0,a?.()},onStepKeyDown:v=>{const S=uue[g?"from-bottom":"from-top"].includes(v.key);c?.({event:v,direction:S?-1:1})}})})}),mue=_.forwardRef((t,e)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:i,onSlideEnd:s,onHomeKeyDown:o,onEndKeyDown:a,onStepKeyDown:c,...l}=t,d=gR(i0,n);return E.jsx(q_.span,{...l,ref:e,onKeyDown:yg(t.onKeyDown,h=>{h.key==="Home"?(o(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):cue.concat(lue).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:yg(t.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),d.thumbs.has(m)?m.focus():r(h)}),onPointerMove:yg(t.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&i(h)}),onPointerUp:yg(t.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),s(h))})})}),gue="SliderTrack",vue=_.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,i=gR(gue,n);return E.jsx(q_.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...r,ref:e})});vue.displayName=gue;var zL="SliderRange",yue=_.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,i=gR(zL,n),s=pue(zL,n),o=_.useRef(null),a=Rf(e,o),c=i.values.length,l=i.values.map(m=>Sue(m,i.min,i.max)),d=c>1?Math.min(...l):0,h=100-Math.max(...l);return E.jsx(q_.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...r,ref:a,style:{...t.style,[s.startEdge]:d+"%",[s.endEdge]:h+"%"}})});yue.displayName=zL;var WL="SliderThumb",bue=_.forwardRef((t,e)=>{const n=Gze(t.__scopeSlider),[r,i]=_.useState(null),s=Rf(e,a=>i(a)),o=_.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return E.jsx(Xze,{...t,ref:s,index:o})}),Xze=_.forwardRef((t,e)=>{const{__scopeSlider:n,index:r,name:i,...s}=t,o=gR(WL,n),a=pue(WL,n),[c,l]=_.useState(null),d=Rf(e,R=>l(R)),h=c?o.form||!!c.closest("form"):!0,m=Uze(c),g=o.values[r],y=g===void 0?0:Sue(g,o.min,o.max),v=Zze(r,o.values.length),w=m?.[a.size],S=w?tWe(w,y,a.direction):0;return _.useEffect(()=>{if(c)return o.thumbs.add(c),()=>{o.thumbs.delete(c)}},[c,o.thumbs]),E.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${y}% + ${S}px)`},children:[E.jsx(KL.ItemSlot,{scope:t.__scopeSlider,children:E.jsx(q_.span,{role:"slider","aria-label":t["aria-label"]||v,"aria-valuemin":o.min,"aria-valuenow":g,"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:d,style:g===void 0?{display:"none"}:t.style,onFocus:yg(t.onFocus,()=>{o.valueIndexToChangeRef.current=r})})}),h&&E.jsx(_ue,{name:i??(o.name?o.name+(o.values.length>1?"[]":""):void 0),form:o.form,value:g},r)]})});bue.displayName=WL;var Jze="RadioBubbleInput",_ue=_.forwardRef(({__scopeSlider:t,value:e,...n},r)=>{const i=_.useRef(null),s=Rf(i,r),o=Nze(e);return _.useEffect(()=>{const a=i.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(o!==e&&d){const h=new Event("input",{bubbles:!0});d.call(a,e),a.dispatchEvent(h)}},[o,e]),E.jsx(q_.input,{style:{display:"none"},...n,ref:s,defaultValue:e})});_ue.displayName=Jze;function Qze(t=[],e,n){const r=[...t];return r[n]=e,r.sort((i,s)=>i-s)}function Sue(t,e,n){const s=100/(n-e)*(t-e);return sue(s,[0,100])}function Zze(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function eWe(t,e){if(t.length===1)return 0;const n=t.map(i=>Math.abs(i-e)),r=Math.min(...n);return n.indexOf(r)}function tWe(t,e,n){const r=t/2,s=e9([0,50],[0,r]);return(r-s(e)*n)*n}function nWe(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}function rWe(t,e){if(e>0){const n=nWe(t);return Math.min(...n)>=e}return!0}function e9(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function iWe(t){return(String(t).split(".")[1]||"").length}function sWe(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}var oWe=fue,aWe=vue,cWe=yue,lWe=bue;const uWe="_slider_15go1_8",dWe="_track_15go1_14",fWe="_highlight_15go1_31",hWe="_handle_15go1_43",SE={slider:uWe,track:dWe,highlight:fWe,handle:hWe},Eue=({className:t,label:e,value:n,onValueChange:r,onValueCommit:i,min:s,max:o,step:a,disabled:c})=>{const l=_.useCallback(([h])=>r(h),[r]),d=_.useCallback(([h])=>i?.(h),[i]);return E.jsxs(oWe,{className:Oe(t,SE.slider),value:[n],onValueChange:l,onValueCommit:d,min:s,max:o,step:a,disabled:c,children:[E.jsx(aWe,{className:SE.track,children:E.jsx(cWe,{className:SE.highlight})}),E.jsx(qi,{placement:"top",label:Math.round(n*100).toString()+"%",children:E.jsx(lWe,{className:SE.handle,"aria-label":e})})]})},pWe="_selection_1akwb_1",mWe="_title_1akwb_5",gWe="_separator_1akwb_10",vWe="_options_1akwb_14",yWe="_secondary_1akwb_20",W1={selection:pWe,title:mWe,separator:gWe,options:vWe,secondary:yWe},Ux=({device:t,title:e,numberedLabel:n})=>{const{t:r}=We(),i=_.useId(),s=ai(t.available$),o=ai(t.selected$)?.id,a=_.useCallback(c=>{t.select(c.target.value)},[t]);return s.size<=1?null:E.jsxs("div",{className:W1.selection,children:[E.jsx(gl,{type:"body",weight:"semibold",size:"sm",as:"h4",className:W1.title,children:e}),E.jsx(QM,{className:W1.separator}),E.jsx("div",{className:W1.options,children:[...s].map(([c,l])=>{let d;switch(l.type){case"name":d=l.name;break;case"number":d=n(l.number);break;case"default":d=l.name===null?r("settings.devices.default"):E.jsxs(Ys,{i18nKey:"settings.devices.default_named",name:l.name,children:["Default"," ",E.jsxs("span",{className:W1.secondary,children:["(",{name:l.name},")"]})]});break;case"speaker":d=r("settings.devices.loudspeaker");break;case"earpiece":d=r("settings.devices.handset");break}return E.jsx(RMe,{name:i,control:E.jsx(hMe,{checked:c===o,onChange:a,value:c}),children:E.jsx(gMe,{children:d})},c)})})]})};var vp=typeof self<"u"?self:{};function Sh(){throw Error("Invalid UTF8")}function mz(t,e){return e=String.fromCharCode.apply(null,e),t==null?e:t+e}let EE,jx;const bWe=typeof TextDecoder<"u";let _We;const SWe=typeof TextEncoder<"u";function wue(t){if(SWe)t=(_We||=new TextEncoder).encode(t);else{let n=0;const r=new Uint8Array(3*t.length);for(let i=0;i<t.length;i++){var e=t.charCodeAt(i);if(e<128)r[n++]=e;else{if(e<2048)r[n++]=e>>6|192;else{if(e>=55296&&e<=57343){if(e<=56319&&i<t.length){const s=t.charCodeAt(++i);if(s>=56320&&s<=57343){e=1024*(e-55296)+s-56320+65536,r[n++]=e>>18|240,r[n++]=e>>12&63|128,r[n++]=e>>6&63|128,r[n++]=63&e|128;continue}i--}e=65533}r[n++]=e>>12|224,r[n++]=e>>6&63|128}r[n++]=63&e|128}}t=n===r.length?r:r.subarray(0,n)}return t}var t9,_3;e:{for(var gz=["CLOSURE_FLAGS"],Fx=vp,$x=0;$x<gz.length;$x++)if((Fx=Fx[gz[$x]])==null){_3=null;break e}_3=Fx}var Wb,vz=_3&&_3[610401301];t9=vz!=null&&vz;const yz=vp.navigator;function YL(t){return!!t9&&!!Wb&&Wb.brands.some(({brand:e})=>e&&e.indexOf(t)!=-1)}function ia(t){var e;return(e=vp.navigator)&&(e=e.userAgent)||(e=""),e.indexOf(t)!=-1}function Bd(){return!!t9&&!!Wb&&Wb.brands.length>0}function Bx(){return Bd()?YL("Chromium"):(ia("Chrome")||ia("CriOS"))&&!(!Bd()&&ia("Edge"))||ia("Silk")}function n9(t){return n9[" "](t),t}Wb=yz&&yz.userAgentData||null,n9[" "]=function(){};var EWe=!Bd()&&(ia("Trident")||ia("MSIE"));!ia("Android")||Bx(),Bx(),ia("Safari")&&(Bx()||!Bd()&&ia("Coast")||!Bd()&&ia("Opera")||!Bd()&&ia("Edge")||(Bd()?YL("Microsoft Edge"):ia("Edg/"))||Bd()&&YL("Opera"));var Cue={},by=null;function wWe(t){const e=t.length;let n=3*e/4;n%3?n=Math.floor(n):"=.".indexOf(t[e-1])!=-1&&(n="=.".indexOf(t[e-2])!=-1?n-2:n-1);const r=new Uint8Array(n);let i=0;return function(s,o){function a(l){for(;c<s.length;){const d=s.charAt(c++),h=by[d];if(h!=null)return h;if(!/^[\s\xa0]*$/.test(d))throw Error("Unknown base64 encoding at char: "+d)}return l}Tue();let c=0;for(;;){const l=a(-1),d=a(0),h=a(64),m=a(64);if(m===64&&l===-1)break;o(l<<2|d>>4),h!=64&&(o(d<<4&240|h>>2),m!=64&&o(h<<6&192|m))}}(t,function(s){r[i++]=s}),i!==n?r.subarray(0,i):r}function Tue(){if(!by){by={};var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),e=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=t.concat(e[n].split(""));Cue[n]=r;for(let i=0;i<r.length;i++){const s=r[i];by[s]===void 0&&(by[s]=i)}}}}var Rue=typeof Uint8Array<"u",Iue=!EWe&&typeof btoa=="function";function bz(t){if(!Iue){var e;e===void 0&&(e=0),Tue(),e=Cue[e];var n=Array(Math.floor(t.length/3)),r=e[64]||"";let c=0,l=0;for(;c<t.length-2;c+=3){var i=t[c],s=t[c+1],o=t[c+2],a=e[i>>2];i=e[(3&i)<<4|s>>4],s=e[(15&s)<<2|o>>6],o=e[63&o],n[l++]=a+i+s+o}switch(a=0,o=r,t.length-c){case 2:o=e[(15&(a=t[c+1]))<<2]||r;case 1:t=t[c],n[l]=e[t>>2]+e[(3&t)<<4|a>>4]+o+r}return n.join("")}for(e="",n=0,r=t.length-10240;n<r;)e+=String.fromCharCode.apply(null,t.subarray(n,n+=10240));return e+=String.fromCharCode.apply(null,n?t.subarray(n):t),btoa(e)}const _z=/[-_.]/g,CWe={"-":"+",_:"/",".":"="};function TWe(t){return CWe[t]||""}function kue(t){if(!Iue)return wWe(t);_z.test(t)&&(t=t.replace(_z,TWe)),t=atob(t);const e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}function G_(t){return Rue&&t!=null&&t instanceof Uint8Array}var Cv={};function yp(){return RWe||=new Tu(null,Cv)}function r9(t){xue(Cv);var e=t.g;return(e=e==null||G_(e)?e:typeof e=="string"?kue(e):null)==null?e:t.g=e}var Tu=class{h(){return new Uint8Array(r9(this)||0)}constructor(t,e){if(xue(e),this.g=t,t!=null&&t.length===0)throw Error("ByteString should be constructed with non-empty values")}};let RWe,IWe;function xue(t){if(t!==Cv)throw Error("illegal external caller")}function Aue(t,e){t.__closure__error__context__984382||(t.__closure__error__context__984382={}),t.__closure__error__context__984382.severity=e}function XL(t){return Aue(t=Error(t),"warning"),t}var vR=typeof Symbol=="function"&&typeof Symbol()=="symbol",kWe=new Set;function K_(t,e,n=!1,r=!1){return t=typeof Symbol=="function"&&typeof Symbol()=="symbol"?r&&Symbol.for&&t?Symbol.for(t):t!=null?Symbol(t):Symbol():e,n&&kWe.add(t),t}var xWe=K_("jas",void 0,!0,!0),Sz=K_(void 0,"0di"),Hx=K_(void 0,"2ex"),Y1=K_(void 0,"1oa",!0),Tv=K_(void 0,Symbol(),!0);const ze=vR?xWe:"Ga",Pue={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},Lue=Object.defineProperties;function yR(t,e){vR||ze in t||Lue(t,Pue),t[ze]|=e}function $r(t,e){vR||ze in t||Lue(t,Pue),t[ze]=e}function s0(t){return yR(t,34),t}function AWe(t,e){$r(e,-30975&(0|t))}function JL(t,e){$r(e,-30941&(34|t))}function i9(){return typeof BigInt=="function"}function Js(t){return Array.prototype.slice.call(t)}var s9,z_={},Oue={};function Ez(t){return!(!t||typeof t!="object"||t.Ia!==Oue)}function o9(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&t.constructor===Object}function a9(t,e){if(t!=null){if(typeof t=="string")t=t?new Tu(t,Cv):yp();else if(t.constructor!==Tu)if(G_(t))t=t.length?new Tu(new Uint8Array(t),Cv):yp();else{if(!e)throw Error();t=void 0}}return t}function S3(t){return!(!Array.isArray(t)||t.length)&&!!(1&(0|t[ze]))}const wz=[];function Hf(t){if(2&t)throw Error()}$r(wz,55),s9=Object.freeze(wz);let Cz=class Mue{constructor(e,n,r){this.l=0,this.g=e,this.h=n,this.m=r}next(){if(this.l<this.g.length){const e=this.g[this.l++];return{done:!1,value:this.h?this.h.call(this.m,e):e}}return{done:!0,value:void 0}}[Symbol.iterator](){return new Mue(this.g,this.h,this.m)}};function c9(t){return Tv?t[Tv]:void 0}var PWe=Object.freeze({});function bR(t){return t.Qa=!0,t}var LWe=bR(t=>typeof t=="number"),Tz=bR(t=>typeof t=="string"),OWe=bR(t=>typeof t=="boolean"),_R=typeof vp.BigInt=="function"&&typeof vp.BigInt(0)=="bigint",QL=bR(t=>_R?t>=DWe&&t<=UWe:t[0]==="-"?Rz(t,MWe):Rz(t,NWe));const MWe=Number.MIN_SAFE_INTEGER.toString(),DWe=_R?BigInt(Number.MIN_SAFE_INTEGER):void 0,NWe=Number.MAX_SAFE_INTEGER.toString(),UWe=_R?BigInt(Number.MAX_SAFE_INTEGER):void 0;function Rz(t,e){if(t.length>e.length)return!1;if(t.length<e.length||t===e)return!0;for(let n=0;n<t.length;n++){const r=t[n],i=e[n];if(r>i)return!1;if(r<i)return!0}}const jWe=typeof Uint8Array.prototype.slice=="function";let Due,An=0,br=0;function Iz(t){const e=t>>>0;An=e,br=(t-e)/4294967296>>>0}function Rv(t){if(t<0){Iz(-t);const[e,n]=f9(An,br);An=e>>>0,br=n>>>0}else Iz(t)}function l9(t){const e=Due||=new DataView(new ArrayBuffer(8));e.setFloat32(0,+t,!0),br=0,An=e.getUint32(0,!0)}function u9(t,e){const n=4294967296*e+(t>>>0);return Number.isSafeInteger(n)?n:Yb(t,e)}function d9(t,e){const n=2147483648&e;return n&&(e=~e>>>0,(t=1+~t>>>0)==0&&(e=e+1>>>0)),typeof(t=u9(t,e))=="number"?n?-t:t:n?"-"+t:t}function Yb(t,e){if(t>>>=0,(e>>>=0)<=2097151)var n=""+(4294967296*e+t);else i9()?n=""+(BigInt(e)<<BigInt(32)|BigInt(t)):(t=(16777215&t)+6777216*(n=16777215&(t>>>24|e<<8))+6710656*(e=e>>16&65535),n+=8147497*e,e*=2,t>=1e7&&(n+=t/1e7>>>0,t%=1e7),n>=1e7&&(e+=n/1e7>>>0,n%=1e7),n=e+kz(n)+kz(t));return n}function kz(t){return t=String(t),"0000000".slice(t.length)+t}function SR(t){if(t.length<16)Rv(Number(t));else if(i9())t=BigInt(t),An=Number(t&BigInt(4294967295))>>>0,br=Number(t>>BigInt(32)&BigInt(4294967295));else{const e=+(t[0]==="-");br=An=0;const n=t.length;for(let r=e,i=(n-e)%6+e;i<=n;r=i,i+=6){const s=Number(t.slice(r,i));br*=1e6,An=1e6*An+s,An>=4294967296&&(br+=Math.trunc(An/4294967296),br>>>=0,An>>>=0)}if(e){const[r,i]=f9(An,br);An=r,br=i}}}function f9(t,e){return e=~e,t?t=1+~t:e+=1,[t,e]}const h9=typeof BigInt=="function"?BigInt.asIntN:void 0,FWe=typeof BigInt=="function"?BigInt.asUintN:void 0,Gg=Number.isSafeInteger,ER=Number.isFinite,E3=Math.trunc;function Vf(t){return t==null||typeof t=="number"?t:t==="NaN"||t==="Infinity"||t==="-Infinity"?Number(t):void 0}function Nue(t){return t==null||typeof t=="boolean"?t:typeof t=="number"?!!t:void 0}const $We=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function wR(t){switch(typeof t){case"bigint":return!0;case"number":return ER(t);case"string":return $We.test(t);default:return!1}}function o0(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return ER(t)?0|t:void 0}function Uue(t){if(t==null)return t;if(typeof t=="string"&&t)t=+t;else if(typeof t!="number")return;return ER(t)?t>>>0:void 0}function xz(t){if(t[0]==="-")return!1;const e=t.length;return e<20||e===20&&Number(t.substring(0,6))<184467}function p9(t){return t=E3(t),Gg(t)||(Rv(t),t=d9(An,br)),t}function m9(t){var e=E3(Number(t));if(Gg(e))return String(e);if((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),e=t.length,!(t[0]==="-"?e<20||e===20&&Number(t.substring(0,7))>-922337:e<19||e===19&&Number(t.substring(0,6))<922337))if(SR(t),t=An,2147483648&(e=br))if(i9())t=""+(BigInt(0|e)<<BigInt(32)|BigInt(t>>>0));else{const[n,r]=f9(t,e);t="-"+Yb(n,r)}else t=Yb(t,e);return t}function w3(t){return t==null?t:typeof t=="bigint"?(QL(t)?t=Number(t):(t=h9(64,t),t=QL(t)?Number(t):String(t)),t):wR(t)?typeof t=="number"?p9(t):m9(t):void 0}function BWe(t){if(t==null)return t;var e=typeof t;if(e==="bigint")return String(FWe(64,t));if(wR(t)){if(e==="string")return e=E3(Number(t)),Gg(e)&&e>=0?t=String(e):((e=t.indexOf("."))!==-1&&(t=t.substring(0,e)),xz(t)||(SR(t),t=Yb(An,br))),t;if(e==="number")return(t=E3(t))>=0&&Gg(t)?t:function(n){if(n<0){Rv(n);var r=Yb(An,br);return n=Number(r),Gg(n)?n:r}return xz(r=String(n))?r:(Rv(n),u9(An,br))}(t)}}function jue(t){if(typeof t!="string")throw Error();return t}function a0(t){if(t!=null&&typeof t!="string")throw Error();return t}function Iv(t){return t==null||typeof t=="string"?t:void 0}function g9(t,e,n,r){if(t!=null&&typeof t=="object"&&t.W===z_)return t;if(!Array.isArray(t))return n?2&r?((t=e[Sz])||(s0((t=new e).u),t=e[Sz]=t),e=t):e=new e:e=void 0,e;let i=n=0|t[ze];return i===0&&(i|=32&r),i|=2&r,i!==n&&$r(t,i),new e(t)}function HWe(t,e,n){if(e)e:{if(!wR(e=t))throw XL("int64");switch(typeof e){case"string":e=m9(e);break e;case"bigint":if(t=e=h9(64,e),Tz(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(LWe(t)&&!Number.isSafeInteger(t))throw Error(String(t));e=_R?BigInt(e):OWe(e)?e?"1":"0":Tz(e)?e.trim()||"0":String(e);break e;default:e=p9(e)}}else e=w3(t);return typeof(n=(t=e)==null?n?0:void 0:t)=="string"&&Gg(e=+n)?e:n}const VWe={};let qWe=function(){try{return n9(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),Vx=class{constructor(){this.g=new Map}get(e){return this.g.get(e)}set(e,n){return this.g.set(e,n),this.size=this.g.size,this}delete(e){return e=this.g.delete(e),this.size=this.g.size,e}clear(){this.g.clear(),this.size=this.g.size}has(e){return this.g.has(e)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(e,n){return this.g.forEach(e,n)}[Symbol.iterator](){return this.entries()}};const GWe=qWe?(Object.setPrototypeOf(Vx.prototype,Map.prototype),Object.defineProperties(Vx.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),Vx):class extends Map{constructor(){super()}};function Az(t){return t}function qx(t){if(2&t.L)throw Error("Cannot mutate an immutable Map")}var Ca=class extends GWe{constructor(t,e,n=Az,r=Az){super();let i=0|t[ze];i|=64,$r(t,i),this.L=i,this.S=e,this.R=n,this.Y=this.S?KWe:r;for(let s=0;s<t.length;s++){const o=t[s],a=n(o[0],!1,!0);let c=o[1];e?c===void 0&&(c=null):c=r(o[1],!1,!0,void 0,void 0,i),super.set(a,c)}}na(t=Pz){if(this.size!==0)return this.X(t)}X(t=Pz){const e=[],n=super.entries();for(var r;!(r=n.next()).done;)(r=r.value)[0]=t(r[0]),r[1]=t(r[1]),e.push(r);return e}clear(){qx(this),super.clear()}delete(t){return qx(this),super.delete(this.R(t,!0,!1))}entries(){var t=this.ma();return new Cz(t,zWe,this)}keys(){return this.Ha()}values(){var t=this.ma();return new Cz(t,Ca.prototype.get,this)}forEach(t,e){super.forEach((n,r)=>{t.call(e,this.get(r),r,this)})}set(t,e){return qx(this),(t=this.R(t,!0,!1))==null?this:e==null?(super.delete(t),this):super.set(t,this.Y(e,!0,!0,this.S,!1,this.L))}Na(t){const e=this.R(t[0],!1,!0);t=t[1],t=this.S?t===void 0?null:t:this.Y(t,!1,!0,void 0,!1,this.L),super.set(e,t)}has(t){return super.has(this.R(t,!1,!1))}get(t){t=this.R(t,!1,!1);const e=super.get(t);if(e!==void 0){var n=this.S;return n?((n=this.Y(e,!1,!0,n,this.ra,this.L))!==e&&super.set(t,n),n):e}}ma(){return Array.from(super.keys())}Ha(){return super.keys()}[Symbol.iterator](){return this.entries()}};function KWe(t,e,n,r,i,s){return t=g9(t,r,n,s),i&&(t=TR(t)),t}function Pz(t){return t}function zWe(t){return[t,this.get(t)]}let WWe,Fue,YWe;function Lz(){return WWe||=new Ca(s0([]),void 0,void 0,void 0,VWe)}function v9(t,e,n,r,i){if(t!=null){if(Array.isArray(t))t=S3(t)?void 0:i&&2&(0|t[ze])?t:y9(t,e,n,r!==void 0,i);else if(o9(t)){const s={};for(let o in t)s[o]=v9(t[o],e,n,r,i);t=s}else t=e(t,r);return t}}function y9(t,e,n,r,i){const s=r||n?0|t[ze]:0,o=r?!!(32&s):void 0;r=Js(t);for(let a=0;a<r.length;a++)r[a]=v9(r[a],e,n,o,i);return n&&((t=c9(t))&&(r[Tv]=Js(t)),n(s,r)),r}function XWe(t){return v9(t,$ue,void 0,void 0,!1)}function $ue(t){return t.W===z_?t.toJSON():t instanceof Ca?t.na(XWe):function(e){switch(typeof e){case"number":return isFinite(e)?e:String(e);case"bigint":return QL(e)?Number(e):String(e);case"boolean":return e?1:0;case"object":if(e)if(Array.isArray(e)){if(S3(e))return}else{if(G_(e))return bz(e);if(e instanceof Tu){const n=e.g;return n==null?"":typeof n=="string"?n:e.g=bz(n)}if(e instanceof Ca)return e.na()}}return e}(t)}function Bue(t){return y9(t,$ue,void 0,void 0,!1)}function lf(t,e,n){return t=Hue(t,e[0],e[1],n?1:2),e!==Fue&&n&&yR(t,16384),t}function Hue(t,e,n,r){if(t==null){var i=96;n?(t=[n],i|=512):t=[],e&&(i=-33521665&i|(1023&e)<<15)}else{if(!Array.isArray(t))throw Error("narr");if(2048&(i=0|t[ze]))throw Error("farr");if(64&i)return t;if(r===1||r===2||(i|=64),n&&(i|=512,n!==t[0]))throw Error("mid");e:{if(r=(n=t).length){const s=r-1;if(o9(n[s])){if((e=s-(512&(i|=256)?0:-1))>=1024)throw Error("pvtlmt");i=-33521665&i|(1023&e)<<15;break e}}if(e){if((e=Math.max(e,r-(512&i?0:-1)))>1024)throw Error("spvt");i=-33521665&i|(1023&e)<<15}}}return $r(t,i),t}function ZL(t,e,n=JL){if(t!=null){if(Rue&&t instanceof Uint8Array)return e?t:new Uint8Array(t);if(Array.isArray(t)){var r=0|t[ze];return 2&r?t:(e&&=r===0||!!(32&r)&&!(64&r||!(16&r)),e?($r(t,-12293&(34|r)),t):y9(t,ZL,4&r?JL:n,!0,!0))}return t.W===z_?t=2&(r=0|(n=t.u)[ze])?t:new t.constructor(CR(n,r,!0)):t instanceof Ca&&!(2&t.L)&&(n=s0(t.X(ZL)),t=new Ca(n,t.S,t.R,t.Y)),t}}function CR(t,e,n){const r=n||2&e?JL:AWe,i=!!(32&e);return t=function(s,o,a){const c=Js(s);var l=c.length;const d=256&o?c[l-1]:void 0;for(l+=d?-1:0,o=512&o?1:0;o<l;o++)c[o]=a(c[o]);if(d){o=c[o]={};for(const h in d)o[h]=a(d[h])}return(s=c9(s))&&(c[Tv]=Js(s)),c}(t,e,s=>ZL(s,i,r)),yR(t,32|(n?2:0)),t}function TR(t){const e=t.u,n=0|e[ze];return 2&n?new t.constructor(CR(e,n,!1)):t}function kv(t,e){return Yu(t=t.u,0|t[ze],e)}function Yu(t,e,n,r){if(n===-1)return null;var i=n+(512&e?0:-1);const s=t.length-1;return i>=s&&256&e?t[s][n]:r&&256&e&&(e=t[s][n])!=null?(t[i]!=null&&Hx!=null&&((i=(t=IWe??={})[Hx]||0)>=4||(t[Hx]=i+1,Aue(t=Error(),"incident"),function(o){vp.setTimeout(()=>{throw o},0)}(t))),e):i<=s?t[i]:void 0}function Fn(t,e,n){const r=t.u;let i=0|r[ze];return Hf(i),ur(r,i,e,n),t}function ur(t,e,n,r){const i=512&e?0:-1,s=n+i;var o=t.length-1;return s>=o&&256&e?(t[o][n]=r,e):s<=o?(t[s]=r,256&e&&n in(t=t[o])&&delete t[n],e):(r!==void 0&&(n>=(o=e>>15&1023||536870912)?r!=null&&(t[o+i]={[n]:r},$r(t,e|=256)):t[s]=r),e)}function Hw(t,e){let n=0|(t=t.u)[ze];const r=Yu(t,n,e),i=Vf(r);return i!=null&&i!==r&&ur(t,n,e,i),i}function Vue(t){let e=0|(t=t.u)[ze];const n=Yu(t,e,1),r=a9(n,!0);return r!=null&&r!==n&&ur(t,e,1,r),r}function Fh(){return PWe===void 0?2:4}function $h(t,e,n,r,i){const s=t.u,o=2&(t=0|s[ze])?1:r;i=!!i;let a=0|(r=b9(s,t,e))[ze];if(!(4&a)){4&a&&(r=Js(r),a=Ru(a,t),t=ur(s,t,e,r));let c=0,l=0;for(;c<r.length;c++){const d=n(r[c]);d!=null&&(r[l++]=d)}l<c&&(r.length=l),a=_9(a,t),n=-4097&(20|a),a=n&=-8193,$r(r,a),2&a&&Object.freeze(r)}return o===1||o===4&&32&a?gu(a)||(i=a,a|=2,a!==i&&$r(r,a),Object.freeze(r)):(o===2&&gu(a)&&(r=Js(r),a=Ru(a,t),a=uf(a,t,i),$r(r,a),t=ur(s,t,e,r)),gu(a)||(e=a,a=uf(a,t,i),a!==e&&$r(r,a))),r}function b9(t,e,n,r){return t=Yu(t,e,n,r),Array.isArray(t)?t:s9}function _9(t,e){return t===0&&(t=Ru(t,e)),1|t}function gu(t){return!!(2&t)&&!!(4&t)||!!(2048&t)}function que(t){t=Js(t);for(let e=0;e<t.length;e++){const n=t[e]=Js(t[e]);Array.isArray(n[1])&&(n[1]=s0(n[1]))}return t}function eO(t,e,n,r){let i=0|(t=t.u)[ze];Hf(i),ur(t,i,e,(r==="0"?Number(n)===0:n===r)?void 0:n)}function c0(t,e,n,r,i){Hf(e);var s=!(!(64&e)&&16384&e);const o=(i=b9(t,e,n,i))!==s9;if(s||!o){let a=s=o?0|i[ze]:0;(!o||2&a||gu(a)||4&a&&!(32&a))&&(i=Js(i),a=Ru(a,e),e=ur(t,e,n,i)),a=-13&_9(a,e),a=uf(r?-17&a:16|a,e,!0),a!==s&&$r(i,a)}return i}function Gx(t,e){var n=Ode;return E9(S9(t=t.u),t,0|t[ze],n)===e?e:-1}function S9(t){if(vR)return t[Y1]??(t[Y1]=new Map);if(Y1 in t)return t[Y1];const e=new Map;return Object.defineProperty(t,Y1,{value:e}),e}function Gue(t,e,n,r){const i=S9(t),s=E9(i,t,e,n);return s!==r&&(s&&(e=ur(t,e,s)),i.set(n,r)),e}function E9(t,e,n,r){let i=t.get(r);if(i!=null)return i;i=0;for(let s=0;s<r.length;s++){const o=r[s];Yu(e,n,o)!=null&&(i!==0&&(n=ur(e,n,i)),i=o)}return t.set(r,i),i}function w9(t,e,n,r){let i,s=0|t[ze];if((r=Yu(t,s,n,r))!=null&&r.W===z_)return(e=TR(r))!==r&&ur(t,s,n,e),e.u;if(Array.isArray(r)){const o=0|r[ze];i=2&o?lf(CR(r,o,!1),e,!0):64&o?r:lf(i,e,!0)}else i=lf(void 0,e,!0);return i!==r&&ur(t,s,n,i),i}function Kue(t,e,n,r){let i=0|(t=t.u)[ze];return(e=g9(r=Yu(t,i,n,r),e,!1,i))!==r&&e!=null&&ur(t,i,n,e),e}function zt(t,e,n,r=!1){if((e=Kue(t,e,n,r))==null)return e;if(!(2&(r=0|(t=t.u)[ze]))){const i=TR(e);i!==e&&ur(t,r,n,e=i)}return e}function zue(t,e,n,r,i,s,o){t=t.u;var a=!!(2&e);const c=a?1:i;s=!!s,o&&=!a;var l=0|(i=b9(t,e,r))[ze];if(!(a=!!(4&l))){var d=i,h=e;const m=!!(2&(l=_9(l,e)));m&&(h|=2);let g=!m,y=!0,v=0,w=0;for(;v<d.length;v++){const S=g9(d[v],n,!1,h);if(S instanceof n){if(!m){const R=!!(2&(0|S.u[ze]));g&&=!R,y&&=R}d[w++]=S}}w<v&&(d.length=w),l|=4,l=y?16|l:-17&l,$r(d,l=g?8|l:-9&l),m&&Object.freeze(d)}if(o&&!(8&l||!i.length&&(c===1||c===4&&32&l))){for(gu(l)&&(i=Js(i),l=Ru(l,e),e=ur(t,e,r,i)),n=i,o=l,d=0;d<n.length;d++)(l=n[d])!==(h=TR(l))&&(n[d]=h);o|=8,$r(n,o=n.length?-17&o:16|o),l=o}return c===1||c===4&&32&l?gu(l)||(e=l,(l|=!i.length||16&l&&(!a||32&l)?2:2048)!==e&&$r(i,l),Object.freeze(i)):(c===2&&gu(l)&&($r(i=Js(i),l=uf(l=Ru(l,e),e,s)),e=ur(t,e,r,i)),gu(l)||(r=l,(l=uf(l,e,s))!==r&&$r(i,l))),i}function $u(t,e,n){const r=0|t.u[ze];return zue(t,r,e,n,Fh(),!1,!(2&r))}function Ye(t,e,n,r){return r==null&&(r=void 0),Fn(t,n,r)}function Xy(t,e,n,r){r==null&&(r=void 0);e:{let i=0|(t=t.u)[ze];if(Hf(i),r==null){const s=S9(t);if(E9(s,t,i,n)!==e)break e;s.set(n,0)}else i=Gue(t,i,n,e);ur(t,i,e,r)}}function Ru(t,e){return-2049&(t=32|(2&e?2|t:-3&t))}function uf(t,e,n){return 32&e&&n||(t&=-33),t}function C3(t,e,n,r){const i=0|t.u[ze];Hf(i),t=zue(t,i,n,e,2,!0),r=r??new n,t.push(r),t[ze]=2&(0|r.u[ze])?-9&t[ze]:-17&t[ze]}function fa(t,e){return o0(kv(t,e))}function Ta(t,e){return Iv(kv(t,e))}function Tr(t,e){return Hw(t,e)??0}function Xb(t,e,n){if(n!=null&&typeof n!="boolean")throw t=typeof n,Error(`Expected boolean but got ${t!="object"?t:n?Array.isArray(n)?"array":t:"null"}: ${n}`);Fn(t,e,n)}function sl(t,e,n){if(n!=null){if(typeof n!="number"||!ER(n))throw XL("int32");n|=0}Fn(t,e,n)}function Ve(t,e,n){if(n!=null&&typeof n!="number")throw Error(`Value of float/double field must be a number, found ${typeof n}: ${n}`);Fn(t,e,n)}function T3(t,e,n){{const o=t.u;let a=0|o[ze];if(Hf(a),n==null)ur(o,a,e);else{var r=t=0|n[ze],i=gu(t),s=i||Object.isFrozen(n);for(i||(t=0),s||(n=Js(n),r=0,t=uf(t=Ru(t,a),a,!0),s=!1),t|=21,i=0;i<n.length;i++){const c=n[i],l=jue(c);Object.is(c,l)||(s&&(n=Js(n),r=0,t=uf(t=Ru(t,a),a,!0),s=!1),n[i]=l)}t!==r&&(s&&(n=Js(n),t=uf(t=Ru(t,a),a,!0)),$r(n,t)),ur(o,a,e,n)}}}function RR(t,e,n){Hf(0|t.u[ze]),$h(t,e,Iv,2,!0).push(jue(n))}function Wue(t,e){return Error(`Invalid wire type: ${t} (at position ${e})`)}function C9(){return Error("Failed to read varint, encoding is invalid.")}function Yue(t,e){return Error(`Tried to read past the end of the data ${e} > ${t}`)}function T9(t){if(typeof t=="string")return{buffer:kue(t),N:!1};if(Array.isArray(t))return{buffer:new Uint8Array(t),N:!1};if(t.constructor===Uint8Array)return{buffer:t,N:!1};if(t.constructor===ArrayBuffer)return{buffer:new Uint8Array(t),N:!1};if(t.constructor===Tu)return{buffer:r9(t)||new Uint8Array(0),N:!0};if(t instanceof Uint8Array)return{buffer:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),N:!1};throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers")}function R9(t,e){let n,r=0,i=0,s=0;const o=t.h;let a=t.g;do n=o[a++],r|=(127&n)<<s,s+=7;while(s<32&&128&n);for(s>32&&(i|=(127&n)>>4),s=3;s<32&&128&n;s+=7)n=o[a++],i|=(127&n)<<s;if(Qh(t,a),n<128)return e(r>>>0,i>>>0);throw C9()}function I9(t){let e=0,n=t.g;const r=n+10,i=t.h;for(;n<r;){const s=i[n++];if(e|=s,(128&s)==0)return Qh(t,n),!!(127&e)}throw C9()}function If(t){const e=t.h;let n=t.g,r=e[n++],i=127&r;if(128&r&&(r=e[n++],i|=(127&r)<<7,128&r&&(r=e[n++],i|=(127&r)<<14,128&r&&(r=e[n++],i|=(127&r)<<21,128&r&&(r=e[n++],i|=r<<28,128&r&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++]&&128&e[n++])))))throw C9();return Qh(t,n),i}function Bu(t){return If(t)>>>0}function tO(t){var e=t.h;const n=t.g,r=e[n],i=e[n+1],s=e[n+2];return e=e[n+3],Qh(t,t.g+4),(r<<0|i<<8|s<<16|e<<24)>>>0}function nO(t){var e=tO(t);t=2*(e>>31)+1;const n=e>>>23&255;return e&=8388607,n==255?e?NaN:t*(1/0):n==0?1401298464324817e-60*t*e:t*Math.pow(2,n-150)*(e+8388608)}function JWe(t){return If(t)}function Kx(t,e,{ba:n=!1}={}){t.ba=n,e&&(e=T9(e),t.h=e.buffer,t.m=e.N,t.j=0,t.l=t.h.length,t.g=t.j)}function Qh(t,e){if(t.g=e,e>t.l)throw Yue(t.l,e)}function Xue(t,e){if(e<0)throw Error(`Tried to read a negative byte length: ${e}`);const n=t.g,r=n+e;if(r>t.l)throw Yue(e,t.l-n);return t.g=r,n}function Jue(t,e){if(e==0)return yp();var n=Xue(t,e);return t.ba&&t.m?n=t.h.subarray(n,n+e):(t=t.h,n=n===(e=n+e)?new Uint8Array(0):jWe?t.slice(n,e):new Uint8Array(t.subarray(n,e))),n.length==0?yp():new Tu(n,Cv)}Ca.prototype.toJSON=void 0,Ca.prototype.Ia=Oue;var Oz=[];function Que(t){var e=t.g;if(e.g==e.l)return!1;t.l=t.g.g;var n=Bu(t.g);if(e=n>>>3,!((n&=7)>=0&&n<=5))throw Wue(n,t.l);if(e<1)throw Error(`Invalid field number: ${e} (at position ${t.l})`);return t.m=e,t.h=n,!0}function Vw(t){switch(t.h){case 0:t.h!=0?Vw(t):I9(t.g);break;case 1:Qh(t=t.g,t.g+8);break;case 2:if(t.h!=2)Vw(t);else{var e=Bu(t.g);Qh(t=t.g,t.g+e)}break;case 5:Qh(t=t.g,t.g+4);break;case 3:for(e=t.m;;){if(!Que(t))throw Error("Unmatched start-group tag: stream EOF");if(t.h==4){if(t.m!=e)throw Error("Unmatched end-group tag");break}Vw(t)}break;default:throw Wue(t.h,t.l)}}function W_(t,e,n){const r=t.g.l,i=Bu(t.g),s=t.g.g+i;let o=s-r;if(o<=0&&(t.g.l=s,n(e,t,void 0,void 0,void 0),o=s-t.g.g),o)throw Error(`Message parsing ended unexpectedly. Expected to read ${i} bytes, instead read ${i-o} bytes, either the data ended unexpectedly or the message misreported its own length`);return t.g.g=s,t.g.l=r,e}function k9(t){var e=Bu(t.g),n=Xue(t=t.g,e);if(t=t.h,bWe){var r,i=t;(r=jx)||(r=jx=new TextDecoder("utf-8",{fatal:!0})),e=n+e,i=n===0&&e===i.length?i:i.subarray(n,e);try{var s=r.decode(i)}catch(a){if(EE===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),EE=!0}catch{EE=!1}}throw!EE&&(jx=void 0),a}}else{e=(s=n)+e,n=[];let a,c=null;for(;s<e;){var o=t[s++];o<128?n.push(o):o<224?s>=e?Sh():(a=t[s++],o<194||(192&a)!=128?(s--,Sh()):n.push((31&o)<<6|63&a)):o<240?s>=e-1?Sh():(a=t[s++],(192&a)!=128||o===224&&a<160||o===237&&a>=160||(192&(r=t[s++]))!=128?(s--,Sh()):n.push((15&o)<<12|(63&a)<<6|63&r)):o<=244?s>=e-2?Sh():(a=t[s++],(192&a)!=128||a-144+(o<<28)>>30!=0||(192&(r=t[s++]))!=128||(192&(i=t[s++]))!=128?(s--,Sh()):(o=(7&o)<<18|(63&a)<<12|(63&r)<<6|63&i,o-=65536,n.push(55296+(o>>10&1023),56320+(1023&o)))):Sh(),n.length>=8192&&(c=mz(c,n),n.length=0)}s=mz(c,n)}return s}function Zue(t){const e=Bu(t.g);return Jue(t.g,e)}function IR(t,e,n){var r=Bu(t.g);for(r=t.g.g+r;t.g.g<r;)n.push(e(t.g))}var wE=[];function QWe(t){return t}let Kg;function dc(t,e,n){e.g?e.m(t,e.g,e.h,n):e.m(t,e.h,n)}var He=class{constructor(t,e){this.u=Hue(t,e)}toJSON(){const t=!Kg;try{return t&&(Kg=Bue),ede(this)}finally{t&&(Kg=void 0)}}l(){var t=MYe;return t.g?t.l(this,t.g,t.h,!0):t.l(this,t.h,t.defaultValue,!0)}clone(){const t=this.u;return new this.constructor(CR(t,0|t[ze],!1))}N(){return!!(2&(0|this.u[ze]))}};function ede(t){var e=t.u;{e=(t=Kg(e))!==e;let l=t.length;if(l){var n=t[l-1],r=o9(n);r?l--:n=void 0;var i=t;if(r){e:{var s,o=n,a=!1;if(o)for(let d in o)isNaN(+d)?(s??={})[d]=o[d]:(r=o[d],Array.isArray(r)&&(S3(r)||Ez(r)&&r.size===0)&&(r=null),r==null&&(a=!0),r!=null&&((s??={})[d]=r));if(a||(s=o),s)for(let d in s){a=s;break e}a=null}o=a==null?n!=null:a!==n}for(;l>0&&((s=i[l-1])==null||S3(s)||Ez(s)&&s.size===0);l--)var c=!0;(i!==t||o||c)&&(e?(c||o||a)&&(i.length=l):i=Array.prototype.slice.call(i,0,l),a&&i.push(a)),c=i}else c=t}return c}function Mz(t){return t?/^\d+$/.test(t)?(SR(t),new rO(An,br)):null:ZWe||=new rO(0,0)}He.prototype.W=z_,He.prototype.toString=function(){try{return Kg=QWe,ede(this).toString()}finally{Kg=void 0}};var rO=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let ZWe;function Dz(t){return t?/^-?\d+$/.test(t)?(SR(t),new iO(An,br)):null:eYe||=new iO(0,0)}var iO=class{constructor(t,e){this.h=t>>>0,this.g=e>>>0}};let eYe;function zg(t,e,n){for(;n>0||e>127;)t.g.push(127&e|128),e=(e>>>7|n<<25)>>>0,n>>>=7;t.g.push(e)}function l0(t,e){for(;e>127;)t.g.push(127&e|128),e>>>=7;t.g.push(e)}function kR(t,e){if(e>=0)l0(t,e);else{for(let n=0;n<9;n++)t.g.push(127&e|128),e>>=7;t.g.push(1)}}function Jb(t,e){t.g.push(e>>>0&255),t.g.push(e>>>8&255),t.g.push(e>>>16&255),t.g.push(e>>>24&255)}function xv(t,e){e.length!==0&&(t.l.push(e),t.h+=e.length)}function Lo(t,e,n){l0(t.g,8*e+n)}function x9(t,e){return Lo(t,e,2),e=t.g.end(),xv(t,e),e.push(t.h),e}function A9(t,e){var n=e.pop();for(n=t.h+t.g.length()-n;n>127;)e.push(127&n|128),n>>>=7,t.h++;e.push(n),t.h++}function xR(t,e,n){Lo(t,e,2),l0(t.g,n.length),xv(t,t.g.end()),xv(t,n)}function R3(t,e,n,r){n!=null&&(e=x9(t,e),r(n,t),A9(t,e))}function fc(){const t=class{constructor(){throw Error()}};return Object.setPrototypeOf(t,t.prototype),t}var P9=fc(),tde=fc(),L9=fc(),O9=fc(),nde=fc(),rde=fc(),M9=fc(),ide=fc(),sde=fc(),u0=class{constructor(e,n,r){this.g=e,this.h=n,e=P9,this.l=!!e&&r===e||!1}};function AR(t,e){return new u0(t,e,P9)}function ode(t,e,n,r,i){R3(t,n,ude(e,r),i)}const tYe=AR(function(t,e,n,r,i){return t.h===2&&(W_(t,w9(e,r,n),i),!0)},ode),nYe=AR(function(t,e,n,r,i){return t.h===2&&(W_(t,w9(e,r,n,!0),i),!0)},ode);var PR=Symbol(),D9=Symbol(),Nz=Symbol(),Uz=Symbol();let ade,cde;function Fp(t,e,n,r){var i=r[t];if(i)return i;(i={}).Pa=r,i.V=function(h){switch(typeof h){case"boolean":return Fue||=[0,void 0,!0];case"number":return h>0?void 0:h===0?YWe||=[0,void 0]:[-h,void 0];case"string":return[0,h];case"object":return h}}(r[0]);var s=r[1];let o=1;s&&s.constructor===Object&&(i.ga=s,typeof(s=r[++o])=="function"&&(i.la=!0,ade??=s,cde??=r[o+1],s=r[o+=2]));const a={};for(;s&&Array.isArray(s)&&s.length&&typeof s[0]=="number"&&s[0]>0;){for(var c=0;c<s.length;c++)a[s[c]]=s;s=r[++o]}for(c=1;s!==void 0;){let h;typeof s=="number"&&(c+=s,s=r[++o]);var l=void 0;if(s instanceof u0?h=s:(h=tYe,o--),h?.l){s=r[++o],l=r;var d=o;typeof s=="function"&&(s=s(),l[d]=s),l=s}for(d=c+1,typeof(s=r[++o])=="number"&&s<0&&(d-=s,s=r[++o]);c<d;c++){const m=a[c];l?n(i,c,h,l,m):e(i,c,h,m)}}return r[t]=i}function lde(t){return Array.isArray(t)?t[0]instanceof u0?t:[nYe,t]:[t,void 0]}function ude(t,e){return t instanceof He?t.u:Array.isArray(t)?lf(t,e,!1):void 0}function N9(t,e,n,r){const i=n.g;t[e]=r?(s,o,a)=>i(s,o,a,r):i}function U9(t,e,n,r,i){const s=n.g;let o,a;t[e]=(c,l,d)=>s(c,l,d,a||=Fp(D9,N9,U9,r).V,o||=j9(r),i)}function j9(t){let e=t[Nz];if(e!=null)return e;const n=Fp(D9,N9,U9,t);return e=n.la?(r,i)=>ade(r,i,n):(r,i)=>{const s=0|r[ze];for(;Que(i)&&i.h!=4;){var o=i.m,a=n[o];if(a==null){var c=n.ga;c&&(c=c[o])&&(c=rYe(c))!=null&&(a=n[o]=c)}a!=null&&a(i,r,o)||(o=(a=i).l,Vw(a),a.fa?a=void 0:(c=a.g.g-o,a.g.g=o,a=Jue(a.g,c)),o=r,a&&((c=o[Tv])?c.push(a):o[Tv]=[a]))}return 16384&s&&s0(r),!0},t[Nz]=e}function rYe(t){const e=(t=lde(t))[0].g;if(t=t[1]){const n=j9(t),r=Fp(D9,N9,U9,t).V;return(i,s,o)=>e(i,s,o,r,n)}return e}function LR(t,e,n){t[e]=n.h}function OR(t,e,n,r){let i,s;const o=n.h;t[e]=(a,c,l)=>o(a,c,l,s||=Fp(PR,LR,OR,r).V,i||=dde(r))}function dde(t){let e=t[Uz];if(!e){const n=Fp(PR,LR,OR,t);e=(r,i)=>fde(r,i,n),t[Uz]=e}return e}function fde(t,e,n){for(var r=0|t[ze],i=512&r?0:-1,s=t.length,o=512&r?1:0,a=s+(256&r?-1:0);o<a;o++){const c=t[o];if(c==null)continue;const l=o-i,d=jz(n,l);d&&d(e,c,l)}if(256&r){r=t[s-1];for(const c in r)i=+c,Number.isNaN(i)||(s=r[i])!=null&&(a=jz(n,i))&&a(e,s,i)}if(t=c9(t))for(xv(e,e.g.end()),n=0;n<t.length;n++)xv(e,r9(t[n])||new Uint8Array(0))}function jz(t,e){var n=t[e];if(n)return n;if((n=t.ga)&&(n=n[e])){var r=(n=lde(n))[0].h;if(n=n[1]){const i=dde(n),s=Fp(PR,LR,OR,n).V;n=t.la?cde(s,i):(o,a,c)=>r(o,a,c,s,i)}else n=r;return t[e]=n}}function d0(t,e){if(Array.isArray(e)){var n=0|e[ze];if(4&n)return e;for(var r=0,i=0;r<e.length;r++){const s=t(e[r]);s!=null&&(e[i++]=s)}return i<r&&(e.length=i),$r(e,-12289&(5|n)),2&n&&Object.freeze(e),e}}function Ts(t,e,n){return new u0(t,e,n)}function f0(t,e,n){return new u0(t,e,n)}function Rs(t,e,n){ur(t,0|t[ze],e,n)}var iYe=AR(function(t,e,n,r,i){return t.h===2&&(t=W_(t,lf([void 0,void 0],r,!0),i),Hf(r=0|e[ze]),(i=Yu(e,r,n))instanceof Ca?(2&i.L)!=0?((i=i.X()).push(t),ur(e,r,n,i)):i.Na(t):Array.isArray(i)?(2&(0|i[ze])&&ur(e,r,n,i=que(i)),i.push(t)):ur(e,r,n,[t]),!0)},function(t,e,n,r,i){if(e instanceof Ca)e.forEach((s,o)=>{R3(t,n,lf([o,s],r,!1),i)});else if(Array.isArray(e))for(let s=0;s<e.length;s++){const o=e[s];Array.isArray(o)&&R3(t,n,lf(o,r,!1),i)}});function hde(t,e,n){if(e=function(r){if(r==null)return r;const i=typeof r;if(i==="bigint")return String(h9(64,r));if(wR(r)){if(i==="string")return m9(r);if(i==="number")return p9(r)}}(e),e!=null&&(typeof e=="string"&&Dz(e),e!=null))switch(Lo(t,n,0),typeof e){case"number":t=t.g,Rv(e),zg(t,An,br);break;case"bigint":n=BigInt.asUintN(64,e),n=new iO(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),zg(t.g,n.h,n.g);break;default:n=Dz(e),zg(t.g,n.h,n.g)}}function pde(t,e,n){(e=o0(e))!=null&&e!=null&&(Lo(t,n,0),kR(t.g,e))}function mde(t,e,n){(e=Nue(e))!=null&&(Lo(t,n,0),t.g.g.push(e?1:0))}function gde(t,e,n){(e=Iv(e))!=null&&xR(t,n,wue(e))}function vde(t,e,n,r,i){R3(t,n,ude(e,r),i)}function yde(t,e,n){(e=e==null||typeof e=="string"||G_(e)||e instanceof Tu?e:void 0)!=null&&xR(t,n,T9(e).buffer)}function bde(t,e,n){return(t.h===5||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,nO,e):e.push(nO(t.g)),!0)}var tu=Ts(function(t,e,n){if(t.h!==1)return!1;var r=t.g;t=tO(r);const i=tO(r);r=2*(i>>31)+1;const s=i>>>20&2047;return t=4294967296*(1048575&i)+t,Rs(e,n,s==2047?t?NaN:r*(1/0):s==0?5e-324*r*t:r*Math.pow(2,s-1075)*(t+4503599627370496)),!0},function(t,e,n){(e=Vf(e))!=null&&(Lo(t,n,1),t=t.g,(n=Due||=new DataView(new ArrayBuffer(8))).setFloat64(0,+e,!0),An=n.getUint32(0,!0),br=n.getUint32(4,!0),Jb(t,An),Jb(t,br))},fc()),Hr=Ts(function(t,e,n){return t.h===5&&(Rs(e,n,nO(t.g)),!0)},function(t,e,n){(e=Vf(e))!=null&&(Lo(t,n,5),t=t.g,l9(e),Jb(t,An))},M9),sYe=f0(bde,function(t,e,n){if((e=d0(Vf,e))!=null)for(let o=0;o<e.length;o++){var r=t,i=n,s=e[o];s!=null&&(Lo(r,i,5),r=r.g,l9(s),Jb(r,An))}},M9),F9=f0(bde,function(t,e,n){if((e=d0(Vf,e))!=null&&e.length){Lo(t,n,2),l0(t.g,4*e.length);for(let r=0;r<e.length;r++)n=t.g,l9(e[r]),Jb(n,An)}},M9),kf=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,R9(t.g,d9)),!0)},hde,rde),zx=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=R9(t.g,d9))===0?void 0:t),!0)},hde,rde),oYe=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,R9(t.g,u9)),!0)},function(t,e,n){if((e=BWe(e))!=null&&(typeof e=="string"&&Mz(e),e!=null))switch(Lo(t,n,0),typeof e){case"number":t=t.g,Rv(e),zg(t,An,br);break;case"bigint":n=BigInt.asUintN(64,e),n=new rO(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),zg(t.g,n.h,n.g);break;default:n=Mz(e),zg(t.g,n.h,n.g)}},fc()),Er=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,If(t.g)),!0)},pde,O9),MR=f0(function(t,e,n){return(t.h===0||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,If,e):e.push(If(t.g)),!0)},function(t,e,n){if((e=d0(o0,e))!=null&&e.length){n=x9(t,n);for(let r=0;r<e.length;r++)kR(t.g,e[r]);A9(t,n)}},O9),bg=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=If(t.g))===0?void 0:t),!0)},pde,O9),er=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,I9(t.g)),!0)},mde,tde),Wg=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=I9(t.g))===!1?void 0:t),!0)},mde,tde),Qi=f0(function(t,e,n){return t.h===2&&(t=k9(t),c0(e,0|e[ze],n,!1).push(t),!0)},function(t,e,n){if((e=d0(Iv,e))!=null)for(let o=0;o<e.length;o++){var r=t,i=n,s=e[o];s!=null&&xR(r,i,wue(s))}},L9),Hd=Ts(function(t,e,n){return t.h===2&&(Rs(e,n,(t=k9(t))===""?void 0:t),!0)},gde,L9),fn=Ts(function(t,e,n){return t.h===2&&(Rs(e,n,k9(t)),!0)},gde,L9),ni=function(t,e,n=P9){return new u0(t,e,n)}(function(t,e,n,r,i){return t.h===2&&(r=lf(void 0,r,!0),c0(e,0|e[ze],n,!0).push(r),W_(t,r,i),!0)},function(t,e,n,r,i){if(Array.isArray(e))for(let s=0;s<e.length;s++)vde(t,e[s],n,r,i)}),gn=AR(function(t,e,n,r,i,s){return t.h===2&&(Gue(e,0|e[ze],s,n),W_(t,e=w9(e,r,n),i),!0)},vde),_de=Ts(function(t,e,n){return t.h===2&&(Rs(e,n,Zue(t)),!0)},yde,ide),aYe=f0(function(t,e,n){return(t.h===0||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,Bu,e):e.push(Bu(t.g)),!0)},function(t,e,n){if((e=d0(Uue,e))!=null)for(let o=0;o<e.length;o++){var r=t,i=n,s=e[o];s!=null&&(Lo(r,i,0),l0(r.g,s))}},nde),cYe=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,(t=Bu(t.g))===0?void 0:t),!0)},function(t,e,n){(e=Uue(e))!=null&&e!=null&&(Lo(t,n,0),l0(t.g,e))},nde),Ra=Ts(function(t,e,n){return t.h===0&&(Rs(e,n,If(t.g)),!0)},function(t,e,n){(e=o0(e))!=null&&(e=parseInt(e,10),Lo(t,n,0),kR(t.g,e))},sde);class lYe{constructor(e,n){this.h=e,this.g=n,this.l=zt,this.m=Ye,this.defaultValue=void 0}}function hc(t,e){return new lYe(t,e)}function qf(t,e){return(n,r)=>{if(wE.length){const s=wE.pop();s.o(r),Kx(s.g,n,r),n=s}else n=new class{constructor(s,o){if(Oz.length){const a=Oz.pop();Kx(a,s,o),s=a}else s=new class{constructor(a,c){this.h=null,this.m=!1,this.g=this.l=this.j=0,Kx(this,a,c)}clear(){this.h=null,this.m=!1,this.g=this.l=this.j=0,this.ba=!1}}(s,o);this.g=s,this.l=this.g.g,this.h=this.m=-1,this.o(o)}o({fa:s=!1}={}){this.fa=s}}(n,r);try{const s=new t,o=s.u;j9(e)(o,n);var i=s}finally{n.g.clear(),n.m=-1,n.h=-1,wE.length<100&&wE.push(n)}return i}}function DR(t){return function(){const e=new class{constructor(){this.l=[],this.h=0,this.g=new class{constructor(){this.g=[]}length(){return this.g.length}end(){const o=this.g;return this.g=[],o}}}};fde(this.u,e,Fp(PR,LR,OR,t)),xv(e,e.g.end());const n=new Uint8Array(e.h),r=e.l,i=r.length;let s=0;for(let o=0;o<i;o++){const a=r[o];n.set(a,s),s+=a.length}return e.l=[n],n}}var Fz=class extends He{constructor(t){super(t)}},$z=[0,Hd,Ts(function(t,e,n){return t.h===2&&(Rs(e,n,(t=Zue(t))===yp()?void 0:t),!0)},function(t,e,n){if(e!=null){if(e instanceof He){const r=e.Ra;return void(r&&(e=r(e),e!=null&&xR(t,n,T9(e).buffer)))}if(Array.isArray(e))return}yde(t,e,n)},ide)];let Wx,Bz=globalThis.trustedTypes;function Hz(t){Wx===void 0&&(Wx=function(){let n=null;if(!Bz)return n;try{const r=i=>i;n=Bz.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}());var e=Wx;return new class{constructor(n){this.g=n}toString(){return this.g+""}}(e?e.createScriptURL(t):t)}function uYe(t,...e){if(e.length===0)return Hz(t[0]);let n=t[0];for(let r=0;r<e.length;r++)n+=encodeURIComponent(e[r])+t[r+1];return Hz(n)}var Sde=[0,Er,Ra,er,-1,MR,Ra,-1],dYe=class extends He{constructor(t){super(t)}},Ede=[0,er,fn,er,Ra,-1,f0(function(t,e,n){return(t.h===0||t.h===2)&&(e=c0(e,0|e[ze],n,!1,!1),t.h==2?IR(t,JWe,e):e.push(If(t.g)),!0)},function(t,e,n){if((e=d0(o0,e))!=null&&e.length){n=x9(t,n);for(let r=0;r<e.length;r++)kR(t.g,e[r]);A9(t,n)}},sde),fn,-1,[0,er,-1],Ra,er,-1],wde=[0,fn,-2],Vz=class extends He{constructor(t){super(t)}},Cde=[0],Tde=[0,Er,er,1,er,-3],xo=class extends He{constructor(t){super(t,2)}},Vr={};Vr[336783863]=[0,fn,er,-1,Er,[0,[1,2,3,4,5,6,7,8],gn,Cde,gn,Ede,gn,wde,gn,Tde,gn,Sde,gn,[0,fn,-2],gn,[0,fn,Ra],gn,[0,Ra,fn]],[0,fn],er,[0,[1,3],[2,4],gn,[0,MR],-1,gn,[0,Qi],-1,ni,[0,fn,-1]],fn];var qz=[0,zx,-1,Wg,-3,zx,MR,Hd,bg,zx,-1,Wg,bg,Wg,-2,Hd];function Oo(t,e){eO(t,2,a0(e),"")}function $n(t,e){RR(t,3,e)}function $t(t,e){RR(t,4,e)}var Ss=class extends He{constructor(t){super(t,500)}o(t){return Ye(this,0,7,t)}},Jy=[-1,{}],Gz=[0,fn,1,Jy],Kz=[0,fn,Qi,Jy];function Mo(t,e){C3(t,1,Ss,e)}function zn(t,e){RR(t,10,e)}function Zt(t,e){RR(t,15,e)}var ro=class extends He{constructor(t){super(t,500)}o(t){return Ye(this,0,1001,t)}},Rde=[-500,ni,[-500,Hd,-1,Qi,-3,[-2,Vr,er],ni,$z,bg,-1,Gz,Kz,ni,[0,Hd,Wg],Hd,qz,bg,Qi,987,Qi],4,ni,[-500,fn,-1,[-1,{}],998,fn],ni,[-500,fn,Qi,-1,[-2,{},er],997,Qi,-1],bg,ni,[-500,fn,Qi,Jy,998,Qi],Qi,bg,Gz,Kz,ni,[0,Hd,-1,Jy],Qi,-2,qz,Hd,-1,Wg,[0,Wg,cYe],978,Jy,ni,$z];ro.prototype.g=DR(Rde);var fYe=qf(ro,Rde),hYe=class extends He{constructor(t){super(t)}},Ide=class extends He{constructor(e){super(e)}g(){return $u(this,hYe,1)}},kde=[0,ni,[0,Er,Hr,fn,-1]],NR=qf(Ide,kde),pYe=class extends He{constructor(t){super(t)}},mYe=class extends He{constructor(e){super(e)}},Yx=class extends He{constructor(t){super(t)}h(){return zt(this,pYe,2)}g(){return $u(this,mYe,5)}},xde=qf(class extends He{constructor(t){super(t)}},[0,Qi,MR,F9,[0,Ra,[0,Er,-3],[0,Hr,-3],[0,Er,-1,[0,ni,[0,Er,-2]]],ni,[0,Hr,-1,fn,Hr]],fn,-1,kf,ni,[0,Er,Hr],Qi,kf]),Ade=class extends He{constructor(t){super(t)}},Yg=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,Hr,-4]]),Pde=class extends He{constructor(t){super(t)}},Y_=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,Hr,-4]]),gYe=class extends He{constructor(t){super(t)}},vYe=[0,Er,-1,F9,Ra],Lde=class extends He{constructor(t){super(t)}};Lde.prototype.g=DR([0,Hr,-4,kf]);var yYe=class extends He{constructor(t){super(t)}},bYe=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,1,Er,fn,kde],kf]),zz=class extends He{constructor(t){super(t)}},_Ye=class extends He{constructor(t){super(t)}oa(){const t=Vue(this);return t??yp()}},SYe=class extends He{constructor(t){super(t)}},Ode=[1,2],EYe=qf(class extends He{constructor(t){super(t)}},[0,ni,[0,Ode,gn,[0,F9],gn,[0,_de],Er,fn],kf]),$9=class extends He{constructor(t){super(t)}},Mde=[0,fn,Er,Hr,Qi,-1],Wz=class extends He{constructor(t){super(t)}},wYe=[0,er,-1],Yz=class extends He{constructor(t){super(t)}},qw=[1,2,3,4,5],I3=class extends He{constructor(t){super(t)}g(){return Vue(this)!=null}h(){return Ta(this,2)!=null}},rr=class extends He{constructor(t){super(t)}g(){return Nue(kv(this,2))??!1}},Dde=[0,_de,fn,[0,Er,kf,-1],[0,oYe,kf]],xr=[0,Dde,er,[0,qw,gn,Tde,gn,Ede,gn,Sde,gn,Cde,gn,wde],Ra],UR=class extends He{constructor(t){super(t)}},B9=[0,xr,Hr,-1,Er],CYe=hc(502141897,UR);Vr[502141897]=B9;var TYe=qf(class extends He{constructor(t){super(t)}},[0,[0,Ra,-1,sYe,aYe],vYe]),Nde=class extends He{constructor(t){super(t)}},Ude=class extends He{constructor(t){super(t)}},H9=[0,xr,Hr,[0,xr],er],jde=[0,xr,B9,H9,Hr,[0,[0,Dde]]],RYe=hc(508968150,Ude);Vr[508968150]=jde,Vr[508968149]=H9;var Fde=class extends He{constructor(t){super(t)}},IYe=hc(513916220,Fde);Vr[513916220]=[0,xr,jde,Er];var Vm=class extends He{constructor(t){super(t)}h(){return zt(this,$9,2)}g(){Fn(this,2)}},$de=[0,xr,Mde];Vr[478825465]=$de;var kYe=class extends He{constructor(t){super(t)}},Bde=class extends He{constructor(e){super(e)}},V9=class extends He{constructor(e){super(e)}},q9=class extends He{constructor(t){super(t)}},Hde=class extends He{constructor(t){super(t)}},Xz=[0,xr,[0,xr],$de,-1],Vde=[0,xr,Hr,Er],G9=[0,xr,Hr],qde=[0,xr,Vde,G9,Hr],xYe=hc(479097054,Hde);Vr[479097054]=[0,xr,qde,Xz],Vr[463370452]=Xz,Vr[464864288]=Vde;var AYe=hc(462713202,q9);Vr[462713202]=qde,Vr[474472470]=G9;var PYe=class extends He{constructor(t){super(t)}},Gde=class extends He{constructor(t){super(t)}},Kde=class extends He{constructor(t){super(t)}},zde=class extends He{constructor(t){super(t)}},K9=[0,xr,Hr,-1,Er],sO=[0,xr,Hr,er];zde.prototype.g=DR([0,xr,G9,[0,xr],B9,H9,K9,sO]);var Wde=class extends He{constructor(t){super(t)}},LYe=hc(456383383,Wde);Vr[456383383]=[0,xr,Mde];var Yde=class extends He{constructor(t){super(t)}},OYe=hc(476348187,Yde);Vr[476348187]=[0,xr,wYe];var Xde=class extends He{constructor(t){super(t)}},Jz=class extends He{constructor(t){super(t)}},Jde=[0,Ra,-1],MYe=hc(458105876,class extends He{constructor(t){super(t)}g(){var t=this.u;const e=0|t[ze],n=2&e;return t=function(r,i,s){var o=Jz;const a=2&i;let c=!1;if(s==null){if(a)return Lz();s=[]}else if(s.constructor===Ca){if((2&s.L)==0||a)return s;s=s.X()}else Array.isArray(s)?c=!!(2&(0|s[ze])):s=[];if(a){if(!s.length)return Lz();c||(c=!0,s0(s))}else c&&(c=!1,s=que(s));return c||(64&(0|s[ze])?s[ze]&=-33:32&i&&yR(s,32)),ur(r,i,2,o=new Ca(s,o,HWe,void 0)),o}(t,e,Yu(t,e,2)),!n&&Jz&&(t.ra=!0),t}});Vr[458105876]=[0,Jde,iYe,[!0,kf,[0,fn,-1,Qi]]];var z9=class extends He{constructor(t){super(t)}},Qde=hc(458105758,z9);Vr[458105758]=[0,xr,fn,Jde];var Zde=class extends He{constructor(t){super(t)}},DYe=hc(443442058,Zde);Vr[443442058]=[0,xr,fn,Er,Hr,Qi,-1,er,Hr],Vr[514774813]=K9;var efe=class extends He{constructor(t){super(t)}},NYe=hc(516587230,efe);function oO(t,e){return e=e?e.clone():new $9,t.displayNamesLocale!==void 0?Fn(e,1,a0(t.displayNamesLocale)):t.displayNamesLocale===void 0&&Fn(e,1),t.maxResults!==void 0?sl(e,2,t.maxResults):"maxResults"in t&&Fn(e,2),t.scoreThreshold!==void 0?Ve(e,3,t.scoreThreshold):"scoreThreshold"in t&&Fn(e,3),t.categoryAllowlist!==void 0?T3(e,4,t.categoryAllowlist):"categoryAllowlist"in t&&Fn(e,4),t.categoryDenylist!==void 0?T3(e,5,t.categoryDenylist):"categoryDenylist"in t&&Fn(e,5),e}function W9(t,e=-1,n=""){return{categories:t.map(r=>({index:fa(r,1)??0??-1,score:Tr(r,2)??0,categoryName:Ta(r,3)??""??"",displayName:Ta(r,4)??""??""})),headIndex:e,headName:n}}function tfe(t){var e=$h(t,3,Vf,Fh()),n=$h(t,2,o0,Fh()),r=$h(t,1,Iv,Fh()),i=$h(t,9,Iv,Fh());const s={categories:[],keypoints:[]};for(let o=0;o<e.length;o++)s.categories.push({score:e[o],index:n[o]??-1,categoryName:r[o]??"",displayName:i[o]??""});if((e=zt(t,Yx,4)?.h())&&(s.boundingBox={originX:fa(e,1)??0,originY:fa(e,2)??0,width:fa(e,3)??0,height:fa(e,4)??0,angle:0}),zt(t,Yx,4)?.g().length)for(const o of zt(t,Yx,4).g())s.keypoints.push({x:Hw(o,1)??0,y:Hw(o,2)??0,score:Hw(o,4)??0,label:Ta(o,3)??""});return s}function jR(t){const e=[];for(const n of $u(t,Pde,1))e.push({x:Tr(n,1)??0,y:Tr(n,2)??0,z:Tr(n,3)??0,visibility:Tr(n,4)??0});return e}function Qy(t){const e=[];for(const n of $u(t,Ade,1))e.push({x:Tr(n,1)??0,y:Tr(n,2)??0,z:Tr(n,3)??0,visibility:Tr(n,4)??0});return e}function Qz(t){return Array.from(t,e=>e>127?e-256:e)}function Zz(t,e){if(t.length!==e.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${t.length} vs. ${e.length}).`);let n=0,r=0,i=0;for(let s=0;s<t.length;s++)n+=t[s]*e[s],r+=t[s]*t[s],i+=e[s]*e[s];if(r<=0||i<=0)throw Error("Cannot compute cosine similarity on embedding with 0 norm.");return n/Math.sqrt(r*i)}let CE;Vr[516587230]=[0,xr,K9,sO,Hr],Vr[518928384]=sO;const UYe=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);async function nfe(){if(CE===void 0)try{await WebAssembly.instantiate(UYe),CE=!0}catch{CE=!1}return CE}async function X1(t,e=uYe``){const n=await nfe()?"wasm_internal":"wasm_nosimd_internal";return{wasmLoaderPath:`${e}/${t}_${n}.js`,wasmBinaryPath:`${e}/${t}_${n}.wasm`}}var Ph=class{};function rfe(){var t=navigator;return typeof OffscreenCanvas<"u"&&(!function(e=navigator){return(e=e.userAgent).includes("Safari")&&!e.includes("Chrome")}(t)||!!((t=t.userAgent.match(/Version\/([\d]+).*Safari/))&&t.length>=1&&Number(t[1])>=17))}async function eW(t){if(typeof importScripts!="function"){const e=document.createElement("script");return e.src=t.toString(),e.crossOrigin="anonymous",new Promise((n,r)=>{e.addEventListener("load",()=>{n()},!1),e.addEventListener("error",i=>{r(i)},!1),document.body.appendChild(e)})}importScripts(t.toString())}function ife(t){return t.videoWidth!==void 0?[t.videoWidth,t.videoHeight]:t.naturalWidth!==void 0?[t.naturalWidth,t.naturalHeight]:t.displayWidth!==void 0?[t.displayWidth,t.displayHeight]:[t.width,t.height]}function Ke(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(e=t.i.stringToNewUTF8(e)),t.i._free(e)}function tW(t,e,n){if(!t.i.canvas)throw Error("No OpenGL canvas configured.");if(n?t.i._bindTextureToStream(n):t.i._bindTextureToCanvas(),!(n=t.i.canvas.getContext("webgl2")||t.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e),t.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[r,i]=ife(e);return!t.l||r===t.i.canvas.width&&i===t.i.canvas.height||(t.i.canvas.width=r,t.i.canvas.height=i),[r,i]}function nW(t,e,n){t.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const r=new Uint32Array(e.length);for(let i=0;i<e.length;i++)r[i]=t.i.stringToNewUTF8(e[i]);e=t.i._malloc(4*r.length),t.i.HEAPU32.set(r,e>>2),n(e);for(const i of r)t.i._free(i);t.i._free(e)}function Ic(t,e,n){t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=n}function Cd(t,e,n){let r=[];t.i.simpleListeners=t.i.simpleListeners||{},t.i.simpleListeners[e]=(i,s,o)=>{s?(n(r,o),r=[]):r.push(i)}}Ph.forVisionTasks=function(t){return X1("vision",t)},Ph.forTextTasks=function(t){return X1("text",t)},Ph.forGenAiExperimentalTasks=function(t){return X1("genai_experimental",t)},Ph.forGenAiTasks=function(t){return X1("genai",t)},Ph.forAudioTasks=function(t){return X1("audio",t)},Ph.isSimdSupported=function(){return nfe()};async function jYe(t,e,n,r){return t=await(async(i,s,o,a,c)=>{if(s&&await eW(s),!self.ModuleFactory||o&&(await eW(o),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((s=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(s.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new i(c,a)})(t,n.wasmLoaderPath,n.assetLoaderPath,e,{locateFile:i=>i.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&i.endsWith(".data")?n.assetBinaryPath.toString():i}),await t.o(r),t}function Xx(t,e){const n=zt(t.baseOptions,I3,1)||new I3;typeof e=="string"?(Fn(n,2,a0(e)),Fn(n,1)):e instanceof Uint8Array&&(Fn(n,1,a9(e,!1)),Fn(n,2)),Ye(t.baseOptions,0,1,n)}function rW(t){try{const e=t.G.length;if(e===1)throw Error(t.G[0].message);if(e>1)throw Error("Encountered multiple errors: "+t.G.map(n=>n.message).join(", "))}finally{t.G=[]}}function je(t,e){t.B=Math.max(t.B,e)}function FR(t,e){t.A=new Ss,Oo(t.A,"PassThroughCalculator"),$n(t.A,"free_memory"),$t(t.A,"free_memory_unused_out"),zn(e,"free_memory"),Mo(e,t.A)}function Av(t,e){$n(t.A,e),$t(t.A,e+"_unused_out")}function $R(t){t.g.addBoolToStream(!0,"free_memory",t.B)}var Gw=class{constructor(t){this.g=t,this.G=[],this.B=0,this.g.setAutoRenderToScreen(!1)}l(t,e=!0){if(e){const n=t.baseOptions||{};if(t.baseOptions?.modelAssetBuffer&&t.baseOptions?.modelAssetPath)throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!(zt(this.baseOptions,I3,1)?.g()||zt(this.baseOptions,I3,1)?.h()||t.baseOptions?.modelAssetBuffer||t.baseOptions?.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(r,i){let s=zt(r.baseOptions,Yz,3);if(!s){var o=s=new Yz,a=new Vz;Xy(o,4,qw,a)}"delegate"in i&&(i.delegate==="GPU"?(i=s,o=new dYe,Xy(i,2,qw,o)):(i=s,o=new Vz,Xy(i,4,qw,o))),Ye(r.baseOptions,0,3,s)}(this,n),n.modelAssetPath)return fetch(n.modelAssetPath.toString()).then(r=>{if(r.ok)return r.arrayBuffer();throw Error(`Failed to fetch model: ${n.modelAssetPath} (${r.status})`)}).then(r=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(r),!0,!1,!1),Xx(this,"/model.dat"),this.m(),this.I()});if(n.modelAssetBuffer instanceof Uint8Array)Xx(this,n.modelAssetBuffer);else if(n.modelAssetBuffer)return async function(r){const i=[];for(var s=0;;){const{done:o,value:a}=await r.read();if(o)break;i.push(a),s+=a.length}if(i.length===0)return new Uint8Array(0);if(i.length===1)return i[0];r=new Uint8Array(s),s=0;for(const o of i)r.set(o,s),s+=o.length;return r}(n.modelAssetBuffer).then(r=>{Xx(this,r),this.m(),this.I()})}return this.m(),this.I(),Promise.resolve()}I(){}da(){let t;if(this.g.da(e=>{t=fYe(e)}),!t)throw Error("Failed to retrieve CalculatorGraphConfig");return t}setGraph(t,e){this.g.attachErrorListener((n,r)=>{this.G.push(Error(r))}),this.g.La(),this.g.setGraph(t,e),this.A=void 0,rW(this)}finishProcessing(){this.g.finishProcessing(),rW(this)}close(){this.A=void 0,this.g.closeGraph()}};function Iu(t,e){if(!t)throw Error(`Unable to obtain required WebGL resource: ${e}`);return t}Gw.prototype.close=Gw.prototype.close,function(t,e){t=t.split(".");var n,r=vp;for((t[0]in r)||r.execScript===void 0||r.execScript("var "+t[0]);t.length&&(n=t.shift());)t.length||e===void 0?r=r[n]&&r[n]!==Object.prototype[n]?r[n]:r[n]={}:r[n]=e}("TaskRunner",Gw);class FYe{constructor(e,n,r,i){this.g=e,this.h=n,this.m=r,this.l=i}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function iW(t,e,n){const r=t.g;if(n=Iu(r.createShader(n),"Failed to create WebGL shader"),r.shaderSource(n,e),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${r.getShaderInfoLog(n)}`);return r.attachShader(t.h,n),n}function sW(t,e){const n=t.g,r=Iu(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const i=Iu(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(t.O),n.vertexAttribPointer(t.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const s=Iu(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,s),n.enableVertexAttribArray(t.I),n.vertexAttribPointer(t.I,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(e?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new FYe(n,r,i,s)}function Y9(t,e){if(t.g){if(e!==t.g)throw Error("Cannot change GL context once initialized")}else t.g=e}function X9(t,e,n,r){return Y9(t,e),t.h||(t.m(),t.C()),n?(t.s||(t.s=sW(t,!0)),n=t.s):(t.v||(t.v=sW(t,!1)),n=t.v),e.useProgram(t.h),n.bind(),t.l(),t=r(),n.g.bindVertexArray(null),t}function BR(t,e,n){return Y9(t,e),t=Iu(e.createTexture(),"Failed to create texture"),e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n??e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,n??e.LINEAR),e.bindTexture(e.TEXTURE_2D,null),t}function HR(t,e,n){Y9(t,e),t.A||(t.A=Iu(e.createFramebuffer(),"Failed to create framebuffe.")),e.bindFramebuffer(e.FRAMEBUFFER,t.A),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0)}function J9(t){t.g?.bindFramebuffer(t.g.FRAMEBUFFER,null)}var Q9=class{G(){return`
214
214
  precision mediump float;
215
215
  varying vec2 vTex;
216
216
  uniform sampler2D inputTexture;
@@ -334,7 +334,7 @@ void main() {
334
334
  void main() {
335
335
  gl_FragColor = texture2D(u_texture, v_uv);
336
336
  }
337
- `,a=xf(t,t.VERTEX_SHADER,s),c=xf(t,t.FRAGMENT_SHADER,o),l=qR(t,a,c),d={texture:t.getUniformLocation(l,"u_texture"),position:t.getAttribLocation(l,"position")};return{framebuffer:i,texture:r,program:l,uniforms:d}}function tXe(t,e,n,r,i,s){return t.useProgram(n.program),t.bindFramebuffer(t.FRAMEBUFFER,n.framebuffer),t.viewport(0,0,i,s),t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n.uniforms.position),t.vertexAttribPointer(n.uniforms.position,2,t.FLOAT,!1,0,0),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(n.uniforms.texture,0),t.drawArrays(t.TRIANGLES,0,6),t.bindFramebuffer(t.FRAMEBUFFER,null),n.texture}var IW=t=>{const e=t.getContext("webgl2",{antialias:!0,premultipliedAlpha:!0});let n=null,r=8;const i=4;if(!e){console.error("Failed to create WebGL context");return}e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA);const s=ZYe(e),o=s.program,a=s.attribLocations.position,{mask:c,frame:l,background:d}=s.uniformLocations,h=YYe(e),m=h.program,g=h.uniforms,y=JYe(e),v=y.program,w=y.uniforms,S=Eh(e,0),R=Eh(e,1),x=KYe(e);if(!x)throw new Error("Failed to create vertex buffer");let T=[],I=[],k=[],A=0,O=1;T.push(Eh(e,3)),T.push(Eh(e,4));const D=Math.floor(t.width/i),N=Math.floor(t.height/i),U=eXe(e,D,N);I.push(J1(e,T[0],D,N)),I.push(J1(e,T[1],D,N));const $=Eh(e,5),K=J1(e,$,t.width,t.height);k.push(Eh(e,6)),k.push(Eh(e,7));const Y=[J1(e,k[0],t.width,t.height),J1(e,k[1],t.width,t.height)];e.useProgram(o),e.uniform1i(d,0),e.uniform1i(l,1),e.uniform1i(c,2);let G=Qx();function F(X){if(X.codedWidth===0||k.length===0)return;const ne=X.displayWidth,fe=X.displayHeight;e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,R),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,X);let ye=S;if(n){const Ae=tXe(e,R,U,x,D,N);ye=RW(e,Ae,D,N,n,m,g,x,I,T)}else e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,S),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,G),ye=S;e.viewport(0,0,ne,fe),e.clearColor(1,1,1,1),e.clear(e.COLOR_BUFFER_BIT),e.useProgram(o),e.bindBuffer(e.ARRAY_BUFFER,x),e.vertexAttribPointer(a,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(a),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,ye),e.uniform1i(d,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,R),e.uniform1i(l,1),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,k[A]),e.uniform1i(c,2),e.drawArrays(e.TRIANGLES,0,6)}async function q(X){if(G=Qx(),X)try{G=await zYe(X,t.width,t.height)}catch(ne){console.error("Error processing background image, falling back to black background:",ne)}e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,S),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,G)}function z(X){n=X?Math.max(1,Math.floor(X/i)):null,q(null)}function W(X){const ne=[K,Y[O]],fe=[$,k[O]];RW(e,X,t.width,t.height,r,v,w,x,ne,fe),A=O,O=1-O}function V(){e.deleteProgram(o),e.deleteProgram(m),e.deleteProgram(v),e.deleteTexture(S),e.deleteTexture(R),e.deleteTexture($),e.deleteFramebuffer(K);for(const X of T)e.deleteTexture(X);for(const X of I)e.deleteFramebuffer(X);for(const X of k)e.deleteTexture(X);for(const X of Y)e.deleteFramebuffer(X);e.deleteBuffer(x),U&&(e.deleteTexture(U.texture),e.deleteFramebuffer(U.framebuffer),e.deleteProgram(U.program)),G&&(G instanceof ImageBitmap&&G.close(),G=Qx()),T=[],I=[],k=[]}return{renderFrame:F,updateMask:W,setBackgroundImage:q,setBlurRadius:z,cleanup:V}},yfe=class{constructor(){this.isDisabled=!1}async init({outputCanvas:t,inputElement:e}){if(!(e instanceof HTMLVideoElement))throw TypeError("Video transformer needs a HTMLVideoElement as input");this.transformer=new TransformStream({transform:(n,r)=>this.transform(n,r)}),this.canvas=t||null,t&&(this.gl=IW(this.canvas||x3(e.videoWidth,e.videoHeight))),this.inputVideo=e,this.isDisabled=!1}async restart({outputCanvas:t,inputElement:e}){var n;this.canvas=t||null,(n=this.gl)==null||n.cleanup(),this.gl=IW(this.canvas||x3(e.videoWidth,e.videoHeight)),this.inputVideo=e,this.isDisabled=!1}async destroy(){var t;this.isDisabled=!0,this.canvas=void 0,(t=this.gl)==null||t.cleanup(),this.gl=void 0}},bfe=class extends yfe{constructor(t){super(),this.backgroundImage=null,this.segmentationTimeMs=0,this.options=t,this.update(t)}static get isSupported(){return typeof OffscreenCanvas<"u"&&typeof VideoFrame<"u"&&typeof createImageBitmap<"u"&&!!document.createElement("canvas").getContext("webgl2")}async init({outputCanvas:t,inputElement:e}){var n,r,i,s,o,a;await super.init({outputCanvas:t,inputElement:e});const c=await Ph.forVisionTasks((r=(n=this.options.assetPaths)==null?void 0:n.tasksVisionFileSet)!=null?r:`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${GYe["@mediapipe/tasks-vision"]}/wasm`);this.imageSegmenter=await Xi.createFromOptions(c,{baseOptions:{modelAssetPath:(s=(i=this.options.assetPaths)==null?void 0:i.modelAssetPath)!=null?s:"https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite",delegate:"GPU",...this.options.segmenterOptions},canvas:this.canvas,runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!1}),(o=this.options)!=null&&o.imagePath&&!this.backgroundImage&&await this.loadBackground(this.options.imagePath).catch(l=>console.error("Error while loading processor background image: ",l)),this.options.blurRadius&&((a=this.gl)==null||a.setBlurRadius(this.options.blurRadius))}async destroy(){var t;await super.destroy(),await((t=this.imageSegmenter)==null?void 0:t.close()),this.backgroundImage=null}async loadBackground(t){var e;const n=new Image;await new Promise((i,s)=>{n.crossOrigin="Anonymous",n.onload=()=>i(n),n.onerror=o=>s(o),n.src=t});const r=await createImageBitmap(n);(e=this.gl)==null||e.setBackgroundImage(r)}async transform(t,e){var n,r;try{if(!(t instanceof VideoFrame)||t.codedWidth===0||t.codedHeight===0){console.debug("empty frame detected, ignoring");return}if(this.isDisabled){e.enqueue(t);return}const i=Date.now();if(!this.canvas)throw TypeError("Canvas needs to be initialized first");this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight;const s=new Promise((a,c)=>{var l;try{let d=performance.now();(l=this.imageSegmenter)==null||l.segmentForVideo(t,d,h=>{this.segmentationTimeMs=performance.now()-d,this.segmentationResults=h,this.updateMask(h.categoryMask),h.close(),a()})}catch(d){c(d)}}),o=performance.now();if(this.drawFrame(t),this.canvas&&this.canvas.width>0&&this.canvas.height>0){const a=new VideoFrame(this.canvas,{timestamp:t.timestamp||i});e.enqueue(a);const c=performance.now()-o,l={processingTimeMs:this.segmentationTimeMs+c,segmentationTimeMs:this.segmentationTimeMs,filterTimeMs:c};(r=(n=this.options).onFrameProcessed)==null||r.call(n,l)}else e.enqueue(t);await s}catch(i){console.error("Error while processing frame: ",i)}finally{t.close()}}async update(t){var e;this.options={...this.options,...t},t.blurRadius?(e=this.gl)==null||e.setBlurRadius(t.blurRadius):t.imagePath&&await this.loadBackground(t.imagePath)}async drawFrame(t){var e;this.gl&&((e=this.gl)==null||e.renderFrame(t))}async updateMask(t){var e;t&&((e=this.gl)==null||e.updateMask(t.getAsWebGLTexture()))}},nXe=()=>bfe.isSupported&&gfe.isSupported;const rXe=""+new URL("selfie_segmenter-DF05sdL4.tflite",import.meta.url).href,iXe={wasmLoaderPath:new URL(""+new URL("vision_wasm_internal-CEyeacG0.js",import.meta.url).href,import.meta.url).href,wasmBinaryPath:new URL(""+new URL("vision_wasm_internal-TmjHuG4I.wasm",import.meta.url).href,import.meta.url).href};class sXe extends bfe{async init({outputCanvas:e,inputElement:n}){await yfe.prototype.init.call(this,{outputCanvas:e,inputElement:n}),this.imageSegmenter=await Xi.createFromOptions(iXe,{baseOptions:{modelAssetPath:rXe,delegate:"GPU",...this.options.segmenterOptions},canvas:this.canvas,runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!1}),this.options.blurRadius&&this.gl?.setBlurRadius(this.options.blurRadius)}}const _fe=_.createContext(void 0);function GR(){const t=_.use(_fe);if(t===void 0)throw new Error("useTrackProcessor must be used within a ProcessorProvider");return t}const Sfe=t=>{const{processor:e}=GR();_.useEffect(()=>{t&&(e&&!t.getProcessor()&&t.setProcessor(e),!e&&t.getProcessor()&&t.stopProcessor())},[e,t])},oXe=({children:t})=>{const[e]=Gn(xle),n=_.useMemo(()=>nXe(),[]),r=_.useMemo(()=>new gfe(new sXe({blurRadius:15}),"background-blur"),[]),i=_.useMemo(()=>({supported:n,processor:n&&e?r:void 0}),[n,e,r]);return E.jsx(_fe,{value:i,children:t})},aXe={},cXe={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_VERSION:"embedded-v0.16.2",VITE_PACKAGE:"embedded"},lXe=({client:t,livekitRoom:e})=>{const{t:n}=We(),[r,i]=Gn(Ile),[s,o]=Gn(B8),[a,c]=Gn(kle),[l,d]=Gn(Gb),[h,m]=Gn(Ole),[g,y]=Gn(Dle),[v,w]=Gn(V8),[S,R]=Gn(Mle),x=no(),T=_.useMemo(()=>{if(e?.engine.client.ws?.url){const I=new URL(e.engine.client.ws.url);return I.search="",I}return null},[e]);return E.jsxs(E.Fragment,{children:[E.jsx("p",{children:n("developer_mode.hostname",{hostname:window.location.hostname||"unknown"})}),E.jsx("p",{children:n("version",{productName:"Element Call",version:"embedded-v0.16.2"})}),E.jsx("p",{children:n("developer_mode.crypto_version",{version:t.getCrypto()?.getVersion()||"unknown"})}),E.jsx("p",{children:n("developer_mode.matrix_id",{id:t.getUserId()||"unknown"})}),E.jsx("p",{children:n("developer_mode.device_id",{id:t.getDeviceId()||"unknown"})}),E.jsx(yt,{children:E.jsx(Tn,{id:"duplicateTiles",type:"number",label:n("developer_mode.duplicate_tiles_label"),value:r.toString(),min:0,onChange:_.useCallback(I=>{const k=I.target.valueAsNumber;k<0||i(Number.isNaN(k)?0:k)},[i])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"debugTileLayout",type:"checkbox",checked:s,label:n("developer_mode.debug_tile_layout_label"),onChange:I=>o(I.target.checked)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"showNonMemberTiles",type:"checkbox",label:n("developer_mode.show_non_member_tiles"),checked:!!a,onChange:_.useCallback(I=>{c(I.target.checked)},[c])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"showConnectionStats",type:"checkbox",label:n("developer_mode.show_connection_stats"),checked:!!l,onChange:_.useCallback(I=>{d(I.target.checked)},[d])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"useNewMembershipManager",type:"checkbox",label:n("developer_mode.use_new_membership_manager"),checked:!!h,onChange:_.useCallback(I=>{m(I.target.checked)},[m])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"useToDeviceKeyTransport",type:"checkbox",label:n("developer_mode.use_to_device_key_transport"),checked:!!v,onChange:_.useCallback(I=>{w(I.target.checked)},[w])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"muteAllAudio",type:"checkbox",label:n("developer_mode.mute_all_audio"),checked:S,onChange:_.useCallback(I=>{R(I.target.checked)},[R])})})," ",E.jsxs(yt,{children:[E.jsx(Tn,{id:"alwaysShowIphoneEarpiece",type:"checkbox",label:n("developer_mode.always_show_iphone_earpiece"),checked:g,onChange:_.useCallback(I=>{y(I.target.checked)},[y])})," "]}),e?E.jsxs(E.Fragment,{children:[E.jsx("p",{children:n("developer_mode.livekit_sfu",{url:T?.href||"unknown"})}),E.jsx("p",{children:n("developer_mode.livekit_server_info")}),E.jsxs("pre",{className:aXe.pre,children:[e.serverInfo?JSON.stringify(e.serverInfo,null,2):"undefined",e.metadata]})]}):null,E.jsx("p",{children:n("developer_mode.environment_variables")}),E.jsx("pre",{children:JSON.stringify(cXe,null,2)}),E.jsx("p",{children:n("developer_mode.url_params")}),E.jsx("pre",{children:JSON.stringify(x,null,2)})]})},lD="audio",uD=({open:t,onDismiss:e,tab:n,onTabChange:r,client:i,roomId:s,livekitRoom:o})=>{const{t:a}=We(),c=()=>{const{supported:D}=GR(),[N,U]=Gn(xle);return E.jsxs(E.Fragment,{children:[E.jsx("h4",{children:a("settings.background_blur_header")}),E.jsx(yt,{children:E.jsx(Tn,{id:"activateBackgroundBlur",label:a("settings.background_blur_label"),description:D?"":a("settings.blur_not_supported_by_browser"),type:"checkbox",checked:!!N,onChange:$=>U($.target.checked),disabled:!D})})]})},l=Wu();_.useEffect(()=>{t&&l.requestDeviceNames()},[t,l]);const[d,h]=Gn(Lle),[m,g]=_.useState(d),[y]=Gn($8),{available:v}=hR(),{controlledAudioDevices:w}=no(),S=Qe(tue),R={key:"audio",name:a("common.audio"),content:E.jsx(E.Fragment,{children:E.jsxs(zq,{children:[!w&&E.jsx(Ux,{device:l.audioInput,title:a("settings.devices.microphone"),numberedLabel:D=>a("settings.devices.microphone_numbered",{n:D})}),S&&w&&E.jsx(Bt,{onClick:D=>{D.preventDefault(),window.controls.showNativeAudioDevicePicker?.(),window.controls.showNativeOutputDevicePicker?.()},children:a("settings.devices.change_device_button")}),E.jsx(Ux,{device:l.audioOutput,title:a("settings.devices.speaker"),numberedLabel:D=>a("settings.devices.speaker_numbered",{n:D})}),E.jsxs("div",{className:rz.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(Eue,{label:a("video_tile.volume"),value:m,onValueChange:g,onValueCommit:h,min:0,max:1,step:.01})]})]})})},x={key:"video",name:a("common.video"),content:E.jsxs(E.Fragment,{children:[E.jsx(zq,{children:E.jsx(Ux,{device:l.videoInput,title:a("settings.devices.camera"),numberedLabel:D=>a("settings.devices.camera_numbered",{n:D})})}),E.jsx(QM,{}),E.jsx(c,{})]})},T={key:"preferences",name:a("common.preferences"),content:E.jsx(kze,{})},I={key:"profile",name:a("common.profile"),content:E.jsx(WKe,{client:i})},k={key:"feedback",name:a("settings.feedback_tab_title"),content:E.jsx(XKe,{roomId:s})},A={key:"developer",name:a("settings.developer_tab_title"),content:E.jsx(lXe,{client:i,livekitRoom:o})},O=[R,x];return ut===null&&O.push(I),O.push(T),v&&O.push(k),y&&O.push(A),E.jsx(Up,{title:a("common.settings"),className:rz.settingsModal,open:t,onDismiss:e,tabbed:!0,children:E.jsx(RKe,{label:a("common.settings"),tab:n,onTabChange:r,tabs:O})})},uXe=(t,e)=>_.createElement("svg",{width:22,height:22,viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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)"})),kW=_.forwardRef(uXe),dXe=(t,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),fXe=_.forwardRef(dXe),hXe=(t,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),pXe=_.forwardRef(hXe),mXe=(t,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),gXe=_.forwardRef(mXe),vXe="_userButton_t5z8t_15",yXe={userButton:vXe},bXe=({preventNavigation:t,isAuthenticated:e,isPasswordlessUser:n,userId:r,displayName:i,avatarUrl:s,onAction:o})=>{const{t:a}=We(),c=rs(),l=_.useMemo(()=>{const m=[];return e&&(m.push({key:"user",icon:kW,label:i,dataTestid:"usermenu_user"}),m.push({key:"settings",icon:fXe,label:a("common.settings")}),n&&!t&&m.push({key:"login",label:a("action.sign_in"),icon:pXe,dataTestid:"usermenu_login"}),!n&&!t&&m.push({key:"logout",label:a("action.sign_out"),icon:gXe,dataTestid:"usermenu_logout"})),m},[e,n,i,t,a]),[d,h]=_.useState(!1);return e?E.jsx(qM,{title:a("a11y.user_menu"),showTitle:!1,align:"end",open:d,onOpenChange:h,trigger:E.jsx("button",{"aria-label":a("common.profile"),className:yXe.userButton,"data-testid":"usermenu_open",children:e&&(!n||s)?E.jsx(Op,{id:r,name:i,size:Lp.SM,src:s}):E.jsx(kW,{})}),children:l.map(({key:m,icon:g,label:y,dataTestid:v})=>E.jsx(yv,{Icon:g,label:y,"data-testid":v,onSelect:()=>o(m)},m))}):E.jsx(q8,{to:{pathname:"/login"},state:{from:c},children:a("log_in")})},dD=({preventNavigation:t=!1})=>{const e=rs(),n=hl(),{client:r,logout:i,authenticated:s,passwordlessUser:o}=W8(),{displayName:a,avatarUrl:c}=V_(r),[l,d]=_.useState(!1),h=_.useCallback(()=>d(!1),[d]),[m,g]=_.useState(lD),y=_.useCallback(w=>{switch(w){case"user":g("profile"),d(!0);break;case"settings":g("audio"),d(!0);break;case"logout":i?.();break;case"login":n("/login",{state:{from:e}})?.catch(S=>M.error("Failed to navigate to login",S));break}},[n,e,i,d]),v=r?.getUserIdLocalpart()??"";return E.jsxs(E.Fragment,{children:[E.jsx(bXe,{preventNavigation:t,isAuthenticated:s,isPasswordlessUser:o,avatarUrl:c,onAction:y,userId:r?.getUserId()??"",displayName:a||(v?v.replace("@",""):"")}),r&&E.jsx(uD,{client:r,open:l,onDismiss:h,tab:m,onTabChange:g})]})};function _Xe(t){return new Worker(""+new URL("IndexedDBWorker-DiQk_BNn.js",import.meta.url).href,{name:t?.name})}const Efe=new On;function SXe(t){const e=gp(Efe,t,_.useCallback(()=>localStorage.getItem(t),[t])),n=_.useCallback(r=>wfe(t,r),[t]);return[e,n]}const wfe=(t,e)=>{localStorage.setItem(t,e),Efe.emit(t)};function Cfe(t,e){localStorage.getItem(Qb(t))!==e&&wfe(Qb(t),e)}const Qb=t=>`room-shared-key-${t}`,EXe=(t,e)=>{const[n,r]=SXe(Qb(t));return _.useEffect(()=>{e&&r(e)},[e,r]),[e??n,r]};function Tfe(t){const{roomId:e,password:n}=Br();return t!==e&&M.warn("requested key for a roomId which is not the current call room id (from the URL)",t,e),n??localStorage.getItem(Qb(t))}function X_(t){const{client:e}=jp(),[n]=EXe(Qb(t),Tfe(t)??void 0),r=e?.getRoom(t);return _.useMemo(()=>r?n?{kind:hn.SHARED_KEY,secret:n}:r.hasEncryptionStateEvent()?{kind:hn.PER_PARTICIPANT}:{kind:hn.NONE}:{kind:hn.NONE},[r,n])}const xW=!1,wXe="element-call-sync";async function CXe(t){let e=!!await t.store.getSavedSyncToken();return new Promise((n,r)=>{const i=(s,o,a)=>{s==="PREPARED"?e?e=!1:(t.removeListener(Le.Sync,i),n()):s==="ERROR"&&(t.removeListener(Le.Sync,i),r(a?.error))};t.on(Le.Sync,i)})}async function Rfe(t,e){let n;try{n=window.indexedDB}catch(a){M.warn("Could not get indexDB from window.",a)}const r={fallbackICEServerAllowed:xW,isVoipWithNoMediaAllowed:sn.get().features?.feature_group_calls_without_video_and_audio};n&&localStorage?r.store=new LQ({indexedDB:window.indexedDB,localStorage,dbName:wXe,workerFactory:()=>new _Xe}):localStorage&&(r.store=new vb({localStorage}));const{e2eEnabled:i}=Br();i||M.info("Disabling E2E: group call signalling will NOT be encrypted.");const s=aT({...r,...t,useAuthorizationHeader:!0,localTimeoutMs:5e3,useE2eForGroupCall:i,fallbackICEServerAllowed:xW});e||await s.clearStores();try{await s.store.startup()}catch(a){M.error("Error starting matrix client indexDB store. Falling back to memory store.",a),s.store=new vb({localStorage}),await s.store.startup()}try{await s.initRustCrypto()}catch(a){M.warn(a,"Make sure to clear client stores before initializing the rust crypto.")}const o=CXe(s);return await s.startClient({clientWellKnownPollPeriod:60*10}),await o,s}function J_(t){return t.trim().replace(/\s/g,"-").replace(/[^\w-]/g,"").toLowerCase()}function TXe(t,e){return`#${J_(t)}:${e.getDomain()}`}function Ife(t){const e=t.split(":",2);if(e.length===2&&e[0][0]==="#"){if(e[1]===sn.defaultServerName())return e[0];throw new Error("Unsupported remote room alias")}return t}async function kfe(t,e,n){M.log("Creating room for group call");const r=t.createRoom({visibility:GJ.Private,preset:nT.PublicChat,name:e,room_alias_name:n?void 0:J_(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:{[t.getUserId()]:100}}}),i=await new Promise((o,a)=>{r.catch(d=>{a(d),l()});const c=d=>{r.then(h=>{d.roomId===h.room_id&&(o(d.roomId),l())},h=>{M.error("Failed to wait for the room to arrive",h)})},l=()=>{t.off(Le.Room,c)};t.on(Le.Room,c)});let s;return n==hn.SHARED_KEY&&(s=BJ(16),Cfe(i,s)),{roomId:i,alias:n?void 0:TXe(e,t),password:s}}function xfe(t,e,n,r){return`${window.location.protocol}//${window.location.host}${KR(t,e,n)}`}function KR(t,e,n,r){return`/room/#${n?"/"+J_(n):""}?${Tje(t,e).toString()}`}async function RXe(t){let e=0;for(;;)try{return await t()}catch(n){e++;const r=GO(n,e,!0);if(r<0)throw n;await _p(r)}}const fD=t=>{const[e,n]=_.useState(void 0),[r,i]=_.useState(void 0),s=_.useRef(void 0);s.current||(s.current=aT({baseUrl:sn.defaultHomeserverUrl()})),_.useEffect(()=>{ut||s.current.registerRequest({}).catch(a=>{n(a.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url),i(a.data?.params["m.login.recaptcha"]?.public_key)})},[]);const o=_.useCallback(async(a,c,l,d,h)=>{const m=new l7({matrixClient:s.current,doRequest:async x=>s.current.registerRequest({username:a,password:c,auth:x||void 0}),stateUpdated:(x,T)=>{if(T.error)throw new Error(T.error);x==="m.login.terms"?m.submitAuthDict({type:"m.login.terms"}).catch(I=>{M.error(I)}):x==="m.login.recaptcha"&&m.submitAuthDict({type:"m.login.recaptcha",response:d}).catch(I=>{M.error(I)})},requestEmailToken:async()=>Promise.resolve({sid:"dummy"})}),{user_id:g,access_token:y,device_id:v}=await m.attemptAuth();await t?.logout(!0);const w=await Rfe({baseUrl:sn.defaultHomeserverUrl(),accessToken:y,userId:g,deviceId:v},!1);await w.setDisplayName(l);const S={user_id:g,device_id:v,access_token:y,passwordlessUser:h};h&&(S.tempPassword=c);const R=w.getUser(w.getUserId());return R.setRawDisplayName(l),R.setDisplayName(l),[w,S]},[t]);return{privacyPolicyUrl:e,recaptchaKey:r,register:o}},IXe="_buttons_1arp2_8",kXe={buttons:IXe},Afe=({onJoin:t,open:e,onDismiss:n})=>{const{t:r}=We();return E.jsxs(Up,{title:r("join_existing_call_modal.title"),open:e,onDismiss:n,children:[E.jsx("p",{children:r("join_existing_call_modal.text")}),E.jsxs(yt,{rightAlign:!0,className:kXe.buttons,children:[E.jsx(Bt,{onClick:n,children:r("action.no")}),E.jsx(Bt,{onClick:t,"data-testid":"home_joinExistingRoom",children:r("join_existing_call_modal.join_button")})]})]})},AW="https://www.recaptcha.net/recaptcha/api.js?onload=mxOnRecaptchaLoaded&render=explicit";function hD(t){const{t:e}=We(),[n]=_.useState(()=>To(16)),r=_.useRef(void 0);_.useEffect(()=>{if(!t)return;const o=()=>{document.getElementById(n)&&window.grecaptcha.render(n,{sitekey:t,size:"invisible",callback:a=>r.current?.resolve(a),"error-callback":()=>r.current?.reject(new Error)})};if(typeof window.grecaptcha?.render=="function")o();else if(window.mxOnRecaptchaLoaded=o,!document.querySelector(`script[src="${AW}"]`)){const a=document.createElement("script");a.src=AW,a.async=!0,document.body.appendChild(a)}},[n,t]);const i=_.useCallback(async()=>t?window.grecaptcha?new Promise((o,a)=>{const c=new MutationObserver(d=>{for(const h of d)if(h.target?.style?.visibility!=="visible"){a(sz("recaptcha_dismissed",e)),c.disconnect();return}});r.current={resolve:d=>{o(d),c.disconnect()},reject:d=>{a(d),c.disconnect()}},window.grecaptcha.execute().then(()=>{},d=>{M.error("Recaptcha execution failed",d)});const l=document.querySelector('iframe[src*="recaptcha/api2/bframe"]');l?.parentNode?.parentNode&&c.observe(l?.parentNode?.parentNode,{attributes:!0})}):(M.log("Recaptcha not loaded"),Promise.reject(sz("recaptcha_not_loaded",e))):Promise.resolve(""),[t,e]),s=_.useCallback(()=>{window.grecaptcha?.reset()},[]);return{execute:i,reset:s,recaptchaId:n}}const xXe="_form_jcuzc_8",AXe={form:xXe},zR=({ref:t,children:e,className:n,onSubmit:r})=>E.jsx("form",{onSubmit:r,className:Oe(AXe.form,n),ref:t,children:e});zR.displayName="Form";const PXe="_footer_106jg_8",LXe="_mobileLoginLink_106jg_19",OXe="_form_106jg_24",MXe="_notice_106jg_40",Q1={footer:PXe,mobileLoginLink:LXe,form:OXe,notice:MXe},DXe="_container_dwllg_8",NXe="_main_dwllg_15",UXe="_logo_dwllg_23",Xg={container:DXe,main:NXe,logo:UXe},PW=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};class jXe{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:n,separator:r,dictionaries:i,style:s,seed:o}=e;this.dictionaries=i,this.separator=r,this.length=n,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.
337
+ `,a=xf(t,t.VERTEX_SHADER,s),c=xf(t,t.FRAGMENT_SHADER,o),l=qR(t,a,c),d={texture:t.getUniformLocation(l,"u_texture"),position:t.getAttribLocation(l,"position")};return{framebuffer:i,texture:r,program:l,uniforms:d}}function tXe(t,e,n,r,i,s){return t.useProgram(n.program),t.bindFramebuffer(t.FRAMEBUFFER,n.framebuffer),t.viewport(0,0,i,s),t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n.uniforms.position),t.vertexAttribPointer(n.uniforms.position,2,t.FLOAT,!1,0,0),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,e),t.uniform1i(n.uniforms.texture,0),t.drawArrays(t.TRIANGLES,0,6),t.bindFramebuffer(t.FRAMEBUFFER,null),n.texture}var IW=t=>{const e=t.getContext("webgl2",{antialias:!0,premultipliedAlpha:!0});let n=null,r=8;const i=4;if(!e){console.error("Failed to create WebGL context");return}e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA);const s=ZYe(e),o=s.program,a=s.attribLocations.position,{mask:c,frame:l,background:d}=s.uniformLocations,h=YYe(e),m=h.program,g=h.uniforms,y=JYe(e),v=y.program,w=y.uniforms,S=Eh(e,0),R=Eh(e,1),x=KYe(e);if(!x)throw new Error("Failed to create vertex buffer");let T=[],I=[],k=[],A=0,O=1;T.push(Eh(e,3)),T.push(Eh(e,4));const D=Math.floor(t.width/i),N=Math.floor(t.height/i),U=eXe(e,D,N);I.push(J1(e,T[0],D,N)),I.push(J1(e,T[1],D,N));const $=Eh(e,5),K=J1(e,$,t.width,t.height);k.push(Eh(e,6)),k.push(Eh(e,7));const Y=[J1(e,k[0],t.width,t.height),J1(e,k[1],t.width,t.height)];e.useProgram(o),e.uniform1i(d,0),e.uniform1i(l,1),e.uniform1i(c,2);let G=Qx();function F(X){if(X.codedWidth===0||k.length===0)return;const ne=X.displayWidth,fe=X.displayHeight;e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,R),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,X);let ye=S;if(n){const Ae=tXe(e,R,U,x,D,N);ye=RW(e,Ae,D,N,n,m,g,x,I,T)}else e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,S),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,G),ye=S;e.viewport(0,0,ne,fe),e.clearColor(1,1,1,1),e.clear(e.COLOR_BUFFER_BIT),e.useProgram(o),e.bindBuffer(e.ARRAY_BUFFER,x),e.vertexAttribPointer(a,2,e.FLOAT,!1,0,0),e.enableVertexAttribArray(a),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,ye),e.uniform1i(d,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,R),e.uniform1i(l,1),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,k[A]),e.uniform1i(c,2),e.drawArrays(e.TRIANGLES,0,6)}async function q(X){if(G=Qx(),X)try{G=await zYe(X,t.width,t.height)}catch(ne){console.error("Error processing background image, falling back to black background:",ne)}e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,S),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,G)}function z(X){n=X?Math.max(1,Math.floor(X/i)):null,q(null)}function W(X){const ne=[K,Y[O]],fe=[$,k[O]];RW(e,X,t.width,t.height,r,v,w,x,ne,fe),A=O,O=1-O}function V(){e.deleteProgram(o),e.deleteProgram(m),e.deleteProgram(v),e.deleteTexture(S),e.deleteTexture(R),e.deleteTexture($),e.deleteFramebuffer(K);for(const X of T)e.deleteTexture(X);for(const X of I)e.deleteFramebuffer(X);for(const X of k)e.deleteTexture(X);for(const X of Y)e.deleteFramebuffer(X);e.deleteBuffer(x),U&&(e.deleteTexture(U.texture),e.deleteFramebuffer(U.framebuffer),e.deleteProgram(U.program)),G&&(G instanceof ImageBitmap&&G.close(),G=Qx()),T=[],I=[],k=[]}return{renderFrame:F,updateMask:W,setBackgroundImage:q,setBlurRadius:z,cleanup:V}},yfe=class{constructor(){this.isDisabled=!1}async init({outputCanvas:t,inputElement:e}){if(!(e instanceof HTMLVideoElement))throw TypeError("Video transformer needs a HTMLVideoElement as input");this.transformer=new TransformStream({transform:(n,r)=>this.transform(n,r)}),this.canvas=t||null,t&&(this.gl=IW(this.canvas||x3(e.videoWidth,e.videoHeight))),this.inputVideo=e,this.isDisabled=!1}async restart({outputCanvas:t,inputElement:e}){var n;this.canvas=t||null,(n=this.gl)==null||n.cleanup(),this.gl=IW(this.canvas||x3(e.videoWidth,e.videoHeight)),this.inputVideo=e,this.isDisabled=!1}async destroy(){var t;this.isDisabled=!0,this.canvas=void 0,(t=this.gl)==null||t.cleanup(),this.gl=void 0}},bfe=class extends yfe{constructor(t){super(),this.backgroundImage=null,this.segmentationTimeMs=0,this.options=t,this.update(t)}static get isSupported(){return typeof OffscreenCanvas<"u"&&typeof VideoFrame<"u"&&typeof createImageBitmap<"u"&&!!document.createElement("canvas").getContext("webgl2")}async init({outputCanvas:t,inputElement:e}){var n,r,i,s,o,a;await super.init({outputCanvas:t,inputElement:e});const c=await Ph.forVisionTasks((r=(n=this.options.assetPaths)==null?void 0:n.tasksVisionFileSet)!=null?r:`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${GYe["@mediapipe/tasks-vision"]}/wasm`);this.imageSegmenter=await Xi.createFromOptions(c,{baseOptions:{modelAssetPath:(s=(i=this.options.assetPaths)==null?void 0:i.modelAssetPath)!=null?s:"https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite",delegate:"GPU",...this.options.segmenterOptions},canvas:this.canvas,runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!1}),(o=this.options)!=null&&o.imagePath&&!this.backgroundImage&&await this.loadBackground(this.options.imagePath).catch(l=>console.error("Error while loading processor background image: ",l)),this.options.blurRadius&&((a=this.gl)==null||a.setBlurRadius(this.options.blurRadius))}async destroy(){var t;await super.destroy(),await((t=this.imageSegmenter)==null?void 0:t.close()),this.backgroundImage=null}async loadBackground(t){var e;const n=new Image;await new Promise((i,s)=>{n.crossOrigin="Anonymous",n.onload=()=>i(n),n.onerror=o=>s(o),n.src=t});const r=await createImageBitmap(n);(e=this.gl)==null||e.setBackgroundImage(r)}async transform(t,e){var n,r;try{if(!(t instanceof VideoFrame)||t.codedWidth===0||t.codedHeight===0){console.debug("empty frame detected, ignoring");return}if(this.isDisabled){e.enqueue(t);return}const i=Date.now();if(!this.canvas)throw TypeError("Canvas needs to be initialized first");this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight;const s=new Promise((a,c)=>{var l;try{let d=performance.now();(l=this.imageSegmenter)==null||l.segmentForVideo(t,d,h=>{this.segmentationTimeMs=performance.now()-d,this.segmentationResults=h,this.updateMask(h.categoryMask),h.close(),a()})}catch(d){c(d)}}),o=performance.now();if(this.drawFrame(t),this.canvas&&this.canvas.width>0&&this.canvas.height>0){const a=new VideoFrame(this.canvas,{timestamp:t.timestamp||i});e.enqueue(a);const c=performance.now()-o,l={processingTimeMs:this.segmentationTimeMs+c,segmentationTimeMs:this.segmentationTimeMs,filterTimeMs:c};(r=(n=this.options).onFrameProcessed)==null||r.call(n,l)}else e.enqueue(t);await s}catch(i){console.error("Error while processing frame: ",i)}finally{t.close()}}async update(t){var e;this.options={...this.options,...t},t.blurRadius?(e=this.gl)==null||e.setBlurRadius(t.blurRadius):t.imagePath&&await this.loadBackground(t.imagePath)}async drawFrame(t){var e;this.gl&&((e=this.gl)==null||e.renderFrame(t))}async updateMask(t){var e;t&&((e=this.gl)==null||e.updateMask(t.getAsWebGLTexture()))}},nXe=()=>bfe.isSupported&&gfe.isSupported;const rXe=""+new URL("selfie_segmenter-DF05sdL4.tflite",import.meta.url).href,iXe={wasmLoaderPath:new URL(""+new URL("vision_wasm_internal-CEyeacG0.js",import.meta.url).href,import.meta.url).href,wasmBinaryPath:new URL(""+new URL("vision_wasm_internal-TmjHuG4I.wasm",import.meta.url).href,import.meta.url).href};class sXe extends bfe{async init({outputCanvas:e,inputElement:n}){await yfe.prototype.init.call(this,{outputCanvas:e,inputElement:n}),this.imageSegmenter=await Xi.createFromOptions(iXe,{baseOptions:{modelAssetPath:rXe,delegate:"GPU",...this.options.segmenterOptions},canvas:this.canvas,runningMode:"VIDEO",outputCategoryMask:!0,outputConfidenceMasks:!1}),this.options.blurRadius&&this.gl?.setBlurRadius(this.options.blurRadius)}}const _fe=_.createContext(void 0);function GR(){const t=_.use(_fe);if(t===void 0)throw new Error("useTrackProcessor must be used within a ProcessorProvider");return t}const Sfe=t=>{const{processor:e}=GR();_.useEffect(()=>{t&&(e&&!t.getProcessor()&&t.setProcessor(e),!e&&t.getProcessor()&&t.stopProcessor())},[e,t])},oXe=({children:t})=>{const[e]=Gn(xle),n=_.useMemo(()=>nXe(),[]),r=_.useMemo(()=>new gfe(new sXe({blurRadius:15}),"background-blur"),[]),i=_.useMemo(()=>({supported:n,processor:n&&e?r:void 0}),[n,e,r]);return E.jsx(_fe,{value:i,children:t})},aXe={},cXe={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_APP_VERSION:"embedded-v0.16.3",VITE_PACKAGE:"embedded"},lXe=({client:t,livekitRoom:e})=>{const{t:n}=We(),[r,i]=Gn(Ile),[s,o]=Gn(B8),[a,c]=Gn(kle),[l,d]=Gn(Gb),[h,m]=Gn(Ole),[g,y]=Gn(Dle),[v,w]=Gn(V8),[S,R]=Gn(Mle),x=no(),T=_.useMemo(()=>{if(e?.engine.client.ws?.url){const I=new URL(e.engine.client.ws.url);return I.search="",I}return null},[e]);return E.jsxs(E.Fragment,{children:[E.jsx("p",{children:n("developer_mode.hostname",{hostname:window.location.hostname||"unknown"})}),E.jsx("p",{children:n("version",{productName:"Element Call",version:"embedded-v0.16.3"})}),E.jsx("p",{children:n("developer_mode.crypto_version",{version:t.getCrypto()?.getVersion()||"unknown"})}),E.jsx("p",{children:n("developer_mode.matrix_id",{id:t.getUserId()||"unknown"})}),E.jsx("p",{children:n("developer_mode.device_id",{id:t.getDeviceId()||"unknown"})}),E.jsx(yt,{children:E.jsx(Tn,{id:"duplicateTiles",type:"number",label:n("developer_mode.duplicate_tiles_label"),value:r.toString(),min:0,onChange:_.useCallback(I=>{const k=I.target.valueAsNumber;k<0||i(Number.isNaN(k)?0:k)},[i])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"debugTileLayout",type:"checkbox",checked:s,label:n("developer_mode.debug_tile_layout_label"),onChange:I=>o(I.target.checked)})}),E.jsx(yt,{children:E.jsx(Tn,{id:"showNonMemberTiles",type:"checkbox",label:n("developer_mode.show_non_member_tiles"),checked:!!a,onChange:_.useCallback(I=>{c(I.target.checked)},[c])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"showConnectionStats",type:"checkbox",label:n("developer_mode.show_connection_stats"),checked:!!l,onChange:_.useCallback(I=>{d(I.target.checked)},[d])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"useNewMembershipManager",type:"checkbox",label:n("developer_mode.use_new_membership_manager"),checked:!!h,onChange:_.useCallback(I=>{m(I.target.checked)},[m])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"useToDeviceKeyTransport",type:"checkbox",label:n("developer_mode.use_to_device_key_transport"),checked:!!v,onChange:_.useCallback(I=>{w(I.target.checked)},[w])})}),E.jsx(yt,{children:E.jsx(Tn,{id:"muteAllAudio",type:"checkbox",label:n("developer_mode.mute_all_audio"),checked:S,onChange:_.useCallback(I=>{R(I.target.checked)},[R])})})," ",E.jsxs(yt,{children:[E.jsx(Tn,{id:"alwaysShowIphoneEarpiece",type:"checkbox",label:n("developer_mode.always_show_iphone_earpiece"),checked:g,onChange:_.useCallback(I=>{y(I.target.checked)},[y])})," "]}),e?E.jsxs(E.Fragment,{children:[E.jsx("p",{children:n("developer_mode.livekit_sfu",{url:T?.href||"unknown"})}),E.jsx("p",{children:n("developer_mode.livekit_server_info")}),E.jsxs("pre",{className:aXe.pre,children:[e.serverInfo?JSON.stringify(e.serverInfo,null,2):"undefined",e.metadata]})]}):null,E.jsx("p",{children:n("developer_mode.environment_variables")}),E.jsx("pre",{children:JSON.stringify(cXe,null,2)}),E.jsx("p",{children:n("developer_mode.url_params")}),E.jsx("pre",{children:JSON.stringify(x,null,2)})]})},lD="audio",uD=({open:t,onDismiss:e,tab:n,onTabChange:r,client:i,roomId:s,livekitRoom:o})=>{const{t:a}=We(),c=()=>{const{supported:D}=GR(),[N,U]=Gn(xle);return E.jsxs(E.Fragment,{children:[E.jsx("h4",{children:a("settings.background_blur_header")}),E.jsx(yt,{children:E.jsx(Tn,{id:"activateBackgroundBlur",label:a("settings.background_blur_label"),description:D?"":a("settings.blur_not_supported_by_browser"),type:"checkbox",checked:!!N,onChange:$=>U($.target.checked),disabled:!D})})]})},l=Wu();_.useEffect(()=>{t&&l.requestDeviceNames()},[t,l]);const[d,h]=Gn(Lle),[m,g]=_.useState(d),[y]=Gn($8),{available:v}=hR(),{controlledAudioDevices:w}=no(),S=Qe(tue),R={key:"audio",name:a("common.audio"),content:E.jsx(E.Fragment,{children:E.jsxs(zq,{children:[!w&&E.jsx(Ux,{device:l.audioInput,title:a("settings.devices.microphone"),numberedLabel:D=>a("settings.devices.microphone_numbered",{n:D})}),S&&w&&E.jsx(Bt,{onClick:D=>{D.preventDefault(),window.controls.showNativeAudioDevicePicker?.(),window.controls.showNativeOutputDevicePicker?.()},children:a("settings.devices.change_device_button")}),E.jsx(Ux,{device:l.audioOutput,title:a("settings.devices.speaker"),numberedLabel:D=>a("settings.devices.speaker_numbered",{n:D})}),E.jsxs("div",{className:rz.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(Eue,{label:a("video_tile.volume"),value:m,onValueChange:g,onValueCommit:h,min:0,max:1,step:.01})]})]})})},x={key:"video",name:a("common.video"),content:E.jsxs(E.Fragment,{children:[E.jsx(zq,{children:E.jsx(Ux,{device:l.videoInput,title:a("settings.devices.camera"),numberedLabel:D=>a("settings.devices.camera_numbered",{n:D})})}),E.jsx(QM,{}),E.jsx(c,{})]})},T={key:"preferences",name:a("common.preferences"),content:E.jsx(kze,{})},I={key:"profile",name:a("common.profile"),content:E.jsx(WKe,{client:i})},k={key:"feedback",name:a("settings.feedback_tab_title"),content:E.jsx(XKe,{roomId:s})},A={key:"developer",name:a("settings.developer_tab_title"),content:E.jsx(lXe,{client:i,livekitRoom:o})},O=[R,x];return ut===null&&O.push(I),O.push(T),v&&O.push(k),y&&O.push(A),E.jsx(Up,{title:a("common.settings"),className:rz.settingsModal,open:t,onDismiss:e,tabbed:!0,children:E.jsx(RKe,{label:a("common.settings"),tab:n,onTabChange:r,tabs:O})})},uXe=(t,e)=>_.createElement("svg",{width:22,height:22,viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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)"})),kW=_.forwardRef(uXe),dXe=(t,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),fXe=_.forwardRef(dXe),hXe=(t,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),pXe=_.forwardRef(hXe),mXe=(t,e)=>_.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),gXe=_.forwardRef(mXe),vXe="_userButton_t5z8t_15",yXe={userButton:vXe},bXe=({preventNavigation:t,isAuthenticated:e,isPasswordlessUser:n,userId:r,displayName:i,avatarUrl:s,onAction:o})=>{const{t:a}=We(),c=rs(),l=_.useMemo(()=>{const m=[];return e&&(m.push({key:"user",icon:kW,label:i,dataTestid:"usermenu_user"}),m.push({key:"settings",icon:fXe,label:a("common.settings")}),n&&!t&&m.push({key:"login",label:a("action.sign_in"),icon:pXe,dataTestid:"usermenu_login"}),!n&&!t&&m.push({key:"logout",label:a("action.sign_out"),icon:gXe,dataTestid:"usermenu_logout"})),m},[e,n,i,t,a]),[d,h]=_.useState(!1);return e?E.jsx(qM,{title:a("a11y.user_menu"),showTitle:!1,align:"end",open:d,onOpenChange:h,trigger:E.jsx("button",{"aria-label":a("common.profile"),className:yXe.userButton,"data-testid":"usermenu_open",children:e&&(!n||s)?E.jsx(Op,{id:r,name:i,size:Lp.SM,src:s}):E.jsx(kW,{})}),children:l.map(({key:m,icon:g,label:y,dataTestid:v})=>E.jsx(yv,{Icon:g,label:y,"data-testid":v,onSelect:()=>o(m)},m))}):E.jsx(q8,{to:{pathname:"/login"},state:{from:c},children:a("log_in")})},dD=({preventNavigation:t=!1})=>{const e=rs(),n=hl(),{client:r,logout:i,authenticated:s,passwordlessUser:o}=W8(),{displayName:a,avatarUrl:c}=V_(r),[l,d]=_.useState(!1),h=_.useCallback(()=>d(!1),[d]),[m,g]=_.useState(lD),y=_.useCallback(w=>{switch(w){case"user":g("profile"),d(!0);break;case"settings":g("audio"),d(!0);break;case"logout":i?.();break;case"login":n("/login",{state:{from:e}})?.catch(S=>M.error("Failed to navigate to login",S));break}},[n,e,i,d]),v=r?.getUserIdLocalpart()??"";return E.jsxs(E.Fragment,{children:[E.jsx(bXe,{preventNavigation:t,isAuthenticated:s,isPasswordlessUser:o,avatarUrl:c,onAction:y,userId:r?.getUserId()??"",displayName:a||(v?v.replace("@",""):"")}),r&&E.jsx(uD,{client:r,open:l,onDismiss:h,tab:m,onTabChange:g})]})};function _Xe(t){return new Worker(""+new URL("IndexedDBWorker-DiQk_BNn.js",import.meta.url).href,{name:t?.name})}const Efe=new On;function SXe(t){const e=gp(Efe,t,_.useCallback(()=>localStorage.getItem(t),[t])),n=_.useCallback(r=>wfe(t,r),[t]);return[e,n]}const wfe=(t,e)=>{localStorage.setItem(t,e),Efe.emit(t)};function Cfe(t,e){localStorage.getItem(Qb(t))!==e&&wfe(Qb(t),e)}const Qb=t=>`room-shared-key-${t}`,EXe=(t,e)=>{const[n,r]=SXe(Qb(t));return _.useEffect(()=>{e&&r(e)},[e,r]),[e??n,r]};function Tfe(t){const{roomId:e,password:n}=Br();return t!==e&&M.warn("requested key for a roomId which is not the current call room id (from the URL)",t,e),n??localStorage.getItem(Qb(t))}function X_(t){const{client:e}=jp(),[n]=EXe(Qb(t),Tfe(t)??void 0),r=e?.getRoom(t);return _.useMemo(()=>r?n?{kind:hn.SHARED_KEY,secret:n}:r.hasEncryptionStateEvent()?{kind:hn.PER_PARTICIPANT}:{kind:hn.NONE}:{kind:hn.NONE},[r,n])}const xW=!1,wXe="element-call-sync";async function CXe(t){let e=!!await t.store.getSavedSyncToken();return new Promise((n,r)=>{const i=(s,o,a)=>{s==="PREPARED"?e?e=!1:(t.removeListener(Le.Sync,i),n()):s==="ERROR"&&(t.removeListener(Le.Sync,i),r(a?.error))};t.on(Le.Sync,i)})}async function Rfe(t,e){let n;try{n=window.indexedDB}catch(a){M.warn("Could not get indexDB from window.",a)}const r={fallbackICEServerAllowed:xW,isVoipWithNoMediaAllowed:sn.get().features?.feature_group_calls_without_video_and_audio};n&&localStorage?r.store=new LQ({indexedDB:window.indexedDB,localStorage,dbName:wXe,workerFactory:()=>new _Xe}):localStorage&&(r.store=new vb({localStorage}));const{e2eEnabled:i}=Br();i||M.info("Disabling E2E: group call signalling will NOT be encrypted.");const s=aT({...r,...t,useAuthorizationHeader:!0,localTimeoutMs:5e3,useE2eForGroupCall:i,fallbackICEServerAllowed:xW});e||await s.clearStores();try{await s.store.startup()}catch(a){M.error("Error starting matrix client indexDB store. Falling back to memory store.",a),s.store=new vb({localStorage}),await s.store.startup()}try{await s.initRustCrypto()}catch(a){M.warn(a,"Make sure to clear client stores before initializing the rust crypto.")}const o=CXe(s);return await s.startClient({clientWellKnownPollPeriod:60*10}),await o,s}function J_(t){return t.trim().replace(/\s/g,"-").replace(/[^\w-]/g,"").toLowerCase()}function TXe(t,e){return`#${J_(t)}:${e.getDomain()}`}function Ife(t){const e=t.split(":",2);if(e.length===2&&e[0][0]==="#"){if(e[1]===sn.defaultServerName())return e[0];throw new Error("Unsupported remote room alias")}return t}async function kfe(t,e,n){M.log("Creating room for group call");const r=t.createRoom({visibility:GJ.Private,preset:nT.PublicChat,name:e,room_alias_name:n?void 0:J_(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:{[t.getUserId()]:100}}}),i=await new Promise((o,a)=>{r.catch(d=>{a(d),l()});const c=d=>{r.then(h=>{d.roomId===h.room_id&&(o(d.roomId),l())},h=>{M.error("Failed to wait for the room to arrive",h)})},l=()=>{t.off(Le.Room,c)};t.on(Le.Room,c)});let s;return n==hn.SHARED_KEY&&(s=BJ(16),Cfe(i,s)),{roomId:i,alias:n?void 0:TXe(e,t),password:s}}function xfe(t,e,n,r){return`${window.location.protocol}//${window.location.host}${KR(t,e,n)}`}function KR(t,e,n,r){return`/room/#${n?"/"+J_(n):""}?${Tje(t,e).toString()}`}async function RXe(t){let e=0;for(;;)try{return await t()}catch(n){e++;const r=GO(n,e,!0);if(r<0)throw n;await _p(r)}}const fD=t=>{const[e,n]=_.useState(void 0),[r,i]=_.useState(void 0),s=_.useRef(void 0);s.current||(s.current=aT({baseUrl:sn.defaultHomeserverUrl()})),_.useEffect(()=>{ut||s.current.registerRequest({}).catch(a=>{n(a.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url),i(a.data?.params["m.login.recaptcha"]?.public_key)})},[]);const o=_.useCallback(async(a,c,l,d,h)=>{const m=new l7({matrixClient:s.current,doRequest:async x=>s.current.registerRequest({username:a,password:c,auth:x||void 0}),stateUpdated:(x,T)=>{if(T.error)throw new Error(T.error);x==="m.login.terms"?m.submitAuthDict({type:"m.login.terms"}).catch(I=>{M.error(I)}):x==="m.login.recaptcha"&&m.submitAuthDict({type:"m.login.recaptcha",response:d}).catch(I=>{M.error(I)})},requestEmailToken:async()=>Promise.resolve({sid:"dummy"})}),{user_id:g,access_token:y,device_id:v}=await m.attemptAuth();await t?.logout(!0);const w=await Rfe({baseUrl:sn.defaultHomeserverUrl(),accessToken:y,userId:g,deviceId:v},!1);await w.setDisplayName(l);const S={user_id:g,device_id:v,access_token:y,passwordlessUser:h};h&&(S.tempPassword=c);const R=w.getUser(w.getUserId());return R.setRawDisplayName(l),R.setDisplayName(l),[w,S]},[t]);return{privacyPolicyUrl:e,recaptchaKey:r,register:o}},IXe="_buttons_1arp2_8",kXe={buttons:IXe},Afe=({onJoin:t,open:e,onDismiss:n})=>{const{t:r}=We();return E.jsxs(Up,{title:r("join_existing_call_modal.title"),open:e,onDismiss:n,children:[E.jsx("p",{children:r("join_existing_call_modal.text")}),E.jsxs(yt,{rightAlign:!0,className:kXe.buttons,children:[E.jsx(Bt,{onClick:n,children:r("action.no")}),E.jsx(Bt,{onClick:t,"data-testid":"home_joinExistingRoom",children:r("join_existing_call_modal.join_button")})]})]})},AW="https://www.recaptcha.net/recaptcha/api.js?onload=mxOnRecaptchaLoaded&render=explicit";function hD(t){const{t:e}=We(),[n]=_.useState(()=>To(16)),r=_.useRef(void 0);_.useEffect(()=>{if(!t)return;const o=()=>{document.getElementById(n)&&window.grecaptcha.render(n,{sitekey:t,size:"invisible",callback:a=>r.current?.resolve(a),"error-callback":()=>r.current?.reject(new Error)})};if(typeof window.grecaptcha?.render=="function")o();else if(window.mxOnRecaptchaLoaded=o,!document.querySelector(`script[src="${AW}"]`)){const a=document.createElement("script");a.src=AW,a.async=!0,document.body.appendChild(a)}},[n,t]);const i=_.useCallback(async()=>t?window.grecaptcha?new Promise((o,a)=>{const c=new MutationObserver(d=>{for(const h of d)if(h.target?.style?.visibility!=="visible"){a(sz("recaptcha_dismissed",e)),c.disconnect();return}});r.current={resolve:d=>{o(d),c.disconnect()},reject:d=>{a(d),c.disconnect()}},window.grecaptcha.execute().then(()=>{},d=>{M.error("Recaptcha execution failed",d)});const l=document.querySelector('iframe[src*="recaptcha/api2/bframe"]');l?.parentNode?.parentNode&&c.observe(l?.parentNode?.parentNode,{attributes:!0})}):(M.log("Recaptcha not loaded"),Promise.reject(sz("recaptcha_not_loaded",e))):Promise.resolve(""),[t,e]),s=_.useCallback(()=>{window.grecaptcha?.reset()},[]);return{execute:i,reset:s,recaptchaId:n}}const xXe="_form_jcuzc_8",AXe={form:xXe},zR=({ref:t,children:e,className:n,onSubmit:r})=>E.jsx("form",{onSubmit:r,className:Oe(AXe.form,n),ref:t,children:e});zR.displayName="Form";const PXe="_footer_106jg_8",LXe="_mobileLoginLink_106jg_19",OXe="_form_106jg_24",MXe="_notice_106jg_40",Q1={footer:PXe,mobileLoginLink:LXe,form:OXe,notice:MXe},DXe="_container_dwllg_8",NXe="_main_dwllg_15",UXe="_logo_dwllg_23",Xg={container:DXe,main:NXe,logo:UXe},PW=t=>{t=1831565813+(t|=0)|0;let e=Math.imul(t^t>>>15,1|t);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};class jXe{constructor(e){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:n,separator:r,dictionaries:i,style:s,seed:o}=e;this.dictionaries=i,this.separator=r,this.length=n,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.
338
338
  Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let e=this.seed;return this.dictionaries.slice(0,this.length).reduce((n,r)=>{let i;e?(i=(o=>{if(typeof o=="string"){const a=o.split("").map(l=>l.charCodeAt(0)).reduce((l,d)=>l+d,1),c=Math.floor(Number(a));return PW(c)}return PW(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 n?`${n}${this.separator}${s}`:`${s}`},"")}}const LW={separator:"_",dictionaries:[]},FXe=t=>{const e=[...t&&t.dictionaries||LW.dictionaries],n={...LW,...t,length:t&&t.length||e.length,dictionaries:e};if(!t||!t.dictionaries||!t.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 jXe(n).generate()};var $Xe=["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"],BXe=["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"],HXe=["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 VXe=["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 Pfe(){return FXe({dictionaries:[HXe,$Xe,BXe,VXe],style:"lowerCase",length:3,separator:"-"})}const qXe=()=>{const{setClient:t}=jp(),{header:e}=no(),[n,r]=_.useState(!1),[i,s]=_.useState(),[o]=uR(),{recaptchaKey:a,register:c}=fD(),{execute:l,reset:d,recaptchaId:h}=hD(a),[m,g]=_.useState(!1),y=_.useCallback(()=>g(!1),[g]),[v,w]=_.useState(),S=hl(),{t:R}=We(),x=_.useCallback(T=>{T.preventDefault();const I=new FormData(T.target),k=Ife(I.get("callName")),A=I.get("displayName");async function O(){s(void 0),r(!0);const D=await l(),N=Pfe(),[U,$]=await c(N,To(16),A,D,!0);let K;try{K=await kfe(U,k,hn.SHARED_KEY)}catch(Y){if(!t)throw Y;if(Y.errcode==="M_ROOM_IN_USE"){w(()=>{t(U,$);const G=J_(k);S(`/${G}`)?.catch(F=>{M.error("Failed to navigate to alias localpart",F)})}),r(!1),g(!0);return}else throw Y}if(!t)throw new Error("setClient is undefined");if(!K.password)throw new Error("Failed to create room with shared secret");t(U,$),await S(KR(K.roomId,{kind:hn.SHARED_KEY,secret:K.password},k))}O().catch(D=>{M.error(D),r(!1),s(D),d()})},[c,d,l,S,g,t]);return E.jsxs(E.Fragment,{children:[E.jsxs("div",{className:Xg.container,children:[e==="standard"&&E.jsxs(qu,{children:[E.jsx(jf,{children:E.jsx(fp,{})}),E.jsx(Ff,{hideMobile:!0,children:E.jsx(dD,{})})]}),E.jsxs("main",{className:Xg.main,children:[E.jsx(fp,{className:Xg.logo}),E.jsx(gl,{size:"lg",weight:"semibold",children:R("start_new_call")}),E.jsxs(zR,{className:Q1.form,onSubmit:x,children:[E.jsx(yt,{children:E.jsx(Tn,{id:"callName",name:"callName",label:R("call_name"),placeholder:R("call_name"),type:"text",required:!0,autoComplete:"off","data-testid":"home_callName"})}),E.jsx(yt,{children:E.jsx(Tn,{id:"displayName",name:"displayName",label:R("common.display_name"),placeholder:R("common.display_name"),type:"text",required:!0,"data-testid":"home_displayName",autoComplete:"off"})}),o===null&&E.jsx(an,{size:"sm",className:Q1.notice,children:E.jsx(Xle,{})}),E.jsx(an,{size:"sm",className:Q1.notice,children:E.jsxs(Ys,{i18nKey:"unauthenticated_view_ssla_caption",children:['By clicking "Go", you agree to our'," ",E.jsx(Jh,{href:sn.get().ssla,children:"Software and Services License Agreement (SSLA)"})]})}),i&&E.jsx(yt,{children:E.jsx(Bf,{error:i})}),E.jsx(Bt,{type:"submit",size:"lg",disabled:n,"data-testid":"home_go",children:R(n?"common.loading":"action.go")}),E.jsx("div",{id:h})]})]}),E.jsxs("footer",{className:Q1.footer,children:[E.jsx(an,{className:Q1.mobileLoginLink,children:E.jsx(il,{to:"/login","data-testid":"home_login",children:R("unauthenticated_view_login_button")})}),E.jsx(an,{children:E.jsxs(Ys,{i18nKey:"unauthenticated_view_body",children:["Not registered yet?"," ",E.jsx(il,{to:"/register","data-testid":"home_register",children:"Create an account"})]})})]})]}),v&&E.jsx(Afe,{onJoin:v,open:m,onDismiss:y})]})},Gm={};function OW(t,e){if(Gm[e.roomId])return Gm[e.roomId];if(!e||!e.timeline){const i=Number.MAX_SAFE_INTEGER;return Gm[e.roomId]=i,i}const n=t.getUserId();if(e.getMyMembership()!==Be.Join){const i=e.currentState.getStateEvents("m.room.member",n);if(i&&!Array.isArray(i)){const s=i.getTs();return Gm[e.roomId]=s,s}}for(let i=e.timeline.length-1;i>=0;--i){const o=e.timeline[i].getTs();if(o)return Gm[e.roomId]=o,o}const r=Number.MAX_SAFE_INTEGER;return Gm[e.roomId]=r,r}function GXe(t,e){return e.sort((n,r)=>OW(t,r)-OW(t,n))}const KXe=t=>{const e=Tfe(t.roomId);if(!t.hasEncryptionStateEvent()&&!e)return!1;switch(t.getJoinRule()){case ef.Public:return!0;case ef.Knock:switch(t.getMyMembership()){case Be.Join:case Be.Knock:return!0;case Be.Invite:return t.getLiveTimeline().getState(Me.FORWARDS)?.getStateEvents(Z.RoomMember,t.myUserId)?.getPrevContent().membership===ef.Knock;default:return!1}default:return t.getMyMembership()===Be.Join}},zXe=t=>{switch(t.getMyMembership()){case Be.Join:return!!t.getLiveTimeline().getState(Me.FORWARDS)?.events?.get(Z.GroupCallMemberPrefix);case Be.Knock:return!0;default:return!1}};function WXe(t){const[e,n]=_.useState([]);return _.useEffect(()=>{function r(){const i=t.getRooms().filter(zXe).filter(KXe),o=GXe(t,i).map(a=>{const c=t.matrixRTC.getRoomSession(a);return{roomAlias:a.getCanonicalAlias()??void 0,roomName:a.name,avatarUrl:a.getMxcAvatarUrl(),room:a,session:c,participants:c.memberships.filter(l=>l.sender).map(l=>a.getMember(l.sender)).filter(l=>l)}});n(o)}return r(),t.matrixRTC.on(hC.SessionStarted,r),t.on(ke.MyMembership,r),()=>{t.matrixRTC.off(hC.SessionStarted,r),t.off(ke.MyMembership,r)}},[t]),e}const YXe="_form_1vjc2_8",XXe="_fieldRow_1vjc2_16",JXe="_button_1vjc2_24",QXe="_notice_1vjc2_32",Z1={form:YXe,fieldRow:XXe,button:JXe,notice:QXe},ZXe="_callTileSpacer_l4ywf_8",eJe="_callTile_l4ywf_8",tJe="_callTileLink_l4ywf_28",nJe="_callInfo_l4ywf_40",rJe="_callName_l4ywf_53",iJe="_callList_l4ywf_63",sJe="_disabled_l4ywf_74",nu={callTileSpacer:ZXe,callTile:eJe,callTileLink:tJe,callInfo:nJe,callName:rJe,callList:iJe,disabled:sJe},oJe=({rooms:t,client:e})=>E.jsx(E.Fragment,{children:E.jsxs("div",{className:nu.callList,children:[t.map(({room:n,roomName:r,avatarUrl:i,participants:s})=>E.jsx(aJe,{client:e,name:r,avatarUrl:i,room:n,participants:s},n.roomId)),t.length>3&&E.jsxs(E.Fragment,{children:[E.jsx("div",{className:nu.callTileSpacer}),E.jsx("div",{className:nu.callTileSpacer})]})]})}),aJe=({name:t,avatarUrl:e,room:n,client:r})=>{const{t:i}=We(),s=X_(n.roomId),[o,a]=_.useState(!1),c=_.useCallback(d=>{d.stopPropagation(),d.preventDefault(),a(!0),r.leave(n.roomId).catch(()=>a(!1))},[n,r]),l=E.jsxs(E.Fragment,{children:[E.jsx(Op,{id:n.roomId,name:t,size:Lp.LG,src:e}),E.jsx("div",{className:nu.callInfo,children:E.jsx(an,{weight:"semibold",className:nu.callName,children:t})}),E.jsx(UT,{onClick:c,disabled:o,"aria-label":i("action.remove"),children:E.jsx(LT,{})})]});return E.jsx("div",{className:nu.callTile,children:o?E.jsx("span",{className:Oe(nu.callTileLink,nu.disabled),children:l}):E.jsx(yT,{to:KR(n.roomId,s,n.name),className:nu.callTileLink,children:l})})},cJe=({client:t})=>{const{header:e}=no(),[n,r]=_.useState(!1),[i,s]=_.useState(),[o]=uR(),a=hl(),{t:c}=We(),[l,d]=_.useState(!1),h=_.useCallback(()=>d(!1),[d]),m=_.useCallback(S=>{S.preventDefault();const x=new FormData(S.target).get("callName"),T=typeof x=="string"?Ife(x):"";async function I(){s(void 0),r(!0);const k=await kfe(t,T,hn.SHARED_KEY);if(!k.password)throw new Error("Failed to create room with shared secret");await a(KR(k.roomId,{kind:hn.SHARED_KEY,secret:k.password},T))}I().catch(k=>{k.errcode==="M_ROOM_IN_USE"?(v(J_(T)),r(!1),s(void 0),d(!0)):(M.error(k),r(!1),s(k))})},[t,a,d]),g=WXe(t),[y,v]=_.useState(),w=_.useCallback(()=>{a(`/${y}`)?.catch(S=>{M.error("Failed to navigate to existing alias",S)})},[a,y]);return E.jsxs(E.Fragment,{children:[E.jsxs("div",{className:Xg.container,children:[e==="standard"&&E.jsxs(qu,{children:[E.jsx(jf,{children:E.jsx(fp,{})}),E.jsx(Ff,{children:E.jsx(dD,{})})]}),E.jsxs("main",{className:Xg.main,children:[E.jsx(fp,{className:Xg.logo}),E.jsx(gl,{size:"lg",weight:"semibold",children:c("start_new_call")}),E.jsxs(zR,{className:Z1.form,onSubmit:m,children:[E.jsxs(yt,{className:Z1.fieldRow,children:[E.jsx(Tn,{id:"callName",name:"callName",label:c("call_name"),placeholder:c("call_name"),type:"text",required:!0,autoComplete:"off","data-testid":"home_callName"}),E.jsx(Bt,{type:"submit",size:"lg",className:Z1.button,disabled:n,"data-testid":"home_go",children:c(n?"common.loading":"action.go")})]}),o===null&&E.jsx(an,{size:"sm",className:Z1.notice,children:E.jsx(Xle,{})}),i&&E.jsx(yt,{className:Z1.fieldRow,children:E.jsx(Bf,{error:i})})]}),g.length>0&&E.jsx(oJe,{rooms:g,client:t})]})]}),E.jsx(Afe,{onJoin:w,open:l,onDismiss:h})]})};function Q_(t){_.useEffect(()=>{const e="Element Call";document.title=t?`${e} | ${t}`:e},[t])}const Lfe=()=>{const{t}=We();Q_(t("common.home"));const e=r0();return e?e.state==="error"?E.jsx(zb,{widget:ut,error:e.error}):e.authenticated?E.jsx(cJe,{client:e.authenticated.client}):E.jsx(qXe,{}):E.jsx(pR,{})},lJe=(t,e)=>_.createElement("svg",{width:300,height:66,viewBox:"0 0 300 66",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),Ofe=_.forwardRef(lJe),uJe="_logo_1gx2r_8",dJe="_container_1gx2r_14",fJe="_content_1gx2r_22",hJe="_formContainer_1gx2r_30",pJe="_authLinks_1gx2r_62",zc={logo:uJe,container:dJe,content:fJe,formContainer:hJe,authLinks:pJe};function mJe(t){return _.useCallback(async(e,n,r)=>{const i=aT({baseUrl:e}),s=new l7({matrixClient:i,doRequest:async()=>i.login("m.login.password",{identifier:{type:"m.id.user",user:n},password:r}),stateUpdated:()=>{},requestEmailToken:async()=>Promise.resolve({sid:""})}),{user_id:o,access_token:a,device_id:c}=await s.attemptAuth(),l={user_id:o,access_token:a,device_id:c,passwordlessUser:!1};return await t?.logout(!0),[await Rfe({baseUrl:e,accessToken:a,userId:o,deviceId:c},!1),l]},[t])}const gJe=()=>{const{t}=We();Q_(t("login_title"));const{client:e,setClient:n}=jp(),r=mJe(e),i=sn.defaultHomeserverUrl(),s=_.useRef(null),o=_.useRef(null),a=hl(),c=rs(),[l,d]=_.useState(!1),[h,m]=_.useState(),g=_.useCallback(v=>{if(v.preventDefault(),d(!0),!i||!s.current||!o.current){m(Error("Login parameters are undefined")),d(!1);return}r(i,s.current.value,o.current.value).then(async([w,S])=>{if(!n)return;n(w,S);const R=c.state;R&&R.from?await a(R.from):await a("/"),Ut.instance.eventLogin.track()}).catch(w=>{m(w),d(!1)})},[r,c,a,i,n]);let y=sn.defaultServerName()?.slice(0,25);return y=y?.length!==sn.defaultServerName()?.length?y+"...":y,E.jsx(E.Fragment,{children:E.jsx("div",{className:zc.container,children:E.jsxs("div",{className:zc.content,children:[E.jsxs("div",{className:zc.formContainer,children:[E.jsx(Ofe,{width:"auto",height:"auto",className:zc.logo}),E.jsx("h2",{children:t("log_in")}),E.jsx("h4",{children:t("login_subheading")}),E.jsxs("form",{onSubmit:g,children:[E.jsx(yt,{children:E.jsx(Tn,{type:"text",ref:s,placeholder:t("common.username"),label:t("common.username"),autoCorrect:"off",autoCapitalize:"none",prefix:"@",suffix:`:${y}`,"data-testid":"login_username"})}),E.jsx(yt,{children:E.jsx(Tn,{type:"password",ref:o,placeholder:t("common.password"),label:t("common.password"),"data-testid":"login_password"})}),h&&E.jsx(yt,{children:E.jsx(Bf,{error:h})}),E.jsx(yt,{children:E.jsx(Bt,{type:"submit",disabled:l,"data-testid":"login_login",children:t(l?"logging_in":"login_title")})})]})]}),E.jsxs("div",{className:zc.authLinks,children:[E.jsx("p",{children:t("login_auth_links_prompt")}),E.jsx("p",{children:E.jsxs(Ys,{i18nKey:"login_auth_links",children:[E.jsx(il,{to:"/register",children:"Create an account"})," Or ",E.jsx(il,{to:"/",children:"Access as a guest"})]})})]})]})})})},vJe=()=>{const{t}=We();Q_(t("action.register"));const{loading:e,authenticated:n,passwordlessUser:r,client:i,setClient:s}=W8(),o=_.useRef(null),a=hl(),c=rs(),[l,d]=_.useState(!1),[h,m]=_.useState(),[g,y]=_.useState(""),[v,w]=_.useState(""),{recaptchaKey:S,register:R}=fD(i),{execute:x,reset:T,recaptchaId:I}=hD(S),k=_.useCallback(A=>{A.preventDefault();const O=new FormData(A.target),D=O.get("userName"),N=O.get("password"),U=O.get("passwordConfirmation");if(N!==U)return;(async()=>{d(!0);const K=await x(),[Y,G]=await R(D,N,D,K,r);if(i&&i?.groupCallEventHandler&&r)for(const F of i.groupCallEventHandler.groupCalls.values()){const q=F.room.roomId;try{await Y.joinRoom(q)}catch(z){z.errcode==="M_LIMIT_EXCEEDED"?(await _p(z.data.retry_after_ms),await Y.joinRoom(q)):(IT(z),M.error(`Couldn't join room ${q}`,z))}}s?.(Y,G),Ut.instance.eventSignup.cacheSignupEnd(new Date)})().then(async()=>{c.state?.from?await a(c.state?.from):await a("/")}).catch(K=>{m(K),d(!1),T()})},[R,c,a,r,T,x,i,s]);return _.useEffect(()=>{g&&v&&g!==v?o.current?.setCustomValidity(t("register.passwords_must_match")):o.current?.setCustomValidity("")},[g,v,t]),_.useEffect(()=>{!e&&n&&!r&&!l&&a("/")?.catch(A=>{M.error("Failed to navigate to /",A)})},[e,a,n,r,l]),e?E.jsx(pR,{}):(Ut.instance.eventSignup.cacheSignupStart(new Date),E.jsx(E.Fragment,{children:E.jsx("div",{className:zc.container,children:E.jsxs("div",{className:zc.content,children:[E.jsxs("div",{className:zc.formContainer,children:[E.jsx(Ofe,{width:"auto",height:"auto",className:zc.logo}),E.jsx("h2",{children:t("register_heading")}),E.jsxs("form",{onSubmit:k,children:[E.jsx(yt,{children:E.jsx(Tn,{type:"text",name:"userName",placeholder:t("common.username"),label:t("common.username"),autoCorrect:"off",autoCapitalize:"none",prefix:"@",suffix:`:${sn.defaultServerName()}`,"data-testid":"register_username"})}),E.jsx(yt,{children:E.jsx(Tn,{required:!0,name:"password",type:"password",onChange:A=>y(A.target.value),value:g,placeholder:t("common.password"),label:t("common.password"),"data-testid":"register_password"})}),E.jsx(yt,{children:E.jsx(Tn,{required:!0,type:"password",name:"passwordConfirmation",onChange:A=>w(A.target.value),value:v,placeholder:t("register_confirm_password_label"),label:t("register_confirm_password_label"),ref:o,"data-testid":"register_confirm_password"})}),E.jsx(an,{size:"sm",children:E.jsxs(Ys,{i18nKey:"recaptcha_ssla_caption",children:["This site is protected by ReCAPTCHA and the Google"," ",E.jsx(Jh,{href:"https://www.google.com/policies/privacy/",children:"Privacy Policy"})," ","and"," ",E.jsx(Jh,{href:"https://policies.google.com/terms",children:"Terms of Service"})," ","apply.",E.jsx("br",{}),'By clicking "Register", you agree to our'," ",E.jsx(Jh,{href:sn.get().ssla,children:"Software and Services License Agreement (SSLA)"})]})}),h&&E.jsx(yt,{children:E.jsx(Bf,{error:h})}),E.jsx(yt,{children:E.jsx(Bt,{type:"submit",disabled:l,"data-testid":"register_register",children:t(l?"register.registering":"action.register")})}),E.jsx("div",{id:I})]})]}),E.jsx("div",{className:zc.authLinks,children:E.jsxs(Ys,{i18nKey:"register_auth_links",children:[E.jsx("p",{children:"Already have an account?"}),E.jsxs("p",{children:[E.jsx(il,{to:"/login",children:"Log in"})," Or ",E.jsx(il,{to:"/",children:"Access as a guest"})]})]})})]})})}))},yJe="_form_1wfyo_8",bJe="_headline_1wfyo_18",_Je="_container_1wfyo_37",SJe="_main_1wfyo_45",EJe="_footer_1wfyo_62",ey={form:yJe,headline:bJe,container:_Je,main:SJe,footer:EJe};function Mfe(){const{setClient:t}=jp(),{privacyPolicyUrl:e,recaptchaKey:n,register:r}=fD(),{execute:i,reset:s,recaptchaId:o}=hD(n),a=_.useCallback(async c=>{if(!t)throw new Error("No client context");if(ut)throw new Error("Registration was skipped: We should never try to register password-less user in embedded mode.");try{const l=await i(),d=Pfe(),[h,m]=await r(d,To(16),c,l,!0);t(h,m)}catch(l){throw s(),l}},[i,s,r,t]);return{privacyPolicyUrl:e,registerPasswordlessUser:a,recaptchaId:o}}const wJe=()=>{const{header:t}=no(),[e,n]=_.useState(!1),[r,i]=_.useState(),{registerPasswordlessUser:s,recaptchaId:o}=Mfe(),a=_.useCallback(d=>{d.preventDefault(),n(!0);const m=new FormData(d.target).get("displayName");s(typeof m=="string"?m:"").catch(y=>{M.error("Failed to register passwordless user",d),n(!1),i(y)})},[s]),{t:c}=We(),l=rs();return E.jsxs(E.Fragment,{children:[t==="standard"&&E.jsxs(qu,{children:[E.jsx(jf,{children:E.jsx(fp,{})}),E.jsx(Ff,{children:E.jsx(dD,{preventNavigation:!0})})]}),E.jsxs("div",{className:ey.container,children:[E.jsxs("main",{className:ey.main,children:[E.jsx(gl,{size:"xl",weight:"semibold",className:ey.headline,children:c("lobby.join_as_guest")}),E.jsxs(zR,{className:ey.form,onSubmit:a,children:[E.jsx(yt,{children:E.jsx(Tn,{id:"displayName",name:"displayName",label:c("common.display_name"),placeholder:c("common.display_name"),"data-testid":"joincall_displayName",type:"text",required:!0,autoComplete:"off"})}),E.jsx(an,{size:"sm",children:E.jsxs(Ys,{i18nKey:"room_auth_view_ssla_caption",children:['By clicking "Join call now", you agree to our'," ",E.jsx(Jh,{href:sn.get().ssla,children:"Software and Services License Agreement (SSLA)"})]})}),r&&E.jsx(yt,{children:E.jsx(Bf,{error:r})}),E.jsx(Bt,{type:"submit",size:"lg",disabled:e,"data-testid":"joincall_joincall",children:c(e?"common.loading":"room_auth_view_continue_button")}),E.jsx("div",{id:o})]})]}),E.jsx(an,{className:ey.footer,children:E.jsxs(Ys,{i18nKey:"unauthenticated_view_body",children:["Not registered yet?"," ",E.jsx(il,{to:"/register",state:{from:l},children:"Create an account"})]})})]})]})};var IE=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Dfe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var hO={exports:{}},CJe=hO.exports,MW;function TJe(){return MW||(MW=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(CJe,function(){var e=function(){},n="undefined",r=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],s={},o=null;function a(v,w){var S=v[w];if(typeof S.bind=="function")return S.bind(v);try{return Function.prototype.bind.call(S,v)}catch{return function(){return Function.prototype.apply.apply(S,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&r?c:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<i.length;w++){var S=i[w];this[S]=w<v?e:this.methodFactory(S,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function h(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function m(v,w,S){return l(v)||h.apply(this,arguments)}function g(v,w){var S=this,R,x,T,I="loglevel";typeof v=="string"?I+=":"+v:typeof v=="symbol"&&(I=void 0);function k(U){var $=(i[U]||"silent").toUpperCase();if(!(typeof window===n||!I)){try{window.localStorage[I]=$;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+$+";"}catch{}}}function A(){var U;if(!(typeof window===n||!I)){try{U=window.localStorage[I]}catch{}if(typeof U===n)try{var $=window.document.cookie,K=encodeURIComponent(I),Y=$.indexOf(K+"=");Y!==-1&&(U=/^([^;]+)/.exec($.slice(Y+K.length+1))[1])}catch{}return S.levels[U]===void 0&&(U=void 0),U}}function O(){if(!(typeof window===n||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function D(U){var $=U;if(typeof $=="string"&&S.levels[$.toUpperCase()]!==void 0&&($=S.levels[$.toUpperCase()]),typeof $=="number"&&$>=0&&$<=S.levels.SILENT)return $;throw new TypeError("log.setLevel() called with invalid level: "+U)}S.name=v,S.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},S.methodFactory=w||m,S.getLevel=function(){return T??x??R},S.setLevel=function(U,$){return T=D(U),$!==!1&&k(T),d.call(S)},S.setDefaultLevel=function(U){x=D(U),A()||S.setLevel(U,!1)},S.resetLevel=function(){T=null,O(),d.call(S)},S.enableAll=function(U){S.setLevel(S.levels.TRACE,U)},S.disableAll=function(U){S.setLevel(S.levels.SILENT,U)},S.rebuild=function(){if(o!==S&&(R=D(o.getLevel())),d.call(S),o===S)for(var U in s)s[U].rebuild()},R=D(o?o.getLevel():"WARN");var N=A();N!=null&&(T=D(N)),d.call(S)}o=new g,o.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var w=s[v];return w||(w=s[v]=new g(v,o.methodFactory)),w};var y=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return s},o.default=o,o})}(hO)),hO.exports}var RJe=TJe();const IJe=Dfe(RJe);var pO=function(t,e){return pO=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i])},pO(t,e)};function Xu(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");pO(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function kJe(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(d){try{l(r.next(d))}catch(h){o(h)}}function c(d){try{l(r.throw(d))}catch(h){o(h)}}function l(d){d.done?s(d.value):i(d.value).then(a,c)}l((r=r.apply(t,[])).next())})}function Nfe(t,e){var n={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(l){return function(d){return c([l,d])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(n=0)),n;)try{if(r=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,i=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){n.label=l[1];break}if(l[0]===6&&n.label<s[1]){n.label=s[1],s=l;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(l);break}s[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(d){l=[6,d],i=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Mv(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function A3(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),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&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function P3(t,e,n){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 t.concat(s||Array.prototype.slice.call(e))}function Jg(t){return this instanceof Jg?(this.v=t,this):new Jg(t)}function xJe(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,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(g){return function(y){return Promise.resolve(y).then(g,h)}}function a(g,y){r[g]&&(i[g]=function(v){return new Promise(function(w,S){s.push([g,v,w,S])>1||c(g,v)})},y&&(i[g]=y(i[g])))}function c(g,y){try{l(r[g](y))}catch(v){m(s[0][3],v)}}function l(g){g.value instanceof Jg?Promise.resolve(g.value.v).then(d,h):m(s[0][2],g)}function d(g){c("next",g)}function h(g){c("throw",g)}function m(g,y){g(y),s.shift(),s.length&&c(s[0][0],s[0][1])}}function AJe(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Mv=="function"?Mv(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function ci(t){return typeof t=="function"}function pD(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Zx=pD(function(t){return function(e){t(this),this.message=e?e.length+` errors occurred during unsubscription:
339
339
  `+e.map(function(n,r){return r+1+") "+n.toString()}).join(`
340
340
  `):"",this.name="UnsubscriptionError",this.errors=e}});function L3(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var Z_=function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,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=Mv(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.remove(this)}}catch(v){e={error:v}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else o.remove(this);var d=this.initialTeardown;if(ci(d))try{d()}catch(v){s=v instanceof Zx?v.errors:[v]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var m=Mv(h),g=m.next();!g.done;g=m.next()){var y=g.value;try{DW(y)}catch(v){s=s??[],v instanceof Zx?s=P3(P3([],A3(s)),A3(v.errors)):s.push(v)}}}catch(v){r={error:v}}finally{try{g&&!g.done&&(i=m.return)&&i.call(m)}finally{if(r)throw r.error}}}if(s)throw new Zx(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)DW(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&L3(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&L3(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=function(){var e=new t;return e.closed=!0,e}(),t}(),Ufe=Z_.EMPTY;function jfe(t){return t instanceof Z_||t&&"closed"in t&&ci(t.remove)&&ci(t.add)&&ci(t.unsubscribe)}function DW(t){ci(t)?t():t.unsubscribe()}var PJe={Promise:void 0},LJe={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,P3([t,e],A3(n)))},clearTimeout:function(t){return clearTimeout(t)},delegate:void 0};function Ffe(t){LJe.setTimeout(function(){throw t})}function NW(){}function Ww(t){t()}var mD=function(t){Xu(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,jfe(n)&&n.add(r)):r.destination=DJe,r}return e.create=function(n,r,i){return new mO(n,r,i)},e.prototype.next=function(n){this.isStopped||this._next(n)},e.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Z_),OJe=function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){kE(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){kE(r)}else kE(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){kE(n)}},t}(),mO=function(t){Xu(e,t);function e(n,r,i){var s=t.call(this)||this,o;return ci(n)||!n?o={next:n??void 0,error:r??void 0,complete:i??void 0}:o=n,s.destination=new OJe(o),s}return e}(mD);function kE(t){Ffe(t)}function MJe(t){throw t}var DJe={closed:!0,next:NW,error:MJe,complete:NW},gD=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function $fe(t){return t}function NJe(t){return t.length===0?$fe:t.length===1?t[0]:function(e){return t.reduce(function(n,r){return r(n)},e)}}var Ao=function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var i=this,s=jJe(e)?e:new mO(e,n,r);return Ww(function(){var o=i,a=o.operator,c=o.source;s.add(a?a.call(s,c):c?i._subscribe(s):i._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=UW(n),new n(function(i,s){var o=new mO({next:function(a){try{e(a)}catch(c){s(c),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[gD]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return NJe(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=UW(e),new e(function(r,i){var s;n.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},t.create=function(e){return new t(e)},t}();function UW(t){var e;return(e=t??PJe.Promise)!==null&&e!==void 0?e:Promise}function UJe(t){return t&&ci(t.next)&&ci(t.error)&&ci(t.complete)}function jJe(t){return t&&t instanceof mD||UJe(t)&&jfe(t)}function FJe(t){return ci(t?.lift)}function eS(t){return function(e){if(FJe(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function O3(t,e,n,r,i){return new $Je(t,e,n,r,i)}var $Je=function(t){Xu(e,t);function e(n,r,i,s,o,a){var c=t.call(this,n)||this;return c.onFinalize=o,c.shouldUnsubscribe=a,c._next=r?function(l){try{r(l)}catch(d){n.error(d)}}:t.prototype._next,c._error=s?function(l){try{s(l)}catch(d){n.error(d)}finally{this.unsubscribe()}}:t.prototype._error,c._complete=i?function(){try{i()}catch(l){n.error(l)}finally{this.unsubscribe()}}:t.prototype._complete,c}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e}(mD),BJe=pD(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Bfe=function(t){Xu(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new jW(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new BJe},e.prototype.next=function(n){var r=this;Ww(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=Mv(r.currentObservers),a=o.next();!a.done;a=o.next()){var c=a.value;c.next(n)}}catch(l){i={error:l}}finally{try{a&&!a.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(n){var r=this;Ww(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var i=r.observers;i.length;)i.shift().error(n)}})},e.prototype.complete=function(){var n=this;Ww(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.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 n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,i=this,s=i.hasError,o=i.isStopped,a=i.observers;return s||o?Ufe:(this.currentObservers=null,a.push(n),new Z_(function(){r.currentObservers=null,L3(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?n.error(s):o&&n.complete()},e.prototype.asObservable=function(){var n=new Ao;return n.source=this,n},e.create=function(n,r){return new jW(n,r)},e}(Ao),jW=function(t){Xu(e,t);function e(n,r){var i=t.call(this)||this;return i.destination=n,i.source=r,i}return e.prototype.next=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,n)},e.prototype.error=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&i!==void 0?i:Ufe},e}(Bfe);(function(t){Xu(e,t);function e(n){var r=t.call(this)||this;return r._value=n,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(n){var r=t.prototype._subscribe.call(this,n);return!r.closed&&n.next(this._value),r},e.prototype.getValue=function(){var n=this,r=n.hasError,i=n.thrownError,s=n._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(n){t.prototype.next.call(this,this._value=n)},e})(Bfe);var HJe={now:function(){return Date.now()}},VJe=function(t){Xu(e,t);function e(n,r){return t.call(this)||this}return e.prototype.schedule=function(n,r){return this},e}(Z_),FW={setInterval:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,P3([t,e],A3(n)))},clearInterval:function(t){return clearInterval(t)},delegate:void 0},qJe=function(t){Xu(e,t);function e(n,r){var i=t.call(this,n,r)||this;return i.scheduler=n,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(n,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=n;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(n,r,i){return i===void 0&&(i=0),FW.setInterval(n.flush.bind(n,this),i)},e.prototype.recycleAsyncId=function(n,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&FW.clearInterval(r)},e.prototype.execute=function(n,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(n,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(n,r){var i=!1,s;try{this.work(n)}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 n=this,r=n.id,i=n.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,L3(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,t.prototype.unsubscribe.call(this)}},e}(VJe),$W=function(){function t(e,n){n===void 0&&(n=t.now),this.schedulerActionCtor=e,this.now=n}return t.prototype.schedule=function(e,n,r){return n===void 0&&(n=0),new this.schedulerActionCtor(this,e).schedule(r,n)},t.now=HJe.now,t}(),GJe=function(t){Xu(e,t);function e(n,r){r===void 0&&(r=$W.now);var i=t.call(this,n,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(n){var r=this.actions;if(this._active){r.push(n);return}var i;this._active=!0;do if(i=n.execute(n.state,n.delay))break;while(n=r.shift());if(this._active=!1,i){for(;n=r.shift();)n.unsubscribe();throw i}},e}($W);new GJe(qJe);function KJe(t){return t&&ci(t.schedule)}function zJe(t){return t[t.length-1]}function Hfe(t){return KJe(zJe(t))?t.pop():void 0}var Vfe=function(t){return t&&typeof t.length=="number"&&typeof t!="function"};function qfe(t){return ci(t?.then)}function Gfe(t){return ci(t[gD])}function Kfe(t){return Symbol.asyncIterator&&ci(t?.[Symbol.asyncIterator])}function zfe(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function WJe(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Wfe=WJe();function Yfe(t){return ci(t?.[Wfe])}function Xfe(t){return xJe(this,arguments,function(){var e,n,r,i;return Nfe(this,function(s){switch(s.label){case 0:e=t.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,Jg(e.read())];case 3:return n=s.sent(),r=n.value,i=n.done,i?[4,Jg(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Jg(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 Jfe(t){return ci(t?.getReader)}function tS(t){if(t instanceof Ao)return t;if(t!=null){if(Gfe(t))return YJe(t);if(Vfe(t))return XJe(t);if(qfe(t))return JJe(t);if(Kfe(t))return Qfe(t);if(Yfe(t))return QJe(t);if(Jfe(t))return ZJe(t)}throw zfe(t)}function YJe(t){return new Ao(function(e){var n=t[gD]();if(ci(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function XJe(t){return new Ao(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function JJe(t){return new Ao(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Ffe)})}function QJe(t){return new Ao(function(e){var n,r;try{for(var i=Mv(t),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()})}function Qfe(t){return new Ao(function(e){eQe(t,e).catch(function(n){return e.error(n)})})}function ZJe(t){return Qfe(Xfe(t))}function eQe(t,e){var n,r,i,s;return kJe(this,void 0,void 0,function(){var o,a;return Nfe(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=AJe(t),c.label=1;case 1:return[4,n.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),i={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.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 Zh(t,e,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!i)return s}function Zfe(t,e){return e===void 0&&(e=0),eS(function(n,r){n.subscribe(O3(r,function(i){return Zh(r,t,function(){return r.next(i)},e)},function(){return Zh(r,t,function(){return r.complete()},e)},function(i){return Zh(r,t,function(){return r.error(i)},e)}))})}function ehe(t,e){return e===void 0&&(e=0),eS(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function tQe(t,e){return tS(t).pipe(ehe(e),Zfe(e))}function nQe(t,e){return tS(t).pipe(ehe(e),Zfe(e))}function rQe(t,e){return new Ao(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function iQe(t,e){return new Ao(function(n){var r;return Zh(n,e,function(){r=t[Wfe](),Zh(n,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(a){n.error(a);return}o?n.complete():n.next(s)},0,!0)}),function(){return ci(r?.return)&&r.return()}})}function the(t,e){if(!t)throw new Error("Iterable cannot be null");return new Ao(function(n){Zh(n,e,function(){var r=t[Symbol.asyncIterator]();Zh(n,e,function(){r.next().then(function(i){i.done?n.complete():n.next(i.value)})},0,!0)})})}function sQe(t,e){return the(Xfe(t),e)}function oQe(t,e){if(t!=null){if(Gfe(t))return tQe(t,e);if(Vfe(t))return rQe(t,e);if(qfe(t))return nQe(t,e);if(Kfe(t))return the(t,e);if(Yfe(t))return iQe(t,e);if(Jfe(t))return sQe(t,e)}throw zfe(t)}function aQe(t,e){return e?oQe(t,e):tS(t)}pD(function(t){return function(e){e===void 0&&(e=null),t(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=e}});function WR(t,e){return eS(function(n,r){var i=0;n.subscribe(O3(r,function(s){r.next(t.call(e,s,i++))}))})}function cQe(t,e,n,r,i,s,o,a){var c=[],l=0,d=0,h=!1,m=function(){h&&!c.length&&!l&&e.complete()},g=function(v){return l<r?y(v):c.push(v)},y=function(v){l++;var w=!1;tS(n(v,d++)).subscribe(O3(e,function(S){e.next(S)},function(){w=!0},void 0,function(){if(w)try{l--;for(var S=function(){var R=c.shift();o||y(R)};c.length&&l<r;)S();m()}catch(R){e.error(R)}}))};return t.subscribe(O3(e,g,function(){h=!0,m()})),function(){}}function nhe(t,e,n){return n===void 0&&(n=1/0),ci(e)?nhe(function(r,i){return WR(function(s,o){return e(r,s,i,o)})(tS(t(r,i)))},n):(typeof e=="number"&&(n=e),eS(function(r,i){return cQe(r,i,t,n)}))}function lQe(t){return nhe($fe,t)}function uQe(){return lQe(1)}function BW(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return uQe()(aQe(t,Hfe(t)))}function YR(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=Hfe(t);return eS(function(r,i){(n?BW(t,r,n):BW(t,r)).subscribe(i)})}var dQe="lk";function rhe(t){return typeof t>"u"?!1:fQe(t)||hQe(t)}function fQe(t){var e;return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&t.hasOwnProperty("track")&&typeof((e=t.publication)==null?void 0:e.track)<"u":!1}function hQe(t){return t?t.hasOwnProperty("participant")&&t.hasOwnProperty("source")&&t.hasOwnProperty("publication")&&typeof t.publication<"u":!1}var pQe=[ue.ConnectionStateChanged,ue.RoomMetadataChanged,ue.ActiveSpeakersChanged,ue.ConnectionQualityChanged,ue.ParticipantConnected,ue.ParticipantDisconnected,ue.ParticipantPermissionsChanged,ue.ParticipantMetadataChanged,ue.ParticipantNameChanged,ue.ParticipantAttributesChanged,ue.TrackMuted,ue.TrackUnmuted,ue.TrackPublished,ue.TrackUnpublished,ue.TrackStreamStateChanged,ue.TrackSubscriptionFailed,ue.TrackSubscriptionPermissionChanged,ue.TrackSubscriptionStatusChanged],mQe=[...pQe,ue.LocalTrackPublished,ue.LocalTrackUnpublished];ce.TrackPublished,ce.TrackUnpublished,ce.TrackMuted,ce.TrackUnmuted,ce.TrackStreamStateChanged,ce.TrackSubscribed,ce.TrackUnsubscribed,ce.TrackSubscriptionPermissionChanged,ce.TrackSubscriptionFailed,ce.LocalTrackPublished,ce.LocalTrackUnpublished;var gQe=[ce.ConnectionQualityChanged,ce.IsSpeakingChanged,ce.ParticipantMetadataChanged,ce.ParticipantPermissionsChanged,ce.TrackMuted,ce.TrackUnmuted,ce.TrackPublished,ce.TrackUnpublished,ce.TrackStreamStateChanged,ce.TrackSubscriptionFailed,ce.TrackSubscriptionPermissionChanged,ce.TrackSubscriptionStatusChanged];[...gQe,ce.LocalTrackPublished,ce.LocalTrackUnpublished];var Af=IJe.getLogger("lk-components-js");Af.setDefaultLevel("WARN");function ihe(t){return typeof t=="object"}function she(t){return Array.isArray(t)&&t.filter(ihe).length>0}function vQe(t){return`${dQe}-${t}`}function yQe(t){const e=gO(t),n=ohe(t.participant).pipe(WR(()=>gO(t)),YR(e));return{className:vQe(t.source===he.Source.Camera||t.source===he.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:n}}function gO(t){if(rhe(t))return t.publication;{const{source:e,name:n,participant:r}=t;if(e&&n)return r.getTrackPublications().find(i=>i.source===e&&i.trackName===n);if(n)return r.getTrackPublicationByName(n);if(e)return r.getTrackPublication(e);throw new Error("At least one of source and name needs to be defined")}}function bQe(t,...e){return new Ao(n=>{const r=()=>{n.next(t)};return e.forEach(i=>{t.on(i,r)}),()=>{e.forEach(i=>{t.off(i,r)})}}).pipe(YR(t))}function _Qe(t,...e){return new Ao(n=>{const r=()=>{n.next(t)};return e.forEach(i=>{t.on(i,r)}),()=>{e.forEach(i=>{t.off(i,r)})}}).pipe(YR(t))}function ohe(t){return _Qe(t,ce.TrackMuted,ce.TrackUnmuted,ce.ParticipantPermissionsChanged,ce.TrackPublished,ce.TrackUnpublished,ce.LocalTrackPublished,ce.LocalTrackUnpublished,ce.MediaDevicesError,ce.TrackSubscriptionStatusChanged).pipe(WR(e=>{const{isMicrophoneEnabled:n,isCameraEnabled:r,isScreenShareEnabled:i}=e,s=e.getTrackPublication(he.Source.Microphone),o=e.getTrackPublication(he.Source.Camera);return{isCameraEnabled:r,isMicrophoneEnabled:n,isScreenShareEnabled:i,cameraTrack:o,microphoneTrack:s,participant:e}}))}function HW(t,e,n=!0){const r=[t.localParticipant,...Array.from(t.remoteParticipants.values())],i=[];return r.forEach(s=>{e.forEach(o=>{const a=Array.from(s.trackPublications.values()).filter(c=>c.source===o&&(!n||c.track)).map(c=>({participant:s,publication:c,source:c.source}));i.push(...a)})}),{trackReferences:i,participants:r}}function SQe(t,e,n){var r,i;const s=(r=n.additionalRoomEvents)!=null?r:mQe,o=(i=n.onlySubscribed)!=null?i:!0,a=Array.from(new Set([ue.ParticipantConnected,ue.ParticipantDisconnected,ue.ConnectionStateChanged,ue.LocalTrackPublished,ue.LocalTrackUnpublished,ue.TrackPublished,ue.TrackUnpublished,ue.TrackSubscriptionStatusChanged,...s]).values());return bQe(t,...a).pipe(WR(c=>{const l=HW(c,e,o);return Af.debug(`TrackReference[] was updated. (length ${l.trackReferences.length})`,l),l}),YR(HW(t,e,o)))}_.createContext(void 0);const EQe=_.createContext(void 0);function wQe(){return _.useContext(EQe)}function ahe(t){const e=wQe(),n=t??e;if(!n)throw new Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return n}_.createContext(void 0);const che=_.createContext(void 0);function CQe(){return _.useContext(che)}function lhe(t){const e=CQe(),n=t??e;if(!n)throw new Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return n}_.createContext(void 0);function uhe(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(n=uhe(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function TQe(){for(var t,e,n=0,r="",i=arguments.length;n<i;n++)(t=arguments[n])&&(e=uhe(t))&&(r&&(r+=" "),r+=e);return r}function RQe(...t){return(...e)=>{for(const n of t)if(typeof n=="function")try{n(...e)}catch(r){console.error(r)}}}function IQe(...t){const e={...t[0]};for(let n=1;n<t.length;n++){const r=t[n];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]=RQe(s,o):(i==="className"||i==="UNSAFE_className")&&typeof s=="string"&&typeof o=="string"?e[i]=TQe(s,o):e[i]=o!==void 0?o:s}}return e}function kQe(t){return t!==void 0}function xQe(...t){return IQe(...t.filter(kQe))}function AQe(t,e){return t==="processor"&&e&&typeof e=="object"&&"name"in e?e.name:t==="e2ee"&&e?"e2ee-enabled":e}function PQe(t={}){const e=lhe(t.room),[n,r]=_.useState(e.localParticipant),[i,s]=_.useState(n.isMicrophoneEnabled),[o,a]=_.useState(n.isCameraEnabled),[c,l]=_.useState(n.isScreenShareEnabled),[d,h]=_.useState(n.lastMicrophoneError),[m,g]=_.useState(n.lastCameraError),[y,v]=_.useState(void 0),[w,S]=_.useState(void 0),R=x=>{a(x.isCameraEnabled),s(x.isMicrophoneEnabled),l(x.isScreenShareEnabled),S(x.cameraTrack),v(x.microphoneTrack),h(x.participant.lastMicrophoneError),g(x.participant.lastCameraError),r(x.participant)};return _.useEffect(()=>{const x=ohe(e.localParticipant).subscribe(R);return()=>x.unsubscribe()},[e]),{isMicrophoneEnabled:i,isScreenShareEnabled:c,isCameraEnabled:o,microphoneTrack:y,cameraTrack:w,lastMicrophoneError:d,lastCameraError:m,localParticipant:n}}function LQe(t=[he.Source.Camera,he.Source.Microphone,he.Source.ScreenShare,he.Source.ScreenShareAudio,he.Source.Unknown],e={}){const n=lhe(e.room),[r,i]=_.useState([]),[s,o]=_.useState([]),a=_.useMemo(()=>t.map(c=>ihe(c)?c.source:c),[JSON.stringify(t)]);return _.useEffect(()=>{const c=SQe(n,a,{additionalRoomEvents:e.updateOnlyOn,onlySubscribed:e.onlySubscribed}).subscribe(({trackReferences:l,participants:d})=>{Af.debug("setting track bundles",l,d),i(l),o(d)});return()=>c.unsubscribe()},[n,JSON.stringify(e.onlySubscribed),JSON.stringify(e.updateOnlyOn),JSON.stringify(t)]),_.useMemo(()=>{if(she(t)){const c=MQe(t,s),l=Array.from(r);return s.forEach(d=>{c.has(d.identity)&&(c.get(d.identity)??[]).forEach(h=>{if(r.find(({participant:g,publication:y})=>d.identity===g.identity&&y.source===h))return;Af.debug(`Add ${h} placeholder for participant ${d.identity}.`);const m={participant:d,source:h};l.push(m)})}),l}else return r},[r,s,t])}function OQe(t,e){const n=new Set(t);for(const r of e)n.delete(r);return n}function MQe(t,e){const n=new Map;if(she(t)){const r=t.filter(i=>i.withPlaceholder).map(i=>i.source);e.forEach(i=>{const s=i.getTrackPublications().map(a=>{var c;return(c=a.track)==null?void 0:c.source}).filter(a=>a!==void 0),o=Array.from(OQe(new Set(r),new Set(s)));o.length>0&&n.set(i.identity,o)})}return n}function dhe(t,e={}){const[n,r]=_.useState(gO(t)),[i,s]=_.useState(n?.isMuted),[o,a]=_.useState(n?.isSubscribed),[c,l]=_.useState(n?.track),[d,h]=_.useState("landscape"),m=_.useRef(),{className:g,trackObserver:y}=_.useMemo(()=>yQe(t),[t.participant.sid??t.participant.identity,t.source,rhe(t)&&t.publication.trackSid]);return _.useEffect(()=>{const v=y.subscribe(w=>{Af.debug("update track",w),r(w),s(w?.isMuted),a(w?.isSubscribed),l(w?.track)});return()=>v?.unsubscribe()},[y]),_.useEffect(()=>{var v,w;return c&&(m.current&&c.detach(m.current),(v=e.element)!=null&&v.current&&!(t.participant.isLocal&&c?.kind==="audio")&&c.attach(e.element.current)),m.current=(w=e.element)==null?void 0:w.current,()=>{m.current&&c?.detach(m.current)}},[c,e.element]),_.useEffect(()=>{var v,w;if(typeof((v=n?.dimensions)==null?void 0:v.width)=="number"&&typeof((w=n?.dimensions)==null?void 0:w.height)=="number"){const S=n.dimensions.width>n.dimensions.height?"landscape":"portrait";h(S)}},[n]),{publication:n,isMuted:i,isSubscribed:o,track:c,elementProps:xQe(e.props,{className:g,"data-lk-local-participant":t.participant.isLocal,"data-lk-source":n?.source,...n?.kind==="video"&&{"data-lk-orientation":d}})}}var e5,VW;function DQe(){if(VW)return e5;VW=1;var t="Expected a function",e=NaN,n="[object Symbol]",r=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,o=/^0o[0-7]+$/i,a=parseInt,c=typeof IE=="object"&&IE&&IE.Object===Object&&IE,l=typeof self=="object"&&self&&self.Object===Object&&self,d=c||l||Function("return this")(),h=Object.prototype,m=h.toString,g=Math.max,y=Math.min,v=function(){return d.Date.now()};function w(I,k,A){var O,D,N,U,$,K,Y=0,G=!1,F=!1,q=!0;if(typeof I!="function")throw new TypeError(t);k=T(k)||0,S(A)&&(G=!!A.leading,F="maxWait"in A,N=F?g(T(A.maxWait)||0,k):N,q="trailing"in A?!!A.trailing:q);function z(_e){var Ie=O,Ue=D;return O=D=void 0,Y=_e,U=I.apply(Ue,Ie),U}function W(_e){return Y=_e,$=setTimeout(ne,k),G?z(_e):U}function V(_e){var Ie=_e-K,Ue=_e-Y,et=k-Ie;return F?y(et,N-Ue):et}function X(_e){var Ie=_e-K,Ue=_e-Y;return K===void 0||Ie>=k||Ie<0||F&&Ue>=N}function ne(){var _e=v();if(X(_e))return fe(_e);$=setTimeout(ne,V(_e))}function fe(_e){return $=void 0,q&&O?z(_e):(O=D=void 0,U)}function ye(){$!==void 0&&clearTimeout($),Y=0,O=K=D=$=void 0}function Ae(){return $===void 0?U:fe(v())}function be(){var _e=v(),Ie=X(_e);if(O=arguments,D=this,K=_e,Ie){if($===void 0)return W(K);if(F)return $=setTimeout(ne,k),z(K)}return $===void 0&&($=setTimeout(ne,k)),U}return be.cancel=ye,be.flush=Ae,be}function S(I){var k=typeof I;return!!I&&(k=="object"||k=="function")}function R(I){return!!I&&typeof I=="object"}function x(I){return typeof I=="symbol"||R(I)&&m.call(I)==n}function T(I){if(typeof I=="number")return I;if(x(I))return e;if(S(I)){var k=typeof I.valueOf=="function"?I.valueOf():I;I=S(k)?k+"":k}if(typeof I!="string")return I===0?I:+I;I=I.replace(r,"");var A=s.test(I);return A||o.test(I)?a(I.slice(2),A?2:8):i.test(I)?e:+I}return e5=w,e5}var NQe=DQe();const qW=Dfe(NQe);function UQe(t){const e=_.useRef(t);e.current=t,_.useEffect(()=>()=>{e.current()},[])}function jQe(t,e=500,n){const r=_.useRef();UQe(()=>{r.current&&r.current.cancel()});const i=_.useMemo(()=>{const s=qW(t,e,n),o=(...a)=>s(...a);return o.cancel=()=>{s.cancel()},o.isPending=()=>!!r.current,o.flush=()=>s.flush(),o},[t,e,n]);return _.useEffect(()=>{r.current=qW(t,e,n)},[t,e,n]),i}function FQe(t,e,n){const r=(l,d)=>l===d,i=t instanceof Function?t():t,[s,o]=_.useState(i),a=_.useRef(i),c=jQe(o,e,n);return r(a.current,i)||(c(i),a.current=i),[s,c]}function $Qe({threshold:t=0,root:e=null,rootMargin:n="0%",freezeOnceVisible:r=!1,initialIsIntersecting:i=!1,onChange:s}={}){var o;const[a,c]=_.useState(null),[l,d]=_.useState(()=>({isIntersecting:i,entry:void 0})),h=_.useRef();h.current=s;const m=((o=l.entry)==null?void 0:o.isIntersecting)&&r;_.useEffect(()=>{if(!a||!("IntersectionObserver"in window)||m)return;const v=new IntersectionObserver(w=>{const S=Array.isArray(v.thresholds)?v.thresholds:[v.thresholds];w.forEach(R=>{const x=R.isIntersecting&&S.some(T=>R.intersectionRatio>=T);d({isIntersecting:x,entry:R}),h.current&&h.current(x,R)})},{threshold:t,root:e,rootMargin:n});return v.observe(a),()=>{v.disconnect()}},[a,JSON.stringify(t),e,n,m,r]);const g=_.useRef(null);_.useEffect(()=>{var v;!a&&(v=l.entry)!=null&&v.target&&!r&&!m&&g.current!==l.entry.target&&(g.current=l.entry.target,d({isIntersecting:i,entry:void 0}))},[a,l.entry,r,m,i]);const y=[c,!!l.isIntersecting,l.entry];return y.ref=y[0],y.isIntersecting=y[1],y.entry=y[2],y}const BQe=_.forwardRef(function({onTrackClick:t,onClick:e,onSubscriptionStatusChanged:n,trackRef:r,manageSubscription:i,...s},o){const a=ahe(r),c=_.useRef(null);_.useImperativeHandle(o,()=>c.current);const l=$Qe({root:c.current}),[d]=FQe(l,3e3);_.useEffect(()=>{i&&a.publication instanceof xC&&d?.isIntersecting===!1&&l?.isIntersecting===!1&&a.publication.setSubscribed(!1)},[d,a,i]),_.useEffect(()=>{i&&a.publication instanceof xC&&l?.isIntersecting===!0&&a.publication.setSubscribed(!0)},[l,a,i]);const{elementProps:h,publication:m,isSubscribed:g}=dhe(a,{element:c,props:s});_.useEffect(()=>{n?.(!!g)},[g,n]);const y=v=>{e?.(v),t?.({participant:a?.participant,track:m})};return _.createElement("video",{ref:c,...h,muted:!0,onClick:y})}),HQe=_.forwardRef(function({trackRef:t,onSubscriptionStatusChanged:e,volume:n,...r},i){const s=ahe(t),o=_.useRef(null);_.useImperativeHandle(i,()=>o.current);const{elementProps:a,isSubscribed:c,track:l,publication:d}=dhe(s,{element:o,props:r});return _.useEffect(()=>{e?.(!!c)},[c,e]),_.useEffect(()=>{l===void 0||n===void 0||(l instanceof kee?l.setVolume(n):Af.warn("Volume can only be set on remote audio tracks."))},[n,l]),_.useEffect(()=>{d===void 0||r.muted===void 0||(d instanceof xC?d.setEnabled(!r.muted):Af.warn("Can only call setEnabled on remote track publications."))},[r.muted,d,l]),_.createElement("audio",{ref:o,...a})});function VQe(t,e){const[n,r]=_.useState(),i=_.useMemo(()=>new ms,[]);return _.useEffect(()=>{let s=!1,o=[];return i.lock().then(async a=>{try{(t.audio||t.video)&&(o=await v_(t),s?o.forEach(c=>c.stop()):r(o))}catch(c){e&&c instanceof Error?e(c):Af.error(c)}finally{a()}}),()=>{s=!0,o.forEach(a=>{a.stop()})}},[JSON.stringify(t,AQe),e,i]),n}const qQe="_inRoom_110p2_8",GQe="_header_110p2_17",KQe="_filler_110p2_29",zQe="_footer_110p2_34",WQe="_hidden_110p2_53",YQe="_overlay_110p2_57",XQe="_logo_110p2_75",JQe="_buttons_110p2_84",QQe="_layout_110p2_91",ZQe="_shareScreen_110p2_111",eZe="_invite_110p2_123",tZe="_raiseHand_110p2_124",nZe="_fixedGrid_110p2_147",rZe="_scrollingGrid_110p2_153",iZe="_tile_110p2_172",sZe="_maximised_110p2_177",gr={inRoom:qQe,header:GQe,filler:KQe,footer:zQe,hidden:WQe,overlay:YQe,logo:XQe,buttons:JQe,layout:QQe,shareScreen:ZQe,invite:eZe,raiseHand:tZe,fixedGrid:nZe,scrollingGrid:rZe,tile:iZe,maximised:sZe},oZe="_content_1cy0f_8",aZe="_wait_1cy0f_19",cZe="_join_1cy0f_32",ty={content:oZe,wait:aZe,join:cZe};function GW(t,e){let n;return(...r)=>{window.clearTimeout(n),n=window.setTimeout(()=>t(...r),e)}}function Zy({debounce:t,scroll:e,polyfill:n,offsetSize:r}={debounce:0,scroll:!1,offsetSize:!1}){const i=n||(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}),c=t?typeof t=="number"?t:t.scroll:null,l=t?typeof t=="number"?t:t.resize:null,d=_.useRef(!1);_.useEffect(()=>(d.current=!0,()=>void(d.current=!1)));const[h,m,g]=_.useMemo(()=>{const S=()=>{if(!a.current.element)return;const{left:R,top:x,width:T,height:I,bottom:k,right:A,x:O,y:D}=a.current.element.getBoundingClientRect(),N={left:R,top:x,width:T,height:I,bottom:k,right:A,x:O,y:D};a.current.element instanceof HTMLElement&&r&&(N.height=a.current.element.offsetHeight,N.width=a.current.element.offsetWidth),Object.freeze(N),d.current&&!fZe(a.current.lastBounds,N)&&o(a.current.lastBounds=N)};return[S,l?GW(S,l):S,c?GW(S,c):S]},[o,r,c,l]);function y(){a.current.scrollContainers&&(a.current.scrollContainers.forEach(S=>S.removeEventListener("scroll",g,!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 v(){a.current.element&&(a.current.resizeObserver=new i(g),a.current.resizeObserver.observe(a.current.element),e&&a.current.scrollContainers&&a.current.scrollContainers.forEach(S=>S.addEventListener("scroll",g,{capture:!0,passive:!0})),a.current.orientationHandler=()=>{g()},"orientation"in screen&&"addEventListener"in screen.orientation?screen.orientation.addEventListener("change",a.current.orientationHandler):"onorientationchange"in window&&window.addEventListener("orientationchange",a.current.orientationHandler))}const w=S=>{!S||S===a.current.element||(y(),a.current.element=S,a.current.scrollContainers=fhe(S),v())};return uZe(g,!!e),lZe(m),_.useEffect(()=>{y(),v()},[e,g,m]),_.useEffect(()=>y,[]),[w,s,h]}function lZe(t){_.useEffect(()=>{const e=t;return window.addEventListener("resize",e),()=>void window.removeEventListener("resize",e)},[t])}function uZe(t,e){_.useEffect(()=>{if(e){const n=t;return window.addEventListener("scroll",n,{capture:!0,passive:!0}),()=>void window.removeEventListener("scroll",n,!0)}},[t,e])}function fhe(t){const e=[];if(!t||t===document.body)return e;const{overflow:n,overflowX:r,overflowY:i}=window.getComputedStyle(t);return[n,r,i].some(s=>s==="auto"||s==="scroll")&&e.push(t),[...e,...fhe(t.parentElement)]}const dZe=["x","y","top","bottom","left","right","width","height"],fZe=(t,e)=>dZe.every(n=>t[n]===e[n]),hZe="_loading_14w06_8",pZe={loading:hZe},mZe=({size:t,loading:e,...n})=>E.jsxs("div",{children:[e&&E.jsx("div",{className:pZe.loading,children:E.jsx(AMe,{size:t/3})}),E.jsx(Op,{size:t,...n})]}),gZe="_preview_1jjvr_8",vZe="_mirror_1jjvr_24",yZe="_cameraStarting_1jjvr_28",bZe="_avatarContainer_1jjvr_39",_Ze="_buttonBar_1jjvr_51",ny={preview:gZe,mirror:vZe,cameraStarting:yZe,avatarContainer:bZe,buttonBar:_Ze},SZe=({matrixInfo:t,muteStates:e,videoTrack:n,children:r})=>{const{t:i}=We(),[s,o]=Zy(),a=_.useRef(null);_.useEffect(()=>(a.current&&n?.attach(a.current),()=>{n?.detach()}),[n]);const c=_.useMemo(()=>e.video.enabled&&!n,[e.video.enabled,n]);return E.jsxs("div",{className:Oe(ny.preview),ref:s,children:[E.jsx("video",{className:n&&rP(n).facingMode==="user"?ny.mirror:void 0,ref:a,muted:!0,playsInline:!0,tabIndex:-1,disablePictureInPicture:!0}),(!e.video.enabled||c)&&E.jsx(E.Fragment,{children:E.jsxs("div",{className:ny.avatarContainer,children:[c&&E.jsx("div",{className:ny.cameraStarting,role:"status",children:i("video_tile.camera_starting")}),E.jsx(mZe,{id:t.userId,name:t.displayName,size:Math.min(o.width,o.height)/2,src:t.avatarUrl,loading:c})]})}),E.jsx("div",{className:ny.buttonBar,children:r})]})},hhe=t=>{const{t:e}=We();return E.jsx(Bt,{kind:"secondary",size:"sm",Icon:D8e,...t,children:e("action.invite")})};function ic(t){const e=_.useRef(void 0);return e.current??={value:t()},e.current.value}function Pf(t){const e=_.useRef(t);return e.current=t,e}const phe=({client:t,matrixInfo:e,muteStates:n,onEnter:r,enterLabel:i,confineToRoom:s,hideHeader:o,participantCount:a,onShareClick:c,waitingForInvite:l})=>{_.useEffect(()=>(M.info("[Lifecycle] GroupCallView Component mounted"),()=>{M.info("[Lifecycle] GroupCallView Component unmounted")}),[]);const{t:d}=We();Q_(e.roomName);const h=_.useCallback(()=>n.audio.setEnabled?.(q=>!q),[n]),m=_.useCallback(()=>n.video.setEnabled?.(q=>!q),[n]),[g,y]=_.useState(!1),[v,w]=_.useState(lD),S=_.useCallback(()=>y(!0),[y]),R=_.useCallback(()=>y(!1),[y]),x=hl(),T=_.useCallback(()=>{x("/")?.catch(q=>{M.error("Failed to navigate to /",q)})},[x]),I=YT("(max-height: 500px)"),k=!s&&E.jsx(il,{className:ty.recents,to:"/",children:d("lobby.leave_button")}),A=Wu(),O=ai(A.videoInput.selected$)?.id,D=ic(()=>n.audio.enabled&&{deviceId:Bw(A.audioInput.selected$)?.id}),{processor:N}=GR(),U=ic(()=>N),$=_.useMemo(()=>({audio:Object.assign({},D),video:n.video.enabled&&{deviceId:O,processor:U}}),[D,n.video.enabled,O,U]),K=Pf(n),Y=_.useCallback(q=>{M.error("Error while creating preview Tracks:",q),K.current.audio.setEnabled?.(!1),K.current.video.setEnabled?.(!1)},[K]),G=VQe($,Y),F=_.useMemo(()=>G?.find(q=>q.kind===he.Kind.Video)??null,[G]);return _.useEffect(()=>{F&&O===void 0&&A.requestDeviceNames()},[A,O,F]),Sfe(F),E.jsxs(E.Fragment,{children:[E.jsxs("div",{className:Oe(ty.room,gr.inRoom),children:[!o&&E.jsxs(qu,{children:[E.jsx(jf,{children:E.jsx(vae,{id:e.roomId,name:e.roomName,avatarUrl:e.roomAvatar,encrypted:e.e2eeSystem.kind!==hn.NONE,participantCount:a})}),E.jsx(Ff,{children:c!==null&&E.jsx(hhe,{onClick:c})})]}),E.jsxs("div",{className:ty.content,children:[E.jsx(SZe,{matrixInfo:e,muteStates:n,videoTrack:F,children:E.jsx(Bt,{className:Oe(ty.join,{[ty.wait]:l}),size:l?"sm":"lg",onClick:()=>{l||r()},"data-testid":"lobby_joinCall",children:i??d("lobby.join_button")})}),!I&&k]}),E.jsxs("div",{className:gr.footer,children:[I&&k,E.jsxs("div",{className:gr.buttons,children:[E.jsx(Ule,{muted:!n.audio.enabled,onClick:h,disabled:n.audio.setEnabled===null}),E.jsx(jle,{muted:!n.video.enabled,onClick:m,disabled:n.video.setEnabled===null}),E.jsx($le,{onClick:S}),!s&&E.jsx(Fle,{onClick:T})]})]})]}),t&&E.jsx(uD,{client:t,open:g,onDismiss:R,tab:v,onTabChange:w})]})},EZe="_headline_1em2y_8",wZe="_callEndedContent_1em2y_15",CZe="_callEndedButton_1em2y_35",TZe="_submitButton_1em2y_40",RZe="_container_1em2y_47",IZe="_main_1em2y_55",kZe="_footer_1em2y_72",Td={headline:EZe,callEndedContent:wZe,callEndedButton:CZe,submitButton:TZe,container:RZe,main:IZe,footer:kZe},xZe="_starIcon_1m09w_8",AZe="_starRating_1m09w_12",PZe="_inputContainer_1m09w_18",LZe="_hideElement_1m09w_22",ry={starIcon:xZe,starRating:AZe,inputContainer:PZe,hideElement:LZe},OZe=(t,e)=>_.createElement("svg",{width:28,height:26,viewBox:"0 0 28 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),MZe=_.forwardRef(OZe),DZe=(t,e)=>_.createElement("svg",{width:28,height:26,viewBox:"0 0 28 26",fill:"none",xmlns:"http://www.w3.org/2000/svg",ref:e,...t},_.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"})),NZe=_.forwardRef(DZe);function UZe({starCount:t,onChange:e,required:n}){const[r,i]=_.useState(0),[s,o]=_.useState(0),{t:a}=We();return E.jsx("div",{className:ry.starRating,children:[...Array(t)].map((c,l)=>(l+=1,E.jsxs("div",{className:ry.inputContainer,onMouseEnter:()=>o(l),onMouseLeave:()=>o(r),children:[E.jsx("input",{className:ry.hideElement,type:"radio",id:"starInput"+String(l),value:String(l)+"Star",name:"star rating",onChange:d=>{i(l),e(l)},required:!0}),E.jsx("label",{className:ry.hideElement,id:"starInvisibleLabel"+String(l),htmlFor:"starInput"+String(l),children:a("star_rating_input_label",{count:l})}),E.jsx("label",{className:ry.starIcon,id:"starIcon"+String(l),htmlFor:"starInput"+String(l),children:l<=(s||r)?E.jsx(MZe,{}):E.jsx(NZe,{})})]},l)))})}const jZe=({client:t,isPasswordlessUser:e,hideHeader:n,confineToRoom:r,endedCallId:i})=>{const{t:s}=We(),o=hl(),{displayName:a}=V_(t),[c,l]=_.useState(!1),[d,h]=_.useState(0),[m,g]=_.useState(!1),[y,v]=_.useState(!1),w=_.useCallback(x=>{x.preventDefault();const I=new FormData(x.target).get("feedbackText");Ut.instance.eventQualitySurvey.track(i,I,d),g(!0),setTimeout(()=>{v(!0),setTimeout(()=>{e?l(!0):r||o("/")?.catch(k=>{M.error("Failed to navigate to /",k)})},1e3)},1e3)},[i,o,e,r,d]),S=e&&E.jsxs("div",{className:Td.callEndedContent,children:[E.jsxs(Ys,{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(q8,{className:Td.callEndedButton,to:"/register",children:s("call_ended_view.create_account_button")})]}),R=E.jsxs("div",{className:Td.callEndedContent,children:[E.jsx(Ys,{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:w,children:[E.jsx(yt,{children:E.jsx(UZe,{starCount:5,onChange:h,required:!0})}),E.jsx(yt,{children:E.jsx(Tn,{className:Yle.feedback,id:"feedbackText",name:"feedbackText",label:s("settings.feedback_tab_description_label"),placeholder:s("settings.feedback_tab_description_label"),type:"textarea"})})," ",E.jsx(yt,{children:y?E.jsx(Ys,{i18nKey:"call_ended_view.feedback_done",children:E.jsx("p",{children:"Thanks for your feedback!"})}):E.jsx(Bt,{type:"submit",className:Td.submitButton,"data-testid":"home_go",children:s(m?"submitting":"action.submit")})})]})]});return E.jsxs(E.Fragment,{children:[!n&&E.jsxs(qu,{children:[E.jsx(jf,{children:!r&&E.jsx(fp,{})}),E.jsx(Ff,{})]}),E.jsxs("div",{className:Td.container,children:[E.jsxs("main",{className:Td.main,children:[E.jsx(gl,{size:"xl",weight:"semibold",className:Td.headline,children:c?s("call_ended_view.headline",{displayName:a}):s("call_ended_view.headline",{displayName:a})+`
@@ -346,6 +346,6 @@ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},N5=n,N
346
346
  The chosen QR Code version cannot contain this amount of data.
347
347
  Minimum version required to store current data is: `+U+`.
348
348
  `);const $=x(A,O,N),K=t.getSymbolSize(A),Y=new r(K);return g(Y,A),y(Y),v(Y,A),S(Y,O,0),A>=7&&w(Y,A),R(Y,$),isNaN(D)&&(D=o.getBestMask(Y,S.bind(null,Y,O))),o.applyMask(D,Y),S(Y,O,D),{modules:Y,version:A,errorCorrectionLevel:O,maskPattern:D,segments:N}}return b5.create=function(A,O){if(typeof A>"u"||A==="")throw new Error("No input text");let D=e.M,N,U;return typeof O<"u"&&(D=e.from(O.errorCorrectionLevel,e.M),N=l.from(O.version),U=o.from(O.maskPattern),O.toSJISFunc&&t.setToSJISFunction(O.toSJISFunc)),I(A,N,D,U)},b5}var j5={},F5={},xX;function Mpe(){return xX||(xX=1,function(t){function e(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(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("")}}t.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||{}}},t.getScale=function(r,i){return i.width&&i.width>=r+i.margin*2?i.width/(r+i.margin*2):i.scale},t.getImageWidth=function(r,i){const s=t.getScale(r,i);return Math.floor((r+i.margin*2)*s)},t.qrToImageData=function(r,i,s){const o=i.modules.size,a=i.modules.data,c=t.getScale(o,s),l=Math.floor((o+s.margin*2)*c),d=s.margin*c,h=[s.color.light,s.color.dark];for(let m=0;m<l;m++)for(let g=0;g<l;g++){let y=(m*l+g)*4,v=s.color.light;if(m>=d&&g>=d&&m<l-d&&g<l-d){const w=Math.floor((m-d)/c),S=Math.floor((g-d)/c);v=h[a[w*o+S]?1:0]}r[y++]=v.r,r[y++]=v.g,r[y++]=v.b,r[y]=v.a}}}(F5)),F5}var AX;function not(){return AX||(AX=1,function(t){const e=Mpe();function n(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")}}t.render=function(s,o,a){let c=a,l=o;typeof c>"u"&&(!o||!o.getContext)&&(c=o,o=void 0),o||(l=r()),c=e.getOptions(c);const d=e.getImageWidth(s.modules.size,c),h=l.getContext("2d"),m=h.createImageData(d,d);return e.qrToImageData(m.data,s,c),n(h,l,d),h.putImageData(m,0,0),l},t.renderToDataURL=function(s,o,a){let c=a;typeof c>"u"&&(!o||!o.getContext)&&(c=o,o=void 0),c||(c={});const l=t.render(s,o,c),d=c.type||"image/png",h=c.rendererOpts||{};return l.toDataURL(d,h.quality)}}(j5)),j5}var $5={},PX;function rot(){if(PX)return $5;PX=1;const t=Mpe();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 n(i,s,o){let a=i+s;return typeof o<"u"&&(a+=" "+o),a}function r(i,s,o){let a="",c=0,l=!1,d=0;for(let h=0;h<i.length;h++){const m=Math.floor(h%s),g=Math.floor(h/s);!m&&!l&&(l=!0),i[h]?(d++,h>0&&m>0&&i[h-1]||(a+=l?n("M",m+o,.5+g+o):n("m",c,0),c=0,l=!1),m+1<s&&i[h+1]||(a+=n("h",d),d=0)):c++}return a}return $5.render=function(s,o,a){const c=t.getOptions(o),l=s.modules.size,d=s.modules.data,h=l+c.margin*2,m=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",g="<path "+e(c.color.dark,"stroke")+' d="'+r(d,l,c.margin)+'"/>',y='viewBox="0 0 '+h+" "+h+'"',w='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+y+' shape-rendering="crispEdges">'+m+g+`</svg>
349
- `;return typeof a=="function"&&a(null,w),w},$5}var LX;function iot(){if(LX)return Xm;LX=1;const t=jst(),e=tot(),n=not(),r=rot();function i(s,o,a,c,l){const d=[].slice.call(arguments,1),h=d.length,m=typeof d[h-1]=="function";if(!m&&!t())throw new Error("Callback required as last argument");if(m){if(h<2)throw new Error("Too few arguments provided");h===2?(l=a,a=o,o=c=void 0):h===3&&(o.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=o,o=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=o,o=c=void 0):h===2&&!o.getContext&&(c=a,a=o,o=void 0),new Promise(function(g,y){try{const v=e.create(a,c);g(s(v,o,c))}catch(v){y(v)}})}try{const g=e.create(a,c);l(null,s(g,o,c))}catch(g){l(g)}}return Xm.create=e.create,Xm.toCanvas=i.bind(null,n.render),Xm.toDataURL=i.bind(null,n.renderToDataURL),Xm.toString=i.bind(null,function(s,o,a){return r.render(s,a)}),Xm}var sot=iot();const oot="_qrCode_h54ia_8",aot={qrCode:oot},cot=({data:t,className:e})=>{const[n,r]=_.useState(null);return _.useEffect(()=>{let i=!1;return sot.toDataURL(t,{errorCorrectionLevel:"L"}).then(s=>{i||r(s)}).catch(s=>{i||r(null)}),()=>{i=!0}},[t]),E.jsx("div",{className:Oe(aot.qrCode,e),children:n&&E.jsx("img",{src:n,alt:Po("qr_code")})})},lot=({room:t,open:e,onDismiss:n})=>{const{t:r}=We(),i=X_(t.roomId),s=_.useMemo(()=>xfe(t.roomId,i,t.name),[i,t.name,t.roomId]),[o,a]=_.useState(!1),c=_.useCallback(()=>a(!1),[a]),l=_.useCallback(d=>{d.stopPropagation(),Mst(s),n(),a(!0)},[s,n]);return E.jsxs(E.Fragment,{children:[E.jsxs(Up,{title:r("invite_modal.title"),open:e,onDismiss:n,children:[E.jsx(cot,{className:v5.qrCode,data:s}),E.jsx(an,{className:v5.url,size:"sm",weight:"semibold",children:s}),E.jsx(Bt,{className:v5.button,Icon:E8e,onClick:l,"data-testid":"modal_inviteLink",children:r("action.copy_link")})]}),E.jsx(xpe,{open:o,onDismiss:c,autoDismiss:2e3,Icon:foe,children:r("invite_modal.link_copied_toast")})]})},uot=({error:t,recoveryActionHandler:e,widget:n})=>{const{t:r}=We();let i;switch(t.category){case Jw.CONFIGURATION_ISSUE:i=S8e;break;case Jw.NETWORK_CONNECTIVITY:i=R8e;break;case Jw.CLIENT_CONFIGURATION:i=V8e;break;default:i=PT}const s=[];return t instanceof OD&&s.push({label:r("call_ended_view.reconnect_button"),onClick:()=>void e("reconnect")}),E.jsx(qg,{children:E.jsxs(Kb,{Icon:i,title:t.localisedTitle,rageshake:t.code==rpe.UNKNOWN_ERROR,widget:n,children:[E.jsx("p",{children:t.localisedMessage??E.jsx(Ys,{i18nKey:"error.unexpected_ec_error",components:[E.jsx("b",{}),E.jsx("code",{})],values:{errorCode:t.code}})}),s&&s.map((o,a)=>E.jsx(Bt,{kind:"secondary",onClick:o.onClick,children:o.label},`action${a}`))]})})},dot=({recoveryActionHandler:t,onError:e,children:n,widget:r})=>{const i=_.useCallback(({error:s,resetError:o})=>{const a=s instanceof yl?s:new MD(s instanceof Error?s:new Error);return E.jsx(uot,{widget:r??null,error:a,resetError:o,recoveryActionHandler:async c=>{await t(c),o()}})},[t,r]);return E.jsx(AT,{fallback:i,onError:s=>e?.(s),children:n})},fot=({client:t,isPasswordlessUser:e,confineToRoom:n,preload:r,skipLobby:i,header:s,rtcSession:o,isJoined:a,muteStates:c,widget:l})=>{const[d,h]=_.useState(null),m=G8(o),g=Qe(kpe),y=Pf(a4({sounds:Ipe,latencyHint:"interactive",muted:g}));_.useEffect(()=>{m.length>=_st&&c.audio.setEnabled?.(!1)},[]),_.useEffect(()=>{a&&o.updateCallIntent(c.video.enabled?"video":"audio")},[o,a,c.video.enabled]),_.useEffect(()=>(M.info("[Lifecycle] GroupCallView Component mounted"),()=>{M.info("[Lifecycle] GroupCallView Component unmounted")}),[]),_.useEffect(()=>(document.body.classList.add("no-scroll-body"),()=>{document.body.classList.remove("no-scroll-body")}),[]),_.useEffect(()=>(window.rtcSession=o,()=>{delete window.rtcSession}),[o]),Hle(o,ei.MembershipManagerError,Ie=>h(new OD)),_.useEffect(()=>{t.getRoom(o.room.roomId)!==o.room&&M.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.`)},[t,o.room]);const v=o.room,{displayName:w,avatarUrl:S}=V_(t),R=xst(v),x=kst(v),{perParticipantE2EE:T,returnToLobby:I,password:k}=no(),A=X_(v.roomId),[O]=Gn(Ole),[D]=Gn(V8);_.useEffect(()=>{k&&Cfe(v.roomId,k)},[k,v.roomId]),Q_(R),sst(R);const N=_.useMemo(()=>({userId:t.getUserId(),displayName:w,avatarUrl:S,roomId:v.roomId,roomName:R,roomAlias:v.getCanonicalAlias(),roomAvatar:x,e2eeSystem:A}),[t,w,S,R,v,x,A]),U=_.useMemo(()=>new Set(m.map(Ie=>Ie.sender)).size,[m]),$=Wu(),K=Pf(c),Y=_.useCallback(async Ie=>{try{await Rst(Ie,T,O,D)}catch(Ue){if(Ue instanceof yl)h(Ue);else{M.error("Unknown Error while entering RTC session",Ue);const et=new MD(Ue instanceof Error?Ue:new Error("Unknown error",{cause:Ue}));h(et)}}},[T,D,O]);_.useEffect(()=>{const Ie=async({audioInput:Ue,videoInput:et})=>{const ln=await xu.getLocalDevices(void 0,!0);if(Ue){const Bn=KW(Ue,"audioinput",ln);Bn?(M.debug(`Found audio input ID ${Bn} for name ${Ue}`),$.audioInput.select(Bn)):(M.warn("Unknown audio input: "+Ue),K.current.audio.setEnabled?.(!1))}if(et){const Bn=KW(et,"videoinput",ln);Bn?(M.debug(`Found video input ID ${Bn} for name ${et}`),$.videoInput.select(Bn)):(M.warn("Unknown video input: "+et),K.current.video.setEnabled?.(!1))}};if(i)if(l&&r){const Ue=et=>{(async()=>{await Ie(et.detail.data),await Y(o),l.api.transport.reply(et.detail,{})})().catch(ln=>{M.error("Error joining RTC session on preload",ln)})};return l.lazyActions.on(Ri.JoinCall,Ue),()=>{l.lazyActions.off(Ri.JoinCall,Ue)}}else(async()=>{await Y(o)})().catch(Ue=>{M.error("Error joining RTC session immediately",Ue)})},[l,o,r,i,T,$,K,Y,O]);const[G,F]=_.useState(!1),q=hl(),z=_.useCallback((Ie="user",Ue="left")=>{const et=y.current?.playSound(Ue),ln=!!l;F(!0);const Bn=new Promise(Mn=>{Ut.instance.eventCallEnded.track(v.roomId,o.memberships.length,ln,o),window.setTimeout(Mn,10)});nX(o,Ie,Promise.all([et,Bn])).then(async()=>{!e&&!n&&!Ut.instance.isEnabled()&&await q("/")}).catch(Mn=>{M.error("Error leaving RTC session",Mn)})},[y,l,o,v.roomId,e,n,q]);_.useEffect(()=>{if(l&&a){l.api.setAlwaysOnScreen(!0).catch(Ue=>{M.error("Error calling setAlwaysOnScreen(true)",Ue)});const Ie=Ue=>{l.api.transport.reply(Ue.detail,{}),nX(o,"user").catch(et=>{M.error("Failed to leave RTC session",et)})};return l.lazyActions.once(Ri.HangupCall,Ie),()=>{l.lazyActions.off(Ri.HangupCall,Ie)}}},[l,a,o]);const W=Ast(v),[V,X]=_.useState(!1),ne=_.useCallback(()=>X(!1),[X]),fe=_.useCallback(()=>X(!0),[X]),ye=W===ef.Public?fe:null;if(!dee()&&A.kind!==hn.NONE)throw new unt;const Ae=E.jsx(lot,{room:v,open:V,onDismiss:ne}),be=E.jsxs(E.Fragment,{children:[Ae,E.jsx(phe,{client:t,matrixInfo:N,muteStates:c,onEnter:()=>void Y(o),confineToRoom:n,hideHeader:s===Nb.None,participantCount:U,onShareClick:ye})]});let _e;if(d){const Ie=()=>{throw d};_e=E.jsx(Ie,{})}else a?_e=E.jsxs(E.Fragment,{children:[Ae,E.jsx(yst,{client:t,matrixInfo:N,rtcSession:o,matrixRoom:v,onLeave:z,header:s,muteStates:c,e2eeSystem:A,onShareClick:ye})]}):G&&l===null?e||Ut.instance.isEnabled()&&l===null?_e=E.jsx(jZe,{endedCallId:o.room.roomId,client:t,isPasswordlessUser:e,hideHeader:s===Nb.None,confineToRoom:n}):_e=null:G&&l!==null?_e=I?be:null:r||i?_e=null:_e=be;return E.jsx(dot,{widget:l,recoveryActionHandler:async Ie=>{h(null),Ie=="reconnect"&&(F(!1),await Y(o).catch(Ue=>{M.error("Error re-entering RTC session",Ue)}))},onError:()=>{o.isJoined()&&z("error")},children:_e})},hot="_modal_1tnec_8",pot={modal:hot},mot=({roomId:t})=>{const{t:e}=We(),[n,r]=_.useState(!0),i=_.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[r]),s=X_(t);s.kind===hn.NONE&&M.error("Generating app redirect URL for encrypted room but don't have key available!");const o=_.useMemo(()=>{const a=new URL(t===null?window.location.href:xfe(t,s));a.hash=Sje(a.hash,l=>(l.set("appPrompt","false"),l.set("confineToRoom","true"),l));const c=new URL("io.element.call:/");return c.searchParams.set("url",a.toString()),c.toString()},[s,t]);return E.jsxs(Up,{className:pot.modal,title:e("app_selection_modal.title"),open:n,children:[E.jsx(an,{size:"md",weight:"semibold",children:e("app_selection_modal.text")}),E.jsx(Bt,{kind:"secondary",onClick:i,children:e("app_selection_modal.continue_in_browser")}),E.jsx(Bt,{as:"a",href:o,Icon:Woe,children:e("app_selection_modal.open_in_app")})]})},got=3,vot=3e3;async function Dpe(t,e=0,...n){try{return await t.joinRoom(...n)}catch(r){if(r instanceof tr&&r.errcode==="M_FORBIDDEN"&&e<got)return await new Promise(i=>setTimeout(i,vot)),Dpe(t,e+1,...n);throw r}}class eC extends Error{constructor(e,n,r,i){super(n),this.icon=e,this.messageBody=r,this.reason=i}}const yot=(t,e,n)=>{const[r,i]=_.useState({kind:"loading"}),s=_.useRef(void 0),{t:o}=We(),a=_.useCallback(()=>new eC(v8e,o("group_call_loader.banned_heading"),o("group_call_loader.banned_body"),d()),[o]),c=_.useCallback(()=>new eC(LT,o("group_call_loader.knock_reject_heading"),o("group_call_loader.knock_reject_body"),d()),[o]),l=_.useCallback(()=>new eC(Ooe,o("group_call_loader.call_ended_heading"),o("group_call_loader.call_ended_body"),d()),[o]),d=()=>s.current?.currentState.getStateEvents(Z.RoomMember,s.current?.myUserId)?.getContent().reason;return _.useEffect(()=>{if(!t||!e)return;const h=async S=>{let R=null;const x=await t.getRoomIdForAlias(S.toLowerCase());return M.info(`${S} resolved to ${x.room_id}`),R=t.getRoom(x.room_id),R?M.info(`Already in room ${x.room_id}, not rejoining.`):(M.info(`Room ${x.room_id} not found, joining.`),R=await t.joinRoom(x.room_id,{viaServers:x.servers})),R},m=async(S,R,x)=>(await t.knockRoom(S,{viaServers:R}),x(),await new Promise((T,I)=>{t.on(ke.MyMembership,(k,A,O)=>{S===k.roomId&&(s.current=k,A===Be.Invite&&O===Be.Knock&&Dpe(t,0,k.roomId,{viaServers:R}).then(D=>{M.log("Auto-joined %s",D.roomId),T(D)},I),A===Be.Ban&&I(a()),A===Be.Leave&&I(c()))})})),g=async()=>{let S=null;if(e[0]==="#")S=await h(e),s.current=S;else{const R=e;S=t.getRoom(R),s.current=S??void 0;const x=S?.getMyMembership();if(x===Be.Join)return S;if(ut)throw new Error("Room not found. The widget-api did not pass over the relevant room events/information.");if(x===Be.Ban)throw a();if(x===Be.Invite)S=await t.joinRoom(R,{viaServers:n});else{let T;try{T=await t.getRoomSummary(R,n)}catch(I){M.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(T===void 0||T.join_rule===ef.Public)S=await t.joinRoom(R,{viaServers:n});else if(T.join_rule===ef.Knock){const I=T;let k=()=>{};const A=new Promise(O=>{I.membership!==Be.Knock?k=O:O()});i({kind:"canKnock",roomSummary:I,knock:k}),await A,S=await m(T.room_id,n,()=>i({kind:"waitForInvite",roomSummary:I}))}else throw new Error(`Room ${T.room_id} is not joinable. This likely means, that the conference owner has changed the room settings to private.`)}}return M.info(`Joined ${e}, waiting room to be ready for group calls`),await t.waitUntilRoomReadyForGroupCalls(S.roomId),M.info(`${e}, is ready for group calls`),S},y=async()=>{const S=await g();return s.current=S,M.debug(`Fetched / joined room ${e}`),t.matrixRTC.getRoomSession(S)},v=async()=>{t.getSyncState()!==Gt.Syncing&&(M.debug("useLoadGroupCall: waiting for client to start syncing..."),await new Promise(S=>{const R=()=>{if(t.getSyncState()===Gt.Syncing)return t.off(Le.Sync,R),S()};t.on(Le.Sync,R)}),M.debug("useLoadGroupCall: client is now syncing."))},w=async()=>{await new Promise((S,R)=>{t.on(ke.MyMembership,(x,T)=>{T===Be.Leave&&R(l()),T===Be.Ban&&R(a())})})};r.kind==="loading"&&(M.log("Start loading group call"),v().then(y).then(S=>i({kind:"loaded",rtcSession:S})).then(w).catch(S=>i({kind:"failed",error:S})))},[a,t,c,l,e,r,o,n]),r},bot=new On;function _ot(t){const e=gp(t??bot,ei.JoinStateChanged,_.useCallback(()=>t?.isJoined()??!1,[t]));return _.useEffect(()=>{M.info(`Session in room ${t?.room.roomId} changed to ${e?"joined":"left"}`)},[t,e]),e}const Sot=()=>{const{confineToRoom:t,appPrompt:e,preload:n,header:r,displayName:i,skipLobby:s}=no(),{t:o}=We(),{roomAlias:a,roomId:c,viaServers:l}=Cje(),d=c??a;d||M.error("No room specified");const{registerPasswordlessUser:h}=Mfe(),[m,g]=_.useState(!1),{loading:y,authenticated:v,client:w,error:S,passwordlessUser:R}=W8(),{avatarUrl:x,displayName:T}=V_(w),I=yot(w,d,l),k=_ot(I.kind==="loaded"?I.rtcSession:void 0),A=Est(k);_.useEffect(()=>{!y&&!v&&i&&!ut&&(g(!0),h(i).catch(K=>{M.error("Failed to register passwordless user",K)}).finally(()=>{g(!1)}))},[y,v,i,g,h]);const[O,D]=uR();_.useEffect(()=>{O===null&&D&&D(!0)},[O,D]);const N=_.useRef(!1);_.useEffect(()=>{I.kind==="loaded"&&N.current&&M.log("Play join sound 'Not yet implemented'")},[I.kind]);const U=()=>{switch(I.kind){case"loaded":return E.jsx(fot,{widget:ut,client:w,rtcSession:I.rtcSession,isJoined:k,isPasswordlessUser:R,confineToRoom:t,preload:n,skipLobby:s||N.current,header:r,muteStates:A});case"waitForInvite":case"canKnock":{N.current=N.current||I.kind==="waitForInvite";const K=I.kind==="canKnock"?I.knock:null,Y=I.kind==="canKnock"?o("lobby.ask_to_join"):E.jsxs(E.Fragment,{children:[o("lobby.waiting_for_invite"),E.jsx(foe,{})]});return E.jsx(phe,{client:w,matrixInfo:{userId:w.getUserId()??"",displayName:T??"",avatarUrl:x??"",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"]?hn.PER_PARTICIPANT:hn.NONE}},onEnter:()=>K?.(),enterLabel:Y,waitingForInvite:I.kind==="waitForInvite",confineToRoom:t,hideHeader:r!=="standard",participantCount:null,muteStates:A,onShareClick:null})}case"loading":return E.jsx(qg,{children:E.jsx("h1",{children:o("common.loading")})});case"failed":return N.current=!1,I.error.errcode==="M_NOT_FOUND"?E.jsx(qg,{children:E.jsx(Kb,{Icon:M8e,title:o("error.call_not_found"),widget:ut,children:E.jsx(Ys,{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(il,{to:"/",children:"create a new one"}),"."]})})})}):I.error instanceof eC?E.jsx(qg,{children:E.jsxs(Kb,{Icon:I.error.icon,title:I.error.message,widget:ut,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(zb,{widget:ut,error:I.error});default:return E.jsx(E.Fragment,{children:" "})}};let $;return y||m?$=E.jsx(pR,{}):S?$=E.jsx(zb,{widget:ut,error:S}):w?d?$=U():$=E.jsx(Lfe,{}):$=E.jsx(wJe,{}),E.jsxs(E.Fragment,{children:[$,e&&sn.get().app_prompt&&(va==="android"||va==="ios")&&c&&E.jsx(mot,{roomId:c})]})},Eot="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==",wot=""+new URL("cs-app-Du_5mVg3.json",import.meta.url).href,Cot=""+new URL("da-app-BBz-lePm.json",import.meta.url).href,Tot=""+new URL("de-app-DjOuqT-j.json",import.meta.url).href,Rot=""+new URL("el-app-BBr3LLTK.json",import.meta.url).href,Iot=""+new URL("en-app-I8blcx-e.json",import.meta.url).href,kot=""+new URL("es-app-Q3c7lmEj.json",import.meta.url).href,xot=""+new URL("et-app-DLvuR7m2.json",import.meta.url).href,Aot="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",Pot=""+new URL("fi-app-tnO3DMdi.json",import.meta.url).href,Lot=""+new URL("fr-app-BxTYbDfK.json",import.meta.url).href,Oot=""+new URL("id-app-BEz8ptLJ.json",import.meta.url).href,Mot=""+new URL("it-app-Cik25Qgd.json",import.meta.url).href,Dot=""+new URL("ja-app-Cp_00ujI.json",import.meta.url).href,Not=""+new URL("lv-app-D-ZV3Ytk.json",import.meta.url).href,Uot=""+new URL("pl-app-CUkXVSZk.json",import.meta.url).href,jot=""+new URL("ro-app-CdYgKCOW.json",import.meta.url).href,Fot=""+new URL("ru-app-CIijOjFj.json",import.meta.url).href,$ot=""+new URL("sk-app-DaVEeQWZ.json",import.meta.url).href,Bot=""+new URL("sv-app-DHLBEOTp.json",import.meta.url).href,Hot=""+new URL("tr-app-Dk--6BpP.json",import.meta.url).href,Vot=""+new URL("uk-app-DZD01h76.json",import.meta.url).href,qot="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==",Got=""+new URL("zh-Hans-app-BY5jJGyr.json",import.meta.url).href,Kot=""+new URL("zh-Hant-app-BV1LKS_j.json",import.meta.url).href,{slice:zot,forEach:Wot}=[];function Yot(t){return Wot.call(zot.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function Xot(t){return typeof t!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(t))}const OX=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Jot=function(t,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${t}=${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(!OX.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!OX.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 r.partitioned&&(s+="; Partitioned"),s},MX={create(t,e,n,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+n*60*1e3)),r&&(i.domain=r),document.cookie=Jot(t,e,i)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let i=n[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(t,e){this.create(t,"",-1,e)}};var Qot={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return MX.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;n&&typeof document<"u"&&MX.create(n,t,r,i,s)}},Zot={name:"querystring",lookup(t){let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:r}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));const s=r.substring(1).split("&");for(let o=0;o<s.length;o++){const a=s[o].indexOf("=");a>0&&s[o].substring(0,a)===e&&(n=s[o].substring(a+1))}}return n}},eat={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,r;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const s=i.substring(1);if(e){const o=s.split("&");for(let a=0;a<o.length;a++){const c=o[a].indexOf("=");c>0&&o[a].substring(0,c)===e&&(r=o[a].substring(c+1))}}if(r)return r;if(!r&&n>-1){const o=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?o[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return r}};let Jm=null;const DX=()=>{if(Jm!==null)return Jm;try{if(Jm=typeof window<"u"&&window.localStorage!==null,!Jm)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Jm=!1}return Jm};var tat={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&DX())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&DX()&&window.localStorage.setItem(n,t)}};let Qm=null;const NX=()=>{if(Qm!==null)return Qm;try{if(Qm=typeof window<"u"&&window.sessionStorage!==null,!Qm)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Qm=!1}return Qm};var nat={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&NX())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&NX()&&window.sessionStorage.setItem(n,t)}},rat={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:i}=navigator;if(n)for(let s=0;s<n.length;s++)e.push(n[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},iat={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},sat={name:"path",lookup(t){let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?n[typeof e=="number"?e:0]?.replace("/",""):void 0}},oat={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,r=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[n]}};let Npe=!1;try{document.cookie,Npe=!0}catch{}const Upe=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Npe||Upe.splice(1,1);const aat=()=>({order:Upe,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class jpe{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=Yot(n,this.options||{},aat()),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(Qot),this.addDetector(Zot),this.addDetector(tat),this.addDetector(nat),this.addDetector(rat),this.addDetector(iat),this.addDetector(sat),this.addDetector(oat),this.addDetector(eat)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(n=n.concat(i))}}),n=n.filter(r=>r!=null&&!Xot(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}jpe.type="languageDetector";var BE={},UX;function cat(){if(UX)return BE;UX=1,Object.defineProperty(BE,"__esModule",{value:!0}),BE.shouldPolyfill=t;function t(){return!Intl.Segmenter}return BE}var lat=cat(),HE={},jX;function uat(){if(jX)return HE;jX=1,Object.defineProperty(HE,"__esModule",{value:!0}),HE.shouldPolyfill=t;function t(){return typeof Intl>"u"||!("DurationFormat"in Intl)}return HE}var dat=uat();const Fpe=Object.assign({"../locales/bg/app.json":Eot,"../locales/cs/app.json":wot,"../locales/da/app.json":Cot,"../locales/de/app.json":Tot,"../locales/el/app.json":Rot,"../locales/en/app.json":Iot,"../locales/es/app.json":kot,"../locales/et/app.json":xot,"../locales/fa/app.json":Aot,"../locales/fi/app.json":Pot,"../locales/fr/app.json":Lot,"../locales/id/app.json":Oot,"../locales/it/app.json":Mot,"../locales/ja/app.json":Dot,"../locales/lv/app.json":Not,"../locales/pl/app.json":Uot,"../locales/ro/app.json":jot,"../locales/ru/app.json":Fot,"../locales/sk/app.json":$ot,"../locales/sv/app.json":Bot,"../locales/tr/app.json":Hot,"../locales/uk/app.json":Vot,"../locales/vi/app.json":qot,"../locales/zh-Hans/app.json":Got,"../locales/zh-Hant/app.json":Kot}),fat=(t,e)=>Fpe[`../locales/${t}/${e}.json`],hat=[...new Set(Object.keys(Fpe).map(t=>{const e=t.match(/\/([^/]+)\/[^/]+\.json$/)?.[1];if(!e)throw new Error(`Could not parse locale URL ${t}`);return e}))],pat={type:"backend",init(){},read(t,e,n){(async()=>{const r=fat(t,e);if(!r)throw new Error(`Namespace ${e} for locale ${t} not found`);const i=await fetch(r,{credentials:"omit",headers:{Accept:"application/json"}});if(p8(i))throw Error(`Failed to fetch ${r}`);return await i.json()})().then(r=>n(null,r),r=>n(r,null))}};class mat{constructor(){this.config=0,this.sentry=0,this.openTelemetry=0}allDepsAreLoaded(){return!Object.values(this).some(e=>e!==2)}}class Va{constructor(){this.isInitialized=!1,this.loadStates=new mat}static isInitialized(){return!!Va.internalInstance?.isInitialized}static async initBeforeReact(){const e=[];lat.shouldPolyfill()&&e.push(lb(()=>import("./polyfill-force-BlR75_rd.js").then(s=>s.p),__vite__mapDeps([2,3]),import.meta.url)),dat.shouldPolyfill()&&e.push(lb(()=>import("./polyfill-force-CkGZrTiH.js").then(s=>s.p),__vite__mapDeps([4,3]),import.meta.url)),await Promise.all(e);const n=new jpe;n.addDetector({name:"urlFragment",lookup:()=>Br().lang??void 0}),Gi.on("languageChanged",s=>{document.documentElement.lang=s}),await Gi.use(pat).use(n).use(h8e).init({fallbackLng:"en",defaultNS:"app",keySeparator:".",nsSeparator:!1,pluralSeparator:"_",contextSeparator:"|",supportedLngs:hat,interpolation:{escapeValue:!1},detection:{order:["urlFragment","navigator"],caches:[]}});const{fonts:r,fontScale:i}=Br();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",va)}static init(){return Va?.internalInstance?.initPromise?null:(Va.internalInstance=new Va,Va.internalInstance.initPromise=new Promise(e=>{Va.internalInstance?.initStep(e)}),Va.internalInstance.initPromise)}static reset(){Va.internalInstance=void 0}initStep(e){if(this.loadStates.config===0&&(this.loadStates.config=1,sn.init().then(()=>{this.loadStates.config=2,this.initStep(e)},n=>{M.error("Failed to load config",n)})),this.loadStates.sentry===0&&this.loadStates.config===2){let n,r;n=Br().sentryDsn??void 0,r=Br().sentryEnvironment??void 0,n&&bke({dsn:n,environment:r,integrations:[jke({useEffect:Ce.useEffect,useLocation:rs,useNavigationType:kwe,createRoutesFromChildren:LC,matchRoutes:U7})],tracesSampleRate:1}),this.loadStates.sentry=2}this.loadStates.openTelemetry===0&&this.loadStates.config===2&&(fR.globalInit(),this.loadStates.openTelemetry=2),this.loadStates.allDepsAreLoaded()&&(e(),this.isInitialized=!0)}}const gat=()=>{const[t,e]=_.useState(()=>Br().theme),n=_.useRef(document.body.classList.item(0));_.useEffect(()=>{if(ut){const r=i=>{i.preventDefault(),"name"in i.detail.data&&typeof i.detail.data.name=="string"&&e(i.detail.data.name),ut.api.transport.reply(i.detail,{})};return ut.lazyActions.on(vr.ThemeChange,r),()=>{ut.lazyActions.off(vr.ThemeChange,r)}}},[]),_.useLayoutEffect(()=>{const r=t?.includes("light")?"light":"dark",i=t?.includes("high-contrast")?"-hc":"",s="cpd-theme-"+r+i;s!==n.current&&(document.body.classList.remove("cpd-theme-light","cpd-theme-dark","cpd-theme-light-hc","cpd-theme-dark-hc"),document.body.classList.add(s),n.current=s),document.body.classList.remove("no-theme")},[n,t])},VE=Fke(Hee),vat=({children:t})=>{const{pathname:e}=rs();return _.useEffect(()=>{let n="";!["/login","/register"].includes(e)&&!ut&&(n="var(--background-gradient)"),document.getElementsByTagName("body")[0].style.backgroundImage=n},[e]),E.jsx(E.Fragment,{children:t})},yat=({children:t})=>(gat(),t),bat=({vm:t})=>{const[e,n]=_.useState(!1);_.useEffect(()=>{Va.init()?.then(async()=>{e||(n(!0),await ut?.api.sendContentLoaded())}).catch(M.error)});const{header:r}=_.useMemo(Br,[]),i=e?E.jsx(bKe,{children:E.jsx(rue,{value:t.mediaDevices,children:E.jsx(oXe,{children:E.jsx(AT,{fallback:s=>E.jsx(zb,{error:s,widget:ut}),children:E.jsxs(qwe,{children:[E.jsx(VE,{path:"/",element:E.jsx(Lfe,{})}),E.jsx(VE,{path:"/login",element:E.jsx(gJe,{})}),E.jsx(VE,{path:"/register",element:E.jsx(vJe,{})}),E.jsx(VE,{path:"*",element:E.jsx(Sot,{})})]})})})})}):E.jsx(pR,{});return E.jsx(hCe,{children:E.jsx(vat,{children:E.jsx(yat,{children:E.jsx(sre,{children:E.jsx(_.Suspense,{fallback:null,children:r===Nb.AppBar?E.jsx(ist,{children:i}):i})})})})})};class _at extends nS{constructor(){super(...arguments),this.mediaDevices=new _ze(this.scope)}}window.setLKLogLevel=PZ;Lje().catch(t=>{M.error("Failed to initialize rageshake",t)});PZ("info");ySe((t,e,n)=>{global.mx_rage_logger.log(t,"livekit",e,n)});M.info("Element Call embedded-v0.16.2");const LO=Nbe.createRoot(document.getElementById("root"));let sb=null;window.isSecureContext?navigator.mediaDevices||(sb=new Error("Your browser does not support WebRTC.")):sb=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.
349
+ `;return typeof a=="function"&&a(null,w),w},$5}var LX;function iot(){if(LX)return Xm;LX=1;const t=jst(),e=tot(),n=not(),r=rot();function i(s,o,a,c,l){const d=[].slice.call(arguments,1),h=d.length,m=typeof d[h-1]=="function";if(!m&&!t())throw new Error("Callback required as last argument");if(m){if(h<2)throw new Error("Too few arguments provided");h===2?(l=a,a=o,o=c=void 0):h===3&&(o.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=o,o=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=o,o=c=void 0):h===2&&!o.getContext&&(c=a,a=o,o=void 0),new Promise(function(g,y){try{const v=e.create(a,c);g(s(v,o,c))}catch(v){y(v)}})}try{const g=e.create(a,c);l(null,s(g,o,c))}catch(g){l(g)}}return Xm.create=e.create,Xm.toCanvas=i.bind(null,n.render),Xm.toDataURL=i.bind(null,n.renderToDataURL),Xm.toString=i.bind(null,function(s,o,a){return r.render(s,a)}),Xm}var sot=iot();const oot="_qrCode_h54ia_8",aot={qrCode:oot},cot=({data:t,className:e})=>{const[n,r]=_.useState(null);return _.useEffect(()=>{let i=!1;return sot.toDataURL(t,{errorCorrectionLevel:"L"}).then(s=>{i||r(s)}).catch(s=>{i||r(null)}),()=>{i=!0}},[t]),E.jsx("div",{className:Oe(aot.qrCode,e),children:n&&E.jsx("img",{src:n,alt:Po("qr_code")})})},lot=({room:t,open:e,onDismiss:n})=>{const{t:r}=We(),i=X_(t.roomId),s=_.useMemo(()=>xfe(t.roomId,i,t.name),[i,t.name,t.roomId]),[o,a]=_.useState(!1),c=_.useCallback(()=>a(!1),[a]),l=_.useCallback(d=>{d.stopPropagation(),Mst(s),n(),a(!0)},[s,n]);return E.jsxs(E.Fragment,{children:[E.jsxs(Up,{title:r("invite_modal.title"),open:e,onDismiss:n,children:[E.jsx(cot,{className:v5.qrCode,data:s}),E.jsx(an,{className:v5.url,size:"sm",weight:"semibold",children:s}),E.jsx(Bt,{className:v5.button,Icon:E8e,onClick:l,"data-testid":"modal_inviteLink",children:r("action.copy_link")})]}),E.jsx(xpe,{open:o,onDismiss:c,autoDismiss:2e3,Icon:foe,children:r("invite_modal.link_copied_toast")})]})},uot=({error:t,recoveryActionHandler:e,widget:n})=>{const{t:r}=We();let i;switch(t.category){case Jw.CONFIGURATION_ISSUE:i=S8e;break;case Jw.NETWORK_CONNECTIVITY:i=R8e;break;case Jw.CLIENT_CONFIGURATION:i=V8e;break;default:i=PT}const s=[];return t instanceof OD&&s.push({label:r("call_ended_view.reconnect_button"),onClick:()=>void e("reconnect")}),E.jsx(qg,{children:E.jsxs(Kb,{Icon:i,title:t.localisedTitle,rageshake:t.code==rpe.UNKNOWN_ERROR,widget:n,children:[E.jsx("p",{children:t.localisedMessage??E.jsx(Ys,{i18nKey:"error.unexpected_ec_error",components:[E.jsx("b",{}),E.jsx("code",{})],values:{errorCode:t.code}})}),s&&s.map((o,a)=>E.jsx(Bt,{kind:"secondary",onClick:o.onClick,children:o.label},`action${a}`))]})})},dot=({recoveryActionHandler:t,onError:e,children:n,widget:r})=>{const i=_.useCallback(({error:s,resetError:o})=>{const a=s instanceof yl?s:new MD(s instanceof Error?s:new Error);return E.jsx(uot,{widget:r??null,error:a,resetError:o,recoveryActionHandler:async c=>{await t(c),o()}})},[t,r]);return E.jsx(AT,{fallback:i,onError:s=>e?.(s),children:n})},fot=({client:t,isPasswordlessUser:e,confineToRoom:n,preload:r,skipLobby:i,header:s,rtcSession:o,isJoined:a,muteStates:c,widget:l})=>{const[d,h]=_.useState(null),m=G8(o),g=Qe(kpe),y=Pf(a4({sounds:Ipe,latencyHint:"interactive",muted:g}));_.useEffect(()=>{m.length>=_st&&c.audio.setEnabled?.(!1)},[]),_.useEffect(()=>{a&&o.updateCallIntent(c.video.enabled?"video":"audio")},[o,a,c.video.enabled]),_.useEffect(()=>(M.info("[Lifecycle] GroupCallView Component mounted"),()=>{M.info("[Lifecycle] GroupCallView Component unmounted")}),[]),_.useEffect(()=>(document.body.classList.add("no-scroll-body"),()=>{document.body.classList.remove("no-scroll-body")}),[]),_.useEffect(()=>(window.rtcSession=o,()=>{delete window.rtcSession}),[o]),Hle(o,ei.MembershipManagerError,Ie=>h(new OD)),_.useEffect(()=>{t.getRoom(o.room.roomId)!==o.room&&M.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.`)},[t,o.room]);const v=o.room,{displayName:w,avatarUrl:S}=V_(t),R=xst(v),x=kst(v),{perParticipantE2EE:T,returnToLobby:I,password:k}=no(),A=X_(v.roomId),[O]=Gn(Ole),[D]=Gn(V8);_.useEffect(()=>{k&&Cfe(v.roomId,k)},[k,v.roomId]),Q_(R),sst(R);const N=_.useMemo(()=>({userId:t.getUserId(),displayName:w,avatarUrl:S,roomId:v.roomId,roomName:R,roomAlias:v.getCanonicalAlias(),roomAvatar:x,e2eeSystem:A}),[t,w,S,R,v,x,A]),U=_.useMemo(()=>new Set(m.map(Ie=>Ie.sender)).size,[m]),$=Wu(),K=Pf(c),Y=_.useCallback(async Ie=>{try{await Rst(Ie,T,O,D)}catch(Ue){if(Ue instanceof yl)h(Ue);else{M.error("Unknown Error while entering RTC session",Ue);const et=new MD(Ue instanceof Error?Ue:new Error("Unknown error",{cause:Ue}));h(et)}}},[T,D,O]);_.useEffect(()=>{const Ie=async({audioInput:Ue,videoInput:et})=>{const ln=await xu.getLocalDevices(void 0,!0);if(Ue){const Bn=KW(Ue,"audioinput",ln);Bn?(M.debug(`Found audio input ID ${Bn} for name ${Ue}`),$.audioInput.select(Bn)):(M.warn("Unknown audio input: "+Ue),K.current.audio.setEnabled?.(!1))}if(et){const Bn=KW(et,"videoinput",ln);Bn?(M.debug(`Found video input ID ${Bn} for name ${et}`),$.videoInput.select(Bn)):(M.warn("Unknown video input: "+et),K.current.video.setEnabled?.(!1))}};if(i)if(l&&r){const Ue=et=>{(async()=>{await Ie(et.detail.data),await Y(o),l.api.transport.reply(et.detail,{})})().catch(ln=>{M.error("Error joining RTC session on preload",ln)})};return l.lazyActions.on(Ri.JoinCall,Ue),()=>{l.lazyActions.off(Ri.JoinCall,Ue)}}else(async()=>{await Y(o)})().catch(Ue=>{M.error("Error joining RTC session immediately",Ue)})},[l,o,r,i,T,$,K,Y,O]);const[G,F]=_.useState(!1),q=hl(),z=_.useCallback((Ie="user",Ue="left")=>{const et=y.current?.playSound(Ue),ln=!!l;F(!0);const Bn=new Promise(Mn=>{Ut.instance.eventCallEnded.track(v.roomId,o.memberships.length,ln,o),window.setTimeout(Mn,10)});nX(o,Ie,Promise.all([et,Bn])).then(async()=>{!e&&!n&&!Ut.instance.isEnabled()&&await q("/")}).catch(Mn=>{M.error("Error leaving RTC session",Mn)})},[y,l,o,v.roomId,e,n,q]);_.useEffect(()=>{if(l&&a){l.api.setAlwaysOnScreen(!0).catch(Ue=>{M.error("Error calling setAlwaysOnScreen(true)",Ue)});const Ie=Ue=>{l.api.transport.reply(Ue.detail,{}),nX(o,"user").catch(et=>{M.error("Failed to leave RTC session",et)})};return l.lazyActions.once(Ri.HangupCall,Ie),()=>{l.lazyActions.off(Ri.HangupCall,Ie)}}},[l,a,o]);const W=Ast(v),[V,X]=_.useState(!1),ne=_.useCallback(()=>X(!1),[X]),fe=_.useCallback(()=>X(!0),[X]),ye=W===ef.Public?fe:null;if(!dee()&&A.kind!==hn.NONE)throw new unt;const Ae=E.jsx(lot,{room:v,open:V,onDismiss:ne}),be=E.jsxs(E.Fragment,{children:[Ae,E.jsx(phe,{client:t,matrixInfo:N,muteStates:c,onEnter:()=>void Y(o),confineToRoom:n,hideHeader:s===Nb.None,participantCount:U,onShareClick:ye})]});let _e;if(d){const Ie=()=>{throw d};_e=E.jsx(Ie,{})}else a?_e=E.jsxs(E.Fragment,{children:[Ae,E.jsx(yst,{client:t,matrixInfo:N,rtcSession:o,matrixRoom:v,onLeave:z,header:s,muteStates:c,e2eeSystem:A,onShareClick:ye})]}):G&&l===null?e||Ut.instance.isEnabled()&&l===null?_e=E.jsx(jZe,{endedCallId:o.room.roomId,client:t,isPasswordlessUser:e,hideHeader:s===Nb.None,confineToRoom:n}):_e=null:G&&l!==null?_e=I?be:null:r||i?_e=null:_e=be;return E.jsx(dot,{widget:l,recoveryActionHandler:async Ie=>{h(null),Ie=="reconnect"&&(F(!1),await Y(o).catch(Ue=>{M.error("Error re-entering RTC session",Ue)}))},onError:()=>{o.isJoined()&&z("error")},children:_e})},hot="_modal_1tnec_8",pot={modal:hot},mot=({roomId:t})=>{const{t:e}=We(),[n,r]=_.useState(!0),i=_.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[r]),s=X_(t);s.kind===hn.NONE&&M.error("Generating app redirect URL for encrypted room but don't have key available!");const o=_.useMemo(()=>{const a=new URL(t===null?window.location.href:xfe(t,s));a.hash=Sje(a.hash,l=>(l.set("appPrompt","false"),l.set("confineToRoom","true"),l));const c=new URL("io.element.call:/");return c.searchParams.set("url",a.toString()),c.toString()},[s,t]);return E.jsxs(Up,{className:pot.modal,title:e("app_selection_modal.title"),open:n,children:[E.jsx(an,{size:"md",weight:"semibold",children:e("app_selection_modal.text")}),E.jsx(Bt,{kind:"secondary",onClick:i,children:e("app_selection_modal.continue_in_browser")}),E.jsx(Bt,{as:"a",href:o,Icon:Woe,children:e("app_selection_modal.open_in_app")})]})},got=3,vot=3e3;async function Dpe(t,e=0,...n){try{return await t.joinRoom(...n)}catch(r){if(r instanceof tr&&r.errcode==="M_FORBIDDEN"&&e<got)return await new Promise(i=>setTimeout(i,vot)),Dpe(t,e+1,...n);throw r}}class eC extends Error{constructor(e,n,r,i){super(n),this.icon=e,this.messageBody=r,this.reason=i}}const yot=(t,e,n)=>{const[r,i]=_.useState({kind:"loading"}),s=_.useRef(void 0),{t:o}=We(),a=_.useCallback(()=>new eC(v8e,o("group_call_loader.banned_heading"),o("group_call_loader.banned_body"),d()),[o]),c=_.useCallback(()=>new eC(LT,o("group_call_loader.knock_reject_heading"),o("group_call_loader.knock_reject_body"),d()),[o]),l=_.useCallback(()=>new eC(Ooe,o("group_call_loader.call_ended_heading"),o("group_call_loader.call_ended_body"),d()),[o]),d=()=>s.current?.currentState.getStateEvents(Z.RoomMember,s.current?.myUserId)?.getContent().reason;return _.useEffect(()=>{if(!t||!e)return;const h=async S=>{let R=null;const x=await t.getRoomIdForAlias(S.toLowerCase());return M.info(`${S} resolved to ${x.room_id}`),R=t.getRoom(x.room_id),R?M.info(`Already in room ${x.room_id}, not rejoining.`):(M.info(`Room ${x.room_id} not found, joining.`),R=await t.joinRoom(x.room_id,{viaServers:x.servers})),R},m=async(S,R,x)=>(await t.knockRoom(S,{viaServers:R}),x(),await new Promise((T,I)=>{t.on(ke.MyMembership,(k,A,O)=>{S===k.roomId&&(s.current=k,A===Be.Invite&&O===Be.Knock&&Dpe(t,0,k.roomId,{viaServers:R}).then(D=>{M.log("Auto-joined %s",D.roomId),T(D)},I),A===Be.Ban&&I(a()),A===Be.Leave&&I(c()))})})),g=async()=>{let S=null;if(e[0]==="#")S=await h(e),s.current=S;else{const R=e;S=t.getRoom(R),s.current=S??void 0;const x=S?.getMyMembership();if(x===Be.Join)return S;if(ut)throw new Error("Room not found. The widget-api did not pass over the relevant room events/information.");if(x===Be.Ban)throw a();if(x===Be.Invite)S=await t.joinRoom(R,{viaServers:n});else{let T;try{T=await t.getRoomSummary(R,n)}catch(I){M.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(T===void 0||T.join_rule===ef.Public)S=await t.joinRoom(R,{viaServers:n});else if(T.join_rule===ef.Knock){const I=T;let k=()=>{};const A=new Promise(O=>{I.membership!==Be.Knock?k=O:O()});i({kind:"canKnock",roomSummary:I,knock:k}),await A,S=await m(T.room_id,n,()=>i({kind:"waitForInvite",roomSummary:I}))}else throw new Error(`Room ${T.room_id} is not joinable. This likely means, that the conference owner has changed the room settings to private.`)}}return M.info(`Joined ${e}, waiting room to be ready for group calls`),await t.waitUntilRoomReadyForGroupCalls(S.roomId),M.info(`${e}, is ready for group calls`),S},y=async()=>{const S=await g();return s.current=S,M.debug(`Fetched / joined room ${e}`),t.matrixRTC.getRoomSession(S)},v=async()=>{t.getSyncState()!==Gt.Syncing&&(M.debug("useLoadGroupCall: waiting for client to start syncing..."),await new Promise(S=>{const R=()=>{if(t.getSyncState()===Gt.Syncing)return t.off(Le.Sync,R),S()};t.on(Le.Sync,R)}),M.debug("useLoadGroupCall: client is now syncing."))},w=async()=>{await new Promise((S,R)=>{t.on(ke.MyMembership,(x,T)=>{T===Be.Leave&&R(l()),T===Be.Ban&&R(a())})})};r.kind==="loading"&&(M.log("Start loading group call"),v().then(y).then(S=>i({kind:"loaded",rtcSession:S})).then(w).catch(S=>i({kind:"failed",error:S})))},[a,t,c,l,e,r,o,n]),r},bot=new On;function _ot(t){const e=gp(t??bot,ei.JoinStateChanged,_.useCallback(()=>t?.isJoined()??!1,[t]));return _.useEffect(()=>{M.info(`Session in room ${t?.room.roomId} changed to ${e?"joined":"left"}`)},[t,e]),e}const Sot=()=>{const{confineToRoom:t,appPrompt:e,preload:n,header:r,displayName:i,skipLobby:s}=no(),{t:o}=We(),{roomAlias:a,roomId:c,viaServers:l}=Cje(),d=c??a;d||M.error("No room specified");const{registerPasswordlessUser:h}=Mfe(),[m,g]=_.useState(!1),{loading:y,authenticated:v,client:w,error:S,passwordlessUser:R}=W8(),{avatarUrl:x,displayName:T}=V_(w),I=yot(w,d,l),k=_ot(I.kind==="loaded"?I.rtcSession:void 0),A=Est(k);_.useEffect(()=>{!y&&!v&&i&&!ut&&(g(!0),h(i).catch(K=>{M.error("Failed to register passwordless user",K)}).finally(()=>{g(!1)}))},[y,v,i,g,h]);const[O,D]=uR();_.useEffect(()=>{O===null&&D&&D(!0)},[O,D]);const N=_.useRef(!1);_.useEffect(()=>{I.kind==="loaded"&&N.current&&M.log("Play join sound 'Not yet implemented'")},[I.kind]);const U=()=>{switch(I.kind){case"loaded":return E.jsx(fot,{widget:ut,client:w,rtcSession:I.rtcSession,isJoined:k,isPasswordlessUser:R,confineToRoom:t,preload:n,skipLobby:s||N.current,header:r,muteStates:A});case"waitForInvite":case"canKnock":{N.current=N.current||I.kind==="waitForInvite";const K=I.kind==="canKnock"?I.knock:null,Y=I.kind==="canKnock"?o("lobby.ask_to_join"):E.jsxs(E.Fragment,{children:[o("lobby.waiting_for_invite"),E.jsx(foe,{})]});return E.jsx(phe,{client:w,matrixInfo:{userId:w.getUserId()??"",displayName:T??"",avatarUrl:x??"",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"]?hn.PER_PARTICIPANT:hn.NONE}},onEnter:()=>K?.(),enterLabel:Y,waitingForInvite:I.kind==="waitForInvite",confineToRoom:t,hideHeader:r!=="standard",participantCount:null,muteStates:A,onShareClick:null})}case"loading":return E.jsx(qg,{children:E.jsx("h1",{children:o("common.loading")})});case"failed":return N.current=!1,I.error.errcode==="M_NOT_FOUND"?E.jsx(qg,{children:E.jsx(Kb,{Icon:M8e,title:o("error.call_not_found"),widget:ut,children:E.jsx(Ys,{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(il,{to:"/",children:"create a new one"}),"."]})})})}):I.error instanceof eC?E.jsx(qg,{children:E.jsxs(Kb,{Icon:I.error.icon,title:I.error.message,widget:ut,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(zb,{widget:ut,error:I.error});default:return E.jsx(E.Fragment,{children:" "})}};let $;return y||m?$=E.jsx(pR,{}):S?$=E.jsx(zb,{widget:ut,error:S}):w?d?$=U():$=E.jsx(Lfe,{}):$=E.jsx(wJe,{}),E.jsxs(E.Fragment,{children:[$,e&&sn.get().app_prompt&&(va==="android"||va==="ios")&&c&&E.jsx(mot,{roomId:c})]})},Eot="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==",wot=""+new URL("cs-app-Du_5mVg3.json",import.meta.url).href,Cot=""+new URL("da-app-BBz-lePm.json",import.meta.url).href,Tot=""+new URL("de-app-DjOuqT-j.json",import.meta.url).href,Rot=""+new URL("el-app-BBr3LLTK.json",import.meta.url).href,Iot=""+new URL("en-app-I8blcx-e.json",import.meta.url).href,kot=""+new URL("es-app-Q3c7lmEj.json",import.meta.url).href,xot=""+new URL("et-app-DLvuR7m2.json",import.meta.url).href,Aot="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",Pot=""+new URL("fi-app-tnO3DMdi.json",import.meta.url).href,Lot=""+new URL("fr-app-BxTYbDfK.json",import.meta.url).href,Oot=""+new URL("id-app-BEz8ptLJ.json",import.meta.url).href,Mot=""+new URL("it-app-Cik25Qgd.json",import.meta.url).href,Dot=""+new URL("ja-app-Cp_00ujI.json",import.meta.url).href,Not=""+new URL("lv-app-D-ZV3Ytk.json",import.meta.url).href,Uot=""+new URL("pl-app-CUkXVSZk.json",import.meta.url).href,jot=""+new URL("ro-app-CdYgKCOW.json",import.meta.url).href,Fot=""+new URL("ru-app-CIijOjFj.json",import.meta.url).href,$ot=""+new URL("sk-app-DaVEeQWZ.json",import.meta.url).href,Bot=""+new URL("sv-app-DHLBEOTp.json",import.meta.url).href,Hot=""+new URL("tr-app-Dk--6BpP.json",import.meta.url).href,Vot=""+new URL("uk-app-DZD01h76.json",import.meta.url).href,qot="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==",Got=""+new URL("zh-Hans-app-BY5jJGyr.json",import.meta.url).href,Kot=""+new URL("zh-Hant-app-BV1LKS_j.json",import.meta.url).href,{slice:zot,forEach:Wot}=[];function Yot(t){return Wot.call(zot.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function Xot(t){return typeof t!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(t))}const OX=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Jot=function(t,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${t}=${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(!OX.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!OX.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 r.partitioned&&(s+="; Partitioned"),s},MX={create(t,e,n,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+n*60*1e3)),r&&(i.domain=r),document.cookie=Jot(t,e,i)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let i=n[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(t,e){this.create(t,"",-1,e)}};var Qot={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return MX.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;n&&typeof document<"u"&&MX.create(n,t,r,i,s)}},Zot={name:"querystring",lookup(t){let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:r}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));const s=r.substring(1).split("&");for(let o=0;o<s.length;o++){const a=s[o].indexOf("=");a>0&&s[o].substring(0,a)===e&&(n=s[o].substring(a+1))}}return n}},eat={name:"hash",lookup(t){let{lookupHash:e,lookupFromHashIndex:n}=t,r;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const s=i.substring(1);if(e){const o=s.split("&");for(let a=0;a<o.length;a++){const c=o[a].indexOf("=");c>0&&o[a].substring(0,c)===e&&(r=o[a].substring(c+1))}}if(r)return r;if(!r&&n>-1){const o=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?o[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return r}};let Jm=null;const DX=()=>{if(Jm!==null)return Jm;try{if(Jm=typeof window<"u"&&window.localStorage!==null,!Jm)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Jm=!1}return Jm};var tat={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&DX())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&DX()&&window.localStorage.setItem(n,t)}};let Qm=null;const NX=()=>{if(Qm!==null)return Qm;try{if(Qm=typeof window<"u"&&window.sessionStorage!==null,!Qm)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Qm=!1}return Qm};var nat={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&NX())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&NX()&&window.sessionStorage.setItem(n,t)}},rat={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:i}=navigator;if(n)for(let s=0;s<n.length;s++)e.push(n[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},iat={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},sat={name:"path",lookup(t){let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?n[typeof e=="number"?e:0]?.replace("/",""):void 0}},oat={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,r=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[n]}};let Npe=!1;try{document.cookie,Npe=!0}catch{}const Upe=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Npe||Upe.splice(1,1);const aat=()=>({order:Upe,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class jpe{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=Yot(n,this.options||{},aat()),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(Qot),this.addDetector(Zot),this.addDetector(tat),this.addDetector(nat),this.addDetector(rat),this.addDetector(iat),this.addDetector(sat),this.addDetector(oat),this.addDetector(eat)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(n=n.concat(i))}}),n=n.filter(r=>r!=null&&!Xot(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}jpe.type="languageDetector";var BE={},UX;function cat(){if(UX)return BE;UX=1,Object.defineProperty(BE,"__esModule",{value:!0}),BE.shouldPolyfill=t;function t(){return!Intl.Segmenter}return BE}var lat=cat(),HE={},jX;function uat(){if(jX)return HE;jX=1,Object.defineProperty(HE,"__esModule",{value:!0}),HE.shouldPolyfill=t;function t(){return typeof Intl>"u"||!("DurationFormat"in Intl)}return HE}var dat=uat();const Fpe=Object.assign({"../locales/bg/app.json":Eot,"../locales/cs/app.json":wot,"../locales/da/app.json":Cot,"../locales/de/app.json":Tot,"../locales/el/app.json":Rot,"../locales/en/app.json":Iot,"../locales/es/app.json":kot,"../locales/et/app.json":xot,"../locales/fa/app.json":Aot,"../locales/fi/app.json":Pot,"../locales/fr/app.json":Lot,"../locales/id/app.json":Oot,"../locales/it/app.json":Mot,"../locales/ja/app.json":Dot,"../locales/lv/app.json":Not,"../locales/pl/app.json":Uot,"../locales/ro/app.json":jot,"../locales/ru/app.json":Fot,"../locales/sk/app.json":$ot,"../locales/sv/app.json":Bot,"../locales/tr/app.json":Hot,"../locales/uk/app.json":Vot,"../locales/vi/app.json":qot,"../locales/zh-Hans/app.json":Got,"../locales/zh-Hant/app.json":Kot}),fat=(t,e)=>Fpe[`../locales/${t}/${e}.json`],hat=[...new Set(Object.keys(Fpe).map(t=>{const e=t.match(/\/([^/]+)\/[^/]+\.json$/)?.[1];if(!e)throw new Error(`Could not parse locale URL ${t}`);return e}))],pat={type:"backend",init(){},read(t,e,n){(async()=>{const r=fat(t,e);if(!r)throw new Error(`Namespace ${e} for locale ${t} not found`);const i=await fetch(r,{credentials:"omit",headers:{Accept:"application/json"}});if(p8(i))throw Error(`Failed to fetch ${r}`);return await i.json()})().then(r=>n(null,r),r=>n(r,null))}};class mat{constructor(){this.config=0,this.sentry=0,this.openTelemetry=0}allDepsAreLoaded(){return!Object.values(this).some(e=>e!==2)}}class Va{constructor(){this.isInitialized=!1,this.loadStates=new mat}static isInitialized(){return!!Va.internalInstance?.isInitialized}static async initBeforeReact(){const e=[];lat.shouldPolyfill()&&e.push(lb(()=>import("./polyfill-force-C-cqkbSt.js").then(s=>s.p),__vite__mapDeps([2,3]),import.meta.url)),dat.shouldPolyfill()&&e.push(lb(()=>import("./polyfill-force-C5_YvYDd.js").then(s=>s.p),__vite__mapDeps([4,3]),import.meta.url)),await Promise.all(e);const n=new jpe;n.addDetector({name:"urlFragment",lookup:()=>Br().lang??void 0}),Gi.on("languageChanged",s=>{document.documentElement.lang=s}),await Gi.use(pat).use(n).use(h8e).init({fallbackLng:"en",defaultNS:"app",keySeparator:".",nsSeparator:!1,pluralSeparator:"_",contextSeparator:"|",supportedLngs:hat,interpolation:{escapeValue:!1},detection:{order:["urlFragment","navigator"],caches:[]}});const{fonts:r,fontScale:i}=Br();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",va)}static init(){return Va?.internalInstance?.initPromise?null:(Va.internalInstance=new Va,Va.internalInstance.initPromise=new Promise(e=>{Va.internalInstance?.initStep(e)}),Va.internalInstance.initPromise)}static reset(){Va.internalInstance=void 0}initStep(e){if(this.loadStates.config===0&&(this.loadStates.config=1,sn.init().then(()=>{this.loadStates.config=2,this.initStep(e)},n=>{M.error("Failed to load config",n)})),this.loadStates.sentry===0&&this.loadStates.config===2){let n,r;n=Br().sentryDsn??void 0,r=Br().sentryEnvironment??void 0,n&&bke({dsn:n,environment:r,integrations:[jke({useEffect:Ce.useEffect,useLocation:rs,useNavigationType:kwe,createRoutesFromChildren:LC,matchRoutes:U7})],tracesSampleRate:1}),this.loadStates.sentry=2}this.loadStates.openTelemetry===0&&this.loadStates.config===2&&(fR.globalInit(),this.loadStates.openTelemetry=2),this.loadStates.allDepsAreLoaded()&&(e(),this.isInitialized=!0)}}const gat=()=>{const[t,e]=_.useState(()=>Br().theme),n=_.useRef(document.body.classList.item(0));_.useEffect(()=>{if(ut){const r=i=>{i.preventDefault(),"name"in i.detail.data&&typeof i.detail.data.name=="string"&&e(i.detail.data.name),ut.api.transport.reply(i.detail,{})};return ut.lazyActions.on(vr.ThemeChange,r),()=>{ut.lazyActions.off(vr.ThemeChange,r)}}},[]),_.useLayoutEffect(()=>{const r=t?.includes("light")?"light":"dark",i=t?.includes("high-contrast")?"-hc":"",s="cpd-theme-"+r+i;s!==n.current&&(document.body.classList.remove("cpd-theme-light","cpd-theme-dark","cpd-theme-light-hc","cpd-theme-dark-hc"),document.body.classList.add(s),n.current=s),document.body.classList.remove("no-theme")},[n,t])},VE=Fke(Hee),vat=({children:t})=>{const{pathname:e}=rs();return _.useEffect(()=>{let n="";!["/login","/register"].includes(e)&&!ut&&(n="var(--background-gradient)"),document.getElementsByTagName("body")[0].style.backgroundImage=n},[e]),E.jsx(E.Fragment,{children:t})},yat=({children:t})=>(gat(),t),bat=({vm:t})=>{const[e,n]=_.useState(!1);_.useEffect(()=>{Va.init()?.then(async()=>{e||(n(!0),await ut?.api.sendContentLoaded())}).catch(M.error)});const{header:r}=_.useMemo(Br,[]),i=e?E.jsx(bKe,{children:E.jsx(rue,{value:t.mediaDevices,children:E.jsx(oXe,{children:E.jsx(AT,{fallback:s=>E.jsx(zb,{error:s,widget:ut}),children:E.jsxs(qwe,{children:[E.jsx(VE,{path:"/",element:E.jsx(Lfe,{})}),E.jsx(VE,{path:"/login",element:E.jsx(gJe,{})}),E.jsx(VE,{path:"/register",element:E.jsx(vJe,{})}),E.jsx(VE,{path:"*",element:E.jsx(Sot,{})})]})})})})}):E.jsx(pR,{});return E.jsx(hCe,{children:E.jsx(vat,{children:E.jsx(yat,{children:E.jsx(sre,{children:E.jsx(_.Suspense,{fallback:null,children:r===Nb.AppBar?E.jsx(ist,{children:i}):i})})})})})};class _at extends nS{constructor(){super(...arguments),this.mediaDevices=new _ze(this.scope)}}window.setLKLogLevel=PZ;Lje().catch(t=>{M.error("Failed to initialize rageshake",t)});PZ("info");ySe((t,e,n)=>{global.mx_rage_logger.log(t,"livekit",e,n)});M.info("Element Call embedded-v0.16.3");const LO=Nbe.createRoot(document.getElementById("root"));let sb=null;window.isSecureContext?navigator.mediaDevices||(sb=new Error("Your browser does not support WebRTC.")):sb=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.
350
350
  https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts`);if(sb!==null)throw LO.render(sb.message),sb;Va.initBeforeReact().then(()=>{LO.render(E.jsx(_.StrictMode,{children:E.jsx(bat,{vm:new _at})}))}).catch(t=>{M.error("Failed to initialize app",t),LO.render(t.message)});export{xat as A,W3 as B,sn as C,z1e as D,Z as E,Pat as F,Oat as G,QO as H,Lat as I,To as J,Be as K,Tat as L,tr as M,Kt as N,vu as O,uB as P,K1e as Q,Mat as R,Ih as S,On as T,Aat as U,Dat as V,qt as W,tv as X,Y1e as Y,Ea as _,Eat as a,cc as b,Sat as c,kat as d,B as e,xW as f,cl as g,L as h,Rfe as i,Cat as j,gi as k,M as l,de as m,Bh as n,xe as o,X3 as p,GO as q,IQ as r,_p as s,$at as t,ibe as u,$v as v,ll as w,Xr as x,eye as y,Cy as z};
351
- //# sourceMappingURL=index-DYaS2vUb.js.map
351
+ //# sourceMappingURL=index-BAfhaCa-.js.map