zooid 0.7.4 → 0.8.0

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,305 +0,0 @@
1
- var $U=Object.defineProperty;var WU=(r,e,t)=>e in r?$U(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ne=(r,e,t)=>WU(r,typeof e!="symbol"?e+"":e,t);function qU(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const o=Object.getOwnPropertyDescriptor(n,i);o&&Object.defineProperty(r,i,o.get?o:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function t(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(i){if(i.ep)return;i.ep=!0;const o=t(i);fetch(i.href,o)}})();var wi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qa(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}function GU(r){if(r.__esModule)return r;var e=r.default;if(typeof e=="function"){var t=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(r).forEach(function(n){var i=Object.getOwnPropertyDescriptor(r,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return r[n]}})}),t}var Ix={exports:{}},kv={},xx={exports:{}},nt={};/**
2
- * @license React
3
- * react.production.min.js
4
- *
5
- * Copyright (c) Facebook, Inc. and its affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var tf=Symbol.for("react.element"),HU=Symbol.for("react.portal"),zU=Symbol.for("react.fragment"),YU=Symbol.for("react.strict_mode"),JU=Symbol.for("react.profiler"),XU=Symbol.for("react.provider"),QU=Symbol.for("react.context"),ZU=Symbol.for("react.forward_ref"),e2=Symbol.for("react.suspense"),t2=Symbol.for("react.memo"),r2=Symbol.for("react.lazy"),B0=Symbol.iterator;function n2(r){return r===null||typeof r!="object"?null:(r=B0&&r[B0]||r["@@iterator"],typeof r=="function"?r:null)}var Ox={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Px=Object.assign,Mx={};function Pc(r,e,t){this.props=r,this.context=e,this.refs=Mx,this.updater=t||Ox}Pc.prototype.isReactComponent={};Pc.prototype.setState=function(r,e){if(typeof r!="object"&&typeof r!="function"&&r!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,r,e,"setState")};Pc.prototype.forceUpdate=function(r){this.updater.enqueueForceUpdate(this,r,"forceUpdate")};function Ax(){}Ax.prototype=Pc.prototype;function K_(r,e,t){this.props=r,this.context=e,this.refs=Mx,this.updater=t||Ox}var V_=K_.prototype=new Ax;V_.constructor=K_;Px(V_,Pc.prototype);V_.isPureReactComponent=!0;var K0=Array.isArray,Dx=Object.prototype.hasOwnProperty,$_={current:null},Nx={key:!0,ref:!0,__self:!0,__source:!0};function Lx(r,e,t){var n,i={},o=null,s=null;if(e!=null)for(n in e.ref!==void 0&&(s=e.ref),e.key!==void 0&&(o=""+e.key),e)Dx.call(e,n)&&!Nx.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=t;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];i.children=l}if(r&&r.defaultProps)for(n in a=r.defaultProps,a)i[n]===void 0&&(i[n]=a[n]);return{$$typeof:tf,type:r,key:o,ref:s,props:i,_owner:$_.current}}function i2(r,e){return{$$typeof:tf,type:r.type,key:e,ref:r.ref,props:r.props,_owner:r._owner}}function W_(r){return typeof r=="object"&&r!==null&&r.$$typeof===tf}function o2(r){var e={"=":"=0",":":"=2"};return"$"+r.replace(/[=:]/g,function(t){return e[t]})}var V0=/\/+/g;function ng(r,e){return typeof r=="object"&&r!==null&&r.key!=null?o2(""+r.key):e.toString(36)}function Nh(r,e,t,n,i){var o=typeof r;(o==="undefined"||o==="boolean")&&(r=null);var s=!1;if(r===null)s=!0;else switch(o){case"string":case"number":s=!0;break;case"object":switch(r.$$typeof){case tf:case HU:s=!0}}if(s)return s=r,i=i(s),r=n===""?"."+ng(s,0):n,K0(i)?(t="",r!=null&&(t=r.replace(V0,"$&/")+"/"),Nh(i,e,t,"",function(c){return c})):i!=null&&(W_(i)&&(i=i2(i,t+(!i.key||s&&s.key===i.key?"":(""+i.key).replace(V0,"$&/")+"/")+r)),e.push(i)),1;if(s=0,n=n===""?".":n+":",K0(r))for(var a=0;a<r.length;a++){o=r[a];var l=n+ng(o,a);s+=Nh(o,e,t,l,i)}else if(l=n2(r),typeof l=="function")for(r=l.call(r),a=0;!(o=r.next()).done;)o=o.value,l=n+ng(o,a++),s+=Nh(o,e,t,l,i);else if(o==="object")throw e=String(r),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(r).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return s}function Bf(r,e,t){if(r==null)return r;var n=[],i=0;return Nh(r,n,"","",function(o){return e.call(t,o,i++)}),n}function s2(r){if(r._status===-1){var e=r._result;e=e(),e.then(function(t){(r._status===0||r._status===-1)&&(r._status=1,r._result=t)},function(t){(r._status===0||r._status===-1)&&(r._status=2,r._result=t)}),r._status===-1&&(r._status=0,r._result=e)}if(r._status===1)return r._result.default;throw r._result}var on={current:null},Lh={transition:null},a2={ReactCurrentDispatcher:on,ReactCurrentBatchConfig:Lh,ReactCurrentOwner:$_};function Ux(){throw Error("act(...) is not supported in production builds of React.")}nt.Children={map:Bf,forEach:function(r,e,t){Bf(r,function(){e.apply(this,arguments)},t)},count:function(r){var e=0;return Bf(r,function(){e++}),e},toArray:function(r){return Bf(r,function(e){return e})||[]},only:function(r){if(!W_(r))throw Error("React.Children.only expected to receive a single React element child.");return r}};nt.Component=Pc;nt.Fragment=zU;nt.Profiler=JU;nt.PureComponent=K_;nt.StrictMode=YU;nt.Suspense=e2;nt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=a2;nt.act=Ux;nt.cloneElement=function(r,e,t){if(r==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+r+".");var n=Px({},r.props),i=r.key,o=r.ref,s=r._owner;if(e!=null){if(e.ref!==void 0&&(o=e.ref,s=$_.current),e.key!==void 0&&(i=""+e.key),r.type&&r.type.defaultProps)var a=r.type.defaultProps;for(l in e)Dx.call(e,l)&&!Nx.hasOwnProperty(l)&&(n[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)n.children=t;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];n.children=a}return{$$typeof:tf,type:r.type,key:i,ref:o,props:n,_owner:s}};nt.createContext=function(r){return r={$$typeof:QU,_currentValue:r,_currentValue2:r,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},r.Provider={$$typeof:XU,_context:r},r.Consumer=r};nt.createElement=Lx;nt.createFactory=function(r){var e=Lx.bind(null,r);return e.type=r,e};nt.createRef=function(){return{current:null}};nt.forwardRef=function(r){return{$$typeof:ZU,render:r}};nt.isValidElement=W_;nt.lazy=function(r){return{$$typeof:r2,_payload:{_status:-1,_result:r},_init:s2}};nt.memo=function(r,e){return{$$typeof:t2,type:r,compare:e===void 0?null:e}};nt.startTransition=function(r){var e=Lh.transition;Lh.transition={};try{r()}finally{Lh.transition=e}};nt.unstable_act=Ux;nt.useCallback=function(r,e){return on.current.useCallback(r,e)};nt.useContext=function(r){return on.current.useContext(r)};nt.useDebugValue=function(){};nt.useDeferredValue=function(r){return on.current.useDeferredValue(r)};nt.useEffect=function(r,e){return on.current.useEffect(r,e)};nt.useId=function(){return on.current.useId()};nt.useImperativeHandle=function(r,e,t){return on.current.useImperativeHandle(r,e,t)};nt.useInsertionEffect=function(r,e){return on.current.useInsertionEffect(r,e)};nt.useLayoutEffect=function(r,e){return on.current.useLayoutEffect(r,e)};nt.useMemo=function(r,e){return on.current.useMemo(r,e)};nt.useReducer=function(r,e,t){return on.current.useReducer(r,e,t)};nt.useRef=function(r){return on.current.useRef(r)};nt.useState=function(r){return on.current.useState(r)};nt.useSyncExternalStore=function(r,e,t){return on.current.useSyncExternalStore(r,e,t)};nt.useTransition=function(){return on.current.useTransition()};nt.version="18.3.1";xx.exports=nt;var _=xx.exports;const ve=qa(_),Iv=qU({__proto__:null,default:ve},[_]);/**
10
- * @license React
11
- * react-jsx-runtime.production.min.js
12
- *
13
- * Copyright (c) Facebook, Inc. and its affiliates.
14
- *
15
- * This source code is licensed under the MIT license found in the
16
- * LICENSE file in the root directory of this source tree.
17
- */var l2=_,c2=Symbol.for("react.element"),u2=Symbol.for("react.fragment"),d2=Object.prototype.hasOwnProperty,f2=l2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,h2={key:!0,ref:!0,__self:!0,__source:!0};function jx(r,e,t){var n,i={},o=null,s=null;t!==void 0&&(o=""+t),e.key!==void 0&&(o=""+e.key),e.ref!==void 0&&(s=e.ref);for(n in e)d2.call(e,n)&&!h2.hasOwnProperty(n)&&(i[n]=e[n]);if(r&&r.defaultProps)for(n in e=r.defaultProps,e)i[n]===void 0&&(i[n]=e[n]);return{$$typeof:c2,type:r,key:o,ref:s,props:i,_owner:f2.current}}kv.Fragment=u2;kv.jsx=jx;kv.jsxs=jx;Ix.exports=kv;var g=Ix.exports,Fx={exports:{}},Kn={},Bx={exports:{}},Kx={};/**
18
- * @license React
19
- * scheduler.production.min.js
20
- *
21
- * Copyright (c) Facebook, Inc. and its affiliates.
22
- *
23
- * This source code is licensed under the MIT license found in the
24
- * LICENSE file in the root directory of this source tree.
25
- */(function(r){function e(q,z){var Q=q.length;q.push(z);e:for(;0<Q;){var Ie=Q-1>>>1,Y=q[Ie];if(0<i(Y,z))q[Ie]=z,q[Q]=Y,Q=Ie;else break e}}function t(q){return q.length===0?null:q[0]}function n(q){if(q.length===0)return null;var z=q[0],Q=q.pop();if(Q!==z){q[0]=Q;e:for(var Ie=0,Y=q.length,le=Y>>>1;Ie<le;){var B=2*(Ie+1)-1,W=q[B],A=B+1,D=q[A];if(0>i(W,Q))A<Y&&0>i(D,W)?(q[Ie]=D,q[A]=Q,Ie=A):(q[Ie]=W,q[B]=Q,Ie=B);else if(A<Y&&0>i(D,Q))q[Ie]=D,q[A]=Q,Ie=A;else break e}}return z}function i(q,z){var Q=q.sortIndex-z.sortIndex;return Q!==0?Q:q.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;r.unstable_now=function(){return o.now()}}else{var s=Date,a=s.now();r.unstable_now=function(){return s.now()-a}}var l=[],c=[],u=1,d=null,f=3,p=!1,h=!1,m=!1,E=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function R(q){for(var z=t(c);z!==null;){if(z.callback===null)n(c);else if(z.startTime<=q)n(c),z.sortIndex=z.expirationTime,e(l,z);else break;z=t(c)}}function k(q){if(m=!1,R(q),!h)if(t(l)!==null)h=!0,re(x);else{var z=t(c);z!==null&&ae(k,z.startTime-q)}}function x(q,z){h=!1,m&&(m=!1,y(C),C=-1),p=!0;var Q=f;try{for(R(z),d=t(l);d!==null&&(!(d.expirationTime>z)||q&&!H());){var Ie=d.callback;if(typeof Ie=="function"){d.callback=null,f=d.priorityLevel;var Y=Ie(d.expirationTime<=z);z=r.unstable_now(),typeof Y=="function"?d.callback=Y:d===t(l)&&n(l),R(z)}else n(l);d=t(l)}if(d!==null)var le=!0;else{var B=t(c);B!==null&&ae(k,B.startTime-z),le=!1}return le}finally{d=null,f=Q,p=!1}}var T=!1,O=null,C=-1,N=5,F=-1;function H(){return!(r.unstable_now()-F<N)}function ie(){if(O!==null){var q=r.unstable_now();F=q;var z=!0;try{z=O(!0,q)}finally{z?$():(T=!1,O=null)}}else T=!1}var $;if(typeof S=="function")$=function(){S(ie)};else if(typeof MessageChannel<"u"){var X=new MessageChannel,oe=X.port2;X.port1.onmessage=ie,$=function(){oe.postMessage(null)}}else $=function(){E(ie,0)};function re(q){O=q,T||(T=!0,$())}function ae(q,z){C=E(function(){q(r.unstable_now())},z)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(q){q.callback=null},r.unstable_continueExecution=function(){h||p||(h=!0,re(x))},r.unstable_forceFrameRate=function(q){0>q||125<q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):N=0<q?Math.floor(1e3/q):5},r.unstable_getCurrentPriorityLevel=function(){return f},r.unstable_getFirstCallbackNode=function(){return t(l)},r.unstable_next=function(q){switch(f){case 1:case 2:case 3:var z=3;break;default:z=f}var Q=f;f=z;try{return q()}finally{f=Q}},r.unstable_pauseExecution=function(){},r.unstable_requestPaint=function(){},r.unstable_runWithPriority=function(q,z){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var Q=f;f=q;try{return z()}finally{f=Q}},r.unstable_scheduleCallback=function(q,z,Q){var Ie=r.unstable_now();switch(typeof Q=="object"&&Q!==null?(Q=Q.delay,Q=typeof Q=="number"&&0<Q?Ie+Q:Ie):Q=Ie,q){case 1:var Y=-1;break;case 2:Y=250;break;case 5:Y=1073741823;break;case 4:Y=1e4;break;default:Y=5e3}return Y=Q+Y,q={id:u++,callback:z,priorityLevel:q,startTime:Q,expirationTime:Y,sortIndex:-1},Q>Ie?(q.sortIndex=Q,e(c,q),t(l)===null&&q===t(c)&&(m?(y(C),C=-1):m=!0,ae(k,Q-Ie))):(q.sortIndex=Y,e(l,q),h||p||(h=!0,re(x))),q},r.unstable_shouldYield=H,r.unstable_wrapCallback=function(q){var z=f;return function(){var Q=f;f=z;try{return q.apply(this,arguments)}finally{f=Q}}}})(Kx);Bx.exports=Kx;var p2=Bx.exports;/**
26
- * @license React
27
- * react-dom.production.min.js
28
- *
29
- * Copyright (c) Facebook, Inc. and its affiliates.
30
- *
31
- * This source code is licensed under the MIT license found in the
32
- * LICENSE file in the root directory of this source tree.
33
- */var v2=_,Bn=p2;function he(r){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+r,t=1;t<arguments.length;t++)e+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+r+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Vx=new Set,ud={};function Ga(r,e){sc(r,e),sc(r+"Capture",e)}function sc(r,e){for(ud[r]=e,r=0;r<e.length;r++)Vx.add(e[r])}var Oo=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),zy=Object.prototype.hasOwnProperty,m2=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,$0={},W0={};function g2(r){return zy.call(W0,r)?!0:zy.call($0,r)?!1:m2.test(r)?W0[r]=!0:($0[r]=!0,!1)}function y2(r,e,t,n){if(t!==null&&t.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:t!==null?!t.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function S2(r,e,t,n){if(e===null||typeof e>"u"||y2(r,e,t,n))return!0;if(n)return!1;if(t!==null)switch(t.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function sn(r,e,t,n,i,o,s){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=t,this.propertyName=r,this.type=e,this.sanitizeURL=o,this.removeEmptyString=s}var Lr={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){Lr[r]=new sn(r,0,!1,r,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var e=r[0];Lr[e]=new sn(e,1,!1,r[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(r){Lr[r]=new sn(r,2,!1,r.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){Lr[r]=new sn(r,2,!1,r,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(r){Lr[r]=new sn(r,3,!1,r.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(r){Lr[r]=new sn(r,3,!0,r,null,!1,!1)});["capture","download"].forEach(function(r){Lr[r]=new sn(r,4,!1,r,null,!1,!1)});["cols","rows","size","span"].forEach(function(r){Lr[r]=new sn(r,6,!1,r,null,!1,!1)});["rowSpan","start"].forEach(function(r){Lr[r]=new sn(r,5,!1,r.toLowerCase(),null,!1,!1)});var q_=/[\-:]([a-z])/g;function G_(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var e=r.replace(q_,G_);Lr[e]=new sn(e,1,!1,r,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var e=r.replace(q_,G_);Lr[e]=new sn(e,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(r){var e=r.replace(q_,G_);Lr[e]=new sn(e,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(r){Lr[r]=new sn(r,1,!1,r.toLowerCase(),null,!1,!1)});Lr.xlinkHref=new sn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(r){Lr[r]=new sn(r,1,!1,r.toLowerCase(),null,!0,!0)});function H_(r,e,t,n){var i=Lr.hasOwnProperty(e)?Lr[e]:null;(i!==null?i.type!==0:n||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(S2(e,t,i,n)&&(t=null),n||i===null?g2(e)&&(t===null?r.removeAttribute(e):r.setAttribute(e,""+t)):i.mustUseProperty?r[i.propertyName]=t===null?i.type===3?!1:"":t:(e=i.attributeName,n=i.attributeNamespace,t===null?r.removeAttribute(e):(i=i.type,t=i===3||i===4&&t===!0?"":""+t,n?r.setAttributeNS(n,e,t):r.setAttribute(e,t))))}var Uo=v2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Kf=Symbol.for("react.element"),kl=Symbol.for("react.portal"),Il=Symbol.for("react.fragment"),z_=Symbol.for("react.strict_mode"),Yy=Symbol.for("react.profiler"),$x=Symbol.for("react.provider"),Wx=Symbol.for("react.context"),Y_=Symbol.for("react.forward_ref"),Jy=Symbol.for("react.suspense"),Xy=Symbol.for("react.suspense_list"),J_=Symbol.for("react.memo"),as=Symbol.for("react.lazy"),qx=Symbol.for("react.offscreen"),q0=Symbol.iterator;function Qc(r){return r===null||typeof r!="object"?null:(r=q0&&r[q0]||r["@@iterator"],typeof r=="function"?r:null)}var Ft=Object.assign,ig;function ku(r){if(ig===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);ig=e&&e[1]||""}return`
34
- `+ig+r}var og=!1;function sg(r,e){if(!r||og)return"";og=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(c){var n=c}Reflect.construct(r,[],e)}else{try{e.call()}catch(c){n=c}r.call(e.prototype)}else{try{throw Error()}catch(c){n=c}r()}}catch(c){if(c&&n&&typeof c.stack=="string"){for(var i=c.stack.split(`
35
- `),o=n.stack.split(`
36
- `),s=i.length-1,a=o.length-1;1<=s&&0<=a&&i[s]!==o[a];)a--;for(;1<=s&&0<=a;s--,a--)if(i[s]!==o[a]){if(s!==1||a!==1)do if(s--,a--,0>a||i[s]!==o[a]){var l=`
37
- `+i[s].replace(" at new "," at ");return r.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",r.displayName)),l}while(1<=s&&0<=a);break}}}finally{og=!1,Error.prepareStackTrace=t}return(r=r?r.displayName||r.name:"")?ku(r):""}function b2(r){switch(r.tag){case 5:return ku(r.type);case 16:return ku("Lazy");case 13:return ku("Suspense");case 19:return ku("SuspenseList");case 0:case 2:case 15:return r=sg(r.type,!1),r;case 11:return r=sg(r.type.render,!1),r;case 1:return r=sg(r.type,!0),r;default:return""}}function Qy(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case Il:return"Fragment";case kl:return"Portal";case Yy:return"Profiler";case z_:return"StrictMode";case Jy:return"Suspense";case Xy:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case Wx:return(r.displayName||"Context")+".Consumer";case $x:return(r._context.displayName||"Context")+".Provider";case Y_:var e=r.render;return r=r.displayName,r||(r=e.displayName||e.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case J_:return e=r.displayName||null,e!==null?e:Qy(r.type)||"Memo";case as:e=r._payload,r=r._init;try{return Qy(r(e))}catch{}}return null}function _2(r){var e=r.type;switch(r.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return r=e.render,r=r.displayName||r.name||"",e.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qy(e);case 8:return e===z_?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function xs(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Gx(r){var e=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function E2(r){var e=Gx(r)?"checked":"value",t=Object.getOwnPropertyDescriptor(r.constructor.prototype,e),n=""+r[e];if(!r.hasOwnProperty(e)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var i=t.get,o=t.set;return Object.defineProperty(r,e,{configurable:!0,get:function(){return i.call(this)},set:function(s){n=""+s,o.call(this,s)}}),Object.defineProperty(r,e,{enumerable:t.enumerable}),{getValue:function(){return n},setValue:function(s){n=""+s},stopTracking:function(){r._valueTracker=null,delete r[e]}}}}function Vf(r){r._valueTracker||(r._valueTracker=E2(r))}function Hx(r){if(!r)return!1;var e=r._valueTracker;if(!e)return!0;var t=e.getValue(),n="";return r&&(n=Gx(r)?r.checked?"true":"false":r.value),r=n,r!==t?(e.setValue(r),!0):!1}function gp(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function Zy(r,e){var t=e.checked;return Ft({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??r._wrapperState.initialChecked})}function G0(r,e){var t=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;t=xs(e.value!=null?e.value:t),r._wrapperState={initialChecked:n,initialValue:t,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function zx(r,e){e=e.checked,e!=null&&H_(r,"checked",e,!1)}function eS(r,e){zx(r,e);var t=xs(e.value),n=e.type;if(t!=null)n==="number"?(t===0&&r.value===""||r.value!=t)&&(r.value=""+t):r.value!==""+t&&(r.value=""+t);else if(n==="submit"||n==="reset"){r.removeAttribute("value");return}e.hasOwnProperty("value")?tS(r,e.type,t):e.hasOwnProperty("defaultValue")&&tS(r,e.type,xs(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(r.defaultChecked=!!e.defaultChecked)}function H0(r,e,t){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+r._wrapperState.initialValue,t||e===r.value||(r.value=e),r.defaultValue=e}t=r.name,t!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,t!==""&&(r.name=t)}function tS(r,e,t){(e!=="number"||gp(r.ownerDocument)!==r)&&(t==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+t&&(r.defaultValue=""+t))}var Iu=Array.isArray;function Vl(r,e,t,n){if(r=r.options,e){e={};for(var i=0;i<t.length;i++)e["$"+t[i]]=!0;for(t=0;t<r.length;t++)i=e.hasOwnProperty("$"+r[t].value),r[t].selected!==i&&(r[t].selected=i),i&&n&&(r[t].defaultSelected=!0)}else{for(t=""+xs(t),e=null,i=0;i<r.length;i++){if(r[i].value===t){r[i].selected=!0,n&&(r[i].defaultSelected=!0);return}e!==null||r[i].disabled||(e=r[i])}e!==null&&(e.selected=!0)}}function rS(r,e){if(e.dangerouslySetInnerHTML!=null)throw Error(he(91));return Ft({},e,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function z0(r,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(he(92));if(Iu(t)){if(1<t.length)throw Error(he(93));t=t[0]}e=t}e==null&&(e=""),t=e}r._wrapperState={initialValue:xs(t)}}function Yx(r,e){var t=xs(e.value),n=xs(e.defaultValue);t!=null&&(t=""+t,t!==r.value&&(r.value=t),e.defaultValue==null&&r.defaultValue!==t&&(r.defaultValue=t)),n!=null&&(r.defaultValue=""+n)}function Y0(r){var e=r.textContent;e===r._wrapperState.initialValue&&e!==""&&e!==null&&(r.value=e)}function Jx(r){switch(r){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function nS(r,e){return r==null||r==="http://www.w3.org/1999/xhtml"?Jx(e):r==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var $f,Xx=function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,t,n,i){MSApp.execUnsafeLocalFunction(function(){return r(e,t,n,i)})}:r}(function(r,e){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=e;else{for($f=$f||document.createElement("div"),$f.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=$f.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;e.firstChild;)r.appendChild(e.firstChild)}});function dd(r,e){if(e){var t=r.firstChild;if(t&&t===r.lastChild&&t.nodeType===3){t.nodeValue=e;return}}r.textContent=e}var $u={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},w2=["Webkit","ms","Moz","O"];Object.keys($u).forEach(function(r){w2.forEach(function(e){e=e+r.charAt(0).toUpperCase()+r.substring(1),$u[e]=$u[r]})});function Qx(r,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||$u.hasOwnProperty(r)&&$u[r]?(""+e).trim():e+"px"}function Zx(r,e){r=r.style;for(var t in e)if(e.hasOwnProperty(t)){var n=t.indexOf("--")===0,i=Qx(t,e[t],n);t==="float"&&(t="cssFloat"),n?r.setProperty(t,i):r[t]=i}}var T2=Ft({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function iS(r,e){if(e){if(T2[r]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(he(137,r));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(he(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(he(61))}if(e.style!=null&&typeof e.style!="object")throw Error(he(62))}}function oS(r,e){if(r.indexOf("-")===-1)return typeof e.is=="string";switch(r){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var sS=null;function X_(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var aS=null,$l=null,Wl=null;function J0(r){if(r=of(r)){if(typeof aS!="function")throw Error(he(280));var e=r.stateNode;e&&(e=Av(e),aS(r.stateNode,r.type,e))}}function eO(r){$l?Wl?Wl.push(r):Wl=[r]:$l=r}function tO(){if($l){var r=$l,e=Wl;if(Wl=$l=null,J0(r),e)for(r=0;r<e.length;r++)J0(e[r])}}function rO(r,e){return r(e)}function nO(){}var ag=!1;function iO(r,e,t){if(ag)return r(e,t);ag=!0;try{return rO(r,e,t)}finally{ag=!1,($l!==null||Wl!==null)&&(nO(),tO())}}function fd(r,e){var t=r.stateNode;if(t===null)return null;var n=Av(t);if(n===null)return null;t=n[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(r=r.type,n=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!n;break e;default:r=!1}if(r)return null;if(t&&typeof t!="function")throw Error(he(231,e,typeof t));return t}var lS=!1;if(Oo)try{var Zc={};Object.defineProperty(Zc,"passive",{get:function(){lS=!0}}),window.addEventListener("test",Zc,Zc),window.removeEventListener("test",Zc,Zc)}catch{lS=!1}function R2(r,e,t,n,i,o,s,a,l){var c=Array.prototype.slice.call(arguments,3);try{e.apply(t,c)}catch(u){this.onError(u)}}var Wu=!1,yp=null,Sp=!1,cS=null,C2={onError:function(r){Wu=!0,yp=r}};function k2(r,e,t,n,i,o,s,a,l){Wu=!1,yp=null,R2.apply(C2,arguments)}function I2(r,e,t,n,i,o,s,a,l){if(k2.apply(this,arguments),Wu){if(Wu){var c=yp;Wu=!1,yp=null}else throw Error(he(198));Sp||(Sp=!0,cS=c)}}function Ha(r){var e=r,t=r;if(r.alternate)for(;e.return;)e=e.return;else{r=e;do e=r,e.flags&4098&&(t=e.return),r=e.return;while(r)}return e.tag===3?t:null}function oO(r){if(r.tag===13){var e=r.memoizedState;if(e===null&&(r=r.alternate,r!==null&&(e=r.memoizedState)),e!==null)return e.dehydrated}return null}function X0(r){if(Ha(r)!==r)throw Error(he(188))}function x2(r){var e=r.alternate;if(!e){if(e=Ha(r),e===null)throw Error(he(188));return e!==r?null:r}for(var t=r,n=e;;){var i=t.return;if(i===null)break;var o=i.alternate;if(o===null){if(n=i.return,n!==null){t=n;continue}break}if(i.child===o.child){for(o=i.child;o;){if(o===t)return X0(i),r;if(o===n)return X0(i),e;o=o.sibling}throw Error(he(188))}if(t.return!==n.return)t=i,n=o;else{for(var s=!1,a=i.child;a;){if(a===t){s=!0,t=i,n=o;break}if(a===n){s=!0,n=i,t=o;break}a=a.sibling}if(!s){for(a=o.child;a;){if(a===t){s=!0,t=o,n=i;break}if(a===n){s=!0,n=o,t=i;break}a=a.sibling}if(!s)throw Error(he(189))}}if(t.alternate!==n)throw Error(he(190))}if(t.tag!==3)throw Error(he(188));return t.stateNode.current===t?r:e}function sO(r){return r=x2(r),r!==null?aO(r):null}function aO(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var e=aO(r);if(e!==null)return e;r=r.sibling}return null}var lO=Bn.unstable_scheduleCallback,Q0=Bn.unstable_cancelCallback,O2=Bn.unstable_shouldYield,P2=Bn.unstable_requestPaint,Jt=Bn.unstable_now,M2=Bn.unstable_getCurrentPriorityLevel,Q_=Bn.unstable_ImmediatePriority,cO=Bn.unstable_UserBlockingPriority,bp=Bn.unstable_NormalPriority,A2=Bn.unstable_LowPriority,uO=Bn.unstable_IdlePriority,xv=null,Yi=null;function D2(r){if(Yi&&typeof Yi.onCommitFiberRoot=="function")try{Yi.onCommitFiberRoot(xv,r,void 0,(r.current.flags&128)===128)}catch{}}var Si=Math.clz32?Math.clz32:U2,N2=Math.log,L2=Math.LN2;function U2(r){return r>>>=0,r===0?32:31-(N2(r)/L2|0)|0}var Wf=64,qf=4194304;function xu(r){switch(r&-r){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function _p(r,e){var t=r.pendingLanes;if(t===0)return 0;var n=0,i=r.suspendedLanes,o=r.pingedLanes,s=t&268435455;if(s!==0){var a=s&~i;a!==0?n=xu(a):(o&=s,o!==0&&(n=xu(o)))}else s=t&~i,s!==0?n=xu(s):o!==0&&(n=xu(o));if(n===0)return 0;if(e!==0&&e!==n&&!(e&i)&&(i=n&-n,o=e&-e,i>=o||i===16&&(o&4194240)!==0))return e;if(n&4&&(n|=t&16),e=r.entangledLanes,e!==0)for(r=r.entanglements,e&=n;0<e;)t=31-Si(e),i=1<<t,n|=r[t],e&=~i;return n}function j2(r,e){switch(r){case 1:case 2:case 4:return e+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function F2(r,e){for(var t=r.suspendedLanes,n=r.pingedLanes,i=r.expirationTimes,o=r.pendingLanes;0<o;){var s=31-Si(o),a=1<<s,l=i[s];l===-1?(!(a&t)||a&n)&&(i[s]=j2(a,e)):l<=e&&(r.expiredLanes|=a),o&=~a}}function uS(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function dO(){var r=Wf;return Wf<<=1,!(Wf&4194240)&&(Wf=64),r}function lg(r){for(var e=[],t=0;31>t;t++)e.push(r);return e}function rf(r,e,t){r.pendingLanes|=e,e!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,e=31-Si(e),r[e]=t}function B2(r,e){var t=r.pendingLanes&~e;r.pendingLanes=e,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=e,r.mutableReadLanes&=e,r.entangledLanes&=e,e=r.entanglements;var n=r.eventTimes;for(r=r.expirationTimes;0<t;){var i=31-Si(t),o=1<<i;e[i]=0,n[i]=-1,r[i]=-1,t&=~o}}function Z_(r,e){var t=r.entangledLanes|=e;for(r=r.entanglements;t;){var n=31-Si(t),i=1<<n;i&e|r[n]&e&&(r[n]|=e),t&=~i}}var ft=0;function fO(r){return r&=-r,1<r?4<r?r&268435455?16:536870912:4:1}var hO,eE,pO,vO,mO,dS=!1,Gf=[],ys=null,Ss=null,bs=null,hd=new Map,pd=new Map,ds=[],K2="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Z0(r,e){switch(r){case"focusin":case"focusout":ys=null;break;case"dragenter":case"dragleave":Ss=null;break;case"mouseover":case"mouseout":bs=null;break;case"pointerover":case"pointerout":hd.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":pd.delete(e.pointerId)}}function eu(r,e,t,n,i,o){return r===null||r.nativeEvent!==o?(r={blockedOn:e,domEventName:t,eventSystemFlags:n,nativeEvent:o,targetContainers:[i]},e!==null&&(e=of(e),e!==null&&eE(e)),r):(r.eventSystemFlags|=n,e=r.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),r)}function V2(r,e,t,n,i){switch(e){case"focusin":return ys=eu(ys,r,e,t,n,i),!0;case"dragenter":return Ss=eu(Ss,r,e,t,n,i),!0;case"mouseover":return bs=eu(bs,r,e,t,n,i),!0;case"pointerover":var o=i.pointerId;return hd.set(o,eu(hd.get(o)||null,r,e,t,n,i)),!0;case"gotpointercapture":return o=i.pointerId,pd.set(o,eu(pd.get(o)||null,r,e,t,n,i)),!0}return!1}function gO(r){var e=_a(r.target);if(e!==null){var t=Ha(e);if(t!==null){if(e=t.tag,e===13){if(e=oO(t),e!==null){r.blockedOn=e,mO(r.priority,function(){pO(t)});return}}else if(e===3&&t.stateNode.current.memoizedState.isDehydrated){r.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}r.blockedOn=null}function Uh(r){if(r.blockedOn!==null)return!1;for(var e=r.targetContainers;0<e.length;){var t=fS(r.domEventName,r.eventSystemFlags,e[0],r.nativeEvent);if(t===null){t=r.nativeEvent;var n=new t.constructor(t.type,t);sS=n,t.target.dispatchEvent(n),sS=null}else return e=of(t),e!==null&&eE(e),r.blockedOn=t,!1;e.shift()}return!0}function eT(r,e,t){Uh(r)&&t.delete(e)}function $2(){dS=!1,ys!==null&&Uh(ys)&&(ys=null),Ss!==null&&Uh(Ss)&&(Ss=null),bs!==null&&Uh(bs)&&(bs=null),hd.forEach(eT),pd.forEach(eT)}function tu(r,e){r.blockedOn===e&&(r.blockedOn=null,dS||(dS=!0,Bn.unstable_scheduleCallback(Bn.unstable_NormalPriority,$2)))}function vd(r){function e(i){return tu(i,r)}if(0<Gf.length){tu(Gf[0],r);for(var t=1;t<Gf.length;t++){var n=Gf[t];n.blockedOn===r&&(n.blockedOn=null)}}for(ys!==null&&tu(ys,r),Ss!==null&&tu(Ss,r),bs!==null&&tu(bs,r),hd.forEach(e),pd.forEach(e),t=0;t<ds.length;t++)n=ds[t],n.blockedOn===r&&(n.blockedOn=null);for(;0<ds.length&&(t=ds[0],t.blockedOn===null);)gO(t),t.blockedOn===null&&ds.shift()}var ql=Uo.ReactCurrentBatchConfig,Ep=!0;function W2(r,e,t,n){var i=ft,o=ql.transition;ql.transition=null;try{ft=1,tE(r,e,t,n)}finally{ft=i,ql.transition=o}}function q2(r,e,t,n){var i=ft,o=ql.transition;ql.transition=null;try{ft=4,tE(r,e,t,n)}finally{ft=i,ql.transition=o}}function tE(r,e,t,n){if(Ep){var i=fS(r,e,t,n);if(i===null)yg(r,e,n,wp,t),Z0(r,n);else if(V2(i,r,e,t,n))n.stopPropagation();else if(Z0(r,n),e&4&&-1<K2.indexOf(r)){for(;i!==null;){var o=of(i);if(o!==null&&hO(o),o=fS(r,e,t,n),o===null&&yg(r,e,n,wp,t),o===i)break;i=o}i!==null&&n.stopPropagation()}else yg(r,e,n,null,t)}}var wp=null;function fS(r,e,t,n){if(wp=null,r=X_(n),r=_a(r),r!==null)if(e=Ha(r),e===null)r=null;else if(t=e.tag,t===13){if(r=oO(e),r!==null)return r;r=null}else if(t===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;r=null}else e!==r&&(r=null);return wp=r,null}function yO(r){switch(r){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(M2()){case Q_:return 1;case cO:return 4;case bp:case A2:return 16;case uO:return 536870912;default:return 16}default:return 16}}var ps=null,rE=null,jh=null;function SO(){if(jh)return jh;var r,e=rE,t=e.length,n,i="value"in ps?ps.value:ps.textContent,o=i.length;for(r=0;r<t&&e[r]===i[r];r++);var s=t-r;for(n=1;n<=s&&e[t-n]===i[o-n];n++);return jh=i.slice(r,1<n?1-n:void 0)}function Fh(r){var e=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&e===13&&(r=13)):r=e,r===10&&(r=13),32<=r||r===13?r:0}function Hf(){return!0}function tT(){return!1}function Vn(r){function e(t,n,i,o,s){this._reactName=t,this._targetInst=i,this.type=n,this.nativeEvent=o,this.target=s,this.currentTarget=null;for(var a in r)r.hasOwnProperty(a)&&(t=r[a],this[a]=t?t(o):o[a]);return this.isDefaultPrevented=(o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===!1)?Hf:tT,this.isPropagationStopped=tT,this}return Ft(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=Hf)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=Hf)},persist:function(){},isPersistent:Hf}),e}var Mc={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},nE=Vn(Mc),nf=Ft({},Mc,{view:0,detail:0}),G2=Vn(nf),cg,ug,ru,Ov=Ft({},nf,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:iE,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==ru&&(ru&&r.type==="mousemove"?(cg=r.screenX-ru.screenX,ug=r.screenY-ru.screenY):ug=cg=0,ru=r),cg)},movementY:function(r){return"movementY"in r?r.movementY:ug}}),rT=Vn(Ov),H2=Ft({},Ov,{dataTransfer:0}),z2=Vn(H2),Y2=Ft({},nf,{relatedTarget:0}),dg=Vn(Y2),J2=Ft({},Mc,{animationName:0,elapsedTime:0,pseudoElement:0}),X2=Vn(J2),Q2=Ft({},Mc,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),Z2=Vn(Q2),ej=Ft({},Mc,{data:0}),nT=Vn(ej),tj={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},rj={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},nj={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function ij(r){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(r):(r=nj[r])?!!e[r]:!1}function iE(){return ij}var oj=Ft({},nf,{key:function(r){if(r.key){var e=tj[r.key]||r.key;if(e!=="Unidentified")return e}return r.type==="keypress"?(r=Fh(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?rj[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:iE,charCode:function(r){return r.type==="keypress"?Fh(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?Fh(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),sj=Vn(oj),aj=Ft({},Ov,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),iT=Vn(aj),lj=Ft({},nf,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:iE}),cj=Vn(lj),uj=Ft({},Mc,{propertyName:0,elapsedTime:0,pseudoElement:0}),dj=Vn(uj),fj=Ft({},Ov,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),hj=Vn(fj),pj=[9,13,27,32],oE=Oo&&"CompositionEvent"in window,qu=null;Oo&&"documentMode"in document&&(qu=document.documentMode);var vj=Oo&&"TextEvent"in window&&!qu,bO=Oo&&(!oE||qu&&8<qu&&11>=qu),oT=" ",sT=!1;function _O(r,e){switch(r){case"keyup":return pj.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function EO(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var xl=!1;function mj(r,e){switch(r){case"compositionend":return EO(e);case"keypress":return e.which!==32?null:(sT=!0,oT);case"textInput":return r=e.data,r===oT&&sT?null:r;default:return null}}function gj(r,e){if(xl)return r==="compositionend"||!oE&&_O(r,e)?(r=SO(),jh=rE=ps=null,xl=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return bO&&e.locale!=="ko"?null:e.data;default:return null}}var yj={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function aT(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e==="input"?!!yj[r.type]:e==="textarea"}function wO(r,e,t,n){eO(n),e=Tp(e,"onChange"),0<e.length&&(t=new nE("onChange","change",null,t,n),r.push({event:t,listeners:e}))}var Gu=null,md=null;function Sj(r){DO(r,0)}function Pv(r){var e=Ml(r);if(Hx(e))return r}function bj(r,e){if(r==="change")return e}var TO=!1;if(Oo){var fg;if(Oo){var hg="oninput"in document;if(!hg){var lT=document.createElement("div");lT.setAttribute("oninput","return;"),hg=typeof lT.oninput=="function"}fg=hg}else fg=!1;TO=fg&&(!document.documentMode||9<document.documentMode)}function cT(){Gu&&(Gu.detachEvent("onpropertychange",RO),md=Gu=null)}function RO(r){if(r.propertyName==="value"&&Pv(md)){var e=[];wO(e,md,r,X_(r)),iO(Sj,e)}}function _j(r,e,t){r==="focusin"?(cT(),Gu=e,md=t,Gu.attachEvent("onpropertychange",RO)):r==="focusout"&&cT()}function Ej(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return Pv(md)}function wj(r,e){if(r==="click")return Pv(e)}function Tj(r,e){if(r==="input"||r==="change")return Pv(e)}function Rj(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var Ti=typeof Object.is=="function"?Object.is:Rj;function gd(r,e){if(Ti(r,e))return!0;if(typeof r!="object"||r===null||typeof e!="object"||e===null)return!1;var t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;for(n=0;n<t.length;n++){var i=t[n];if(!zy.call(e,i)||!Ti(r[i],e[i]))return!1}return!0}function uT(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function dT(r,e){var t=uT(r);r=0;for(var n;t;){if(t.nodeType===3){if(n=r+t.textContent.length,r<=e&&n>=e)return{node:t,offset:e-r};r=n}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=uT(t)}}function CO(r,e){return r&&e?r===e?!0:r&&r.nodeType===3?!1:e&&e.nodeType===3?CO(r,e.parentNode):"contains"in r?r.contains(e):r.compareDocumentPosition?!!(r.compareDocumentPosition(e)&16):!1:!1}function kO(){for(var r=window,e=gp();e instanceof r.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)r=e.contentWindow;else break;e=gp(r.document)}return e}function sE(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e&&(e==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||e==="textarea"||r.contentEditable==="true")}function Cj(r){var e=kO(),t=r.focusedElem,n=r.selectionRange;if(e!==t&&t&&t.ownerDocument&&CO(t.ownerDocument.documentElement,t)){if(n!==null&&sE(t)){if(e=n.start,r=n.end,r===void 0&&(r=e),"selectionStart"in t)t.selectionStart=e,t.selectionEnd=Math.min(r,t.value.length);else if(r=(e=t.ownerDocument||document)&&e.defaultView||window,r.getSelection){r=r.getSelection();var i=t.textContent.length,o=Math.min(n.start,i);n=n.end===void 0?o:Math.min(n.end,i),!r.extend&&o>n&&(i=n,n=o,o=i),i=dT(t,o);var s=dT(t,n);i&&s&&(r.rangeCount!==1||r.anchorNode!==i.node||r.anchorOffset!==i.offset||r.focusNode!==s.node||r.focusOffset!==s.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),r.removeAllRanges(),o>n?(r.addRange(e),r.extend(s.node,s.offset)):(e.setEnd(s.node,s.offset),r.addRange(e)))}}for(e=[],r=t;r=r.parentNode;)r.nodeType===1&&e.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t<e.length;t++)r=e[t],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var kj=Oo&&"documentMode"in document&&11>=document.documentMode,Ol=null,hS=null,Hu=null,pS=!1;function fT(r,e,t){var n=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;pS||Ol==null||Ol!==gp(n)||(n=Ol,"selectionStart"in n&&sE(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),Hu&&gd(Hu,n)||(Hu=n,n=Tp(hS,"onSelect"),0<n.length&&(e=new nE("onSelect","select",null,e,t),r.push({event:e,listeners:n}),e.target=Ol)))}function zf(r,e){var t={};return t[r.toLowerCase()]=e.toLowerCase(),t["Webkit"+r]="webkit"+e,t["Moz"+r]="moz"+e,t}var Pl={animationend:zf("Animation","AnimationEnd"),animationiteration:zf("Animation","AnimationIteration"),animationstart:zf("Animation","AnimationStart"),transitionend:zf("Transition","TransitionEnd")},pg={},IO={};Oo&&(IO=document.createElement("div").style,"AnimationEvent"in window||(delete Pl.animationend.animation,delete Pl.animationiteration.animation,delete Pl.animationstart.animation),"TransitionEvent"in window||delete Pl.transitionend.transition);function Mv(r){if(pg[r])return pg[r];if(!Pl[r])return r;var e=Pl[r],t;for(t in e)if(e.hasOwnProperty(t)&&t in IO)return pg[r]=e[t];return r}var xO=Mv("animationend"),OO=Mv("animationiteration"),PO=Mv("animationstart"),MO=Mv("transitionend"),AO=new Map,hT="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function js(r,e){AO.set(r,e),Ga(e,[r])}for(var vg=0;vg<hT.length;vg++){var mg=hT[vg],Ij=mg.toLowerCase(),xj=mg[0].toUpperCase()+mg.slice(1);js(Ij,"on"+xj)}js(xO,"onAnimationEnd");js(OO,"onAnimationIteration");js(PO,"onAnimationStart");js("dblclick","onDoubleClick");js("focusin","onFocus");js("focusout","onBlur");js(MO,"onTransitionEnd");sc("onMouseEnter",["mouseout","mouseover"]);sc("onMouseLeave",["mouseout","mouseover"]);sc("onPointerEnter",["pointerout","pointerover"]);sc("onPointerLeave",["pointerout","pointerover"]);Ga("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Ga("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Ga("onBeforeInput",["compositionend","keypress","textInput","paste"]);Ga("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Ga("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Ga("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Ou="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Oj=new Set("cancel close invalid load scroll toggle".split(" ").concat(Ou));function pT(r,e,t){var n=r.type||"unknown-event";r.currentTarget=t,I2(n,e,void 0,r),r.currentTarget=null}function DO(r,e){e=(e&4)!==0;for(var t=0;t<r.length;t++){var n=r[t],i=n.event;n=n.listeners;e:{var o=void 0;if(e)for(var s=n.length-1;0<=s;s--){var a=n[s],l=a.instance,c=a.currentTarget;if(a=a.listener,l!==o&&i.isPropagationStopped())break e;pT(i,a,c),o=l}else for(s=0;s<n.length;s++){if(a=n[s],l=a.instance,c=a.currentTarget,a=a.listener,l!==o&&i.isPropagationStopped())break e;pT(i,a,c),o=l}}}if(Sp)throw r=cS,Sp=!1,cS=null,r}function Ct(r,e){var t=e[SS];t===void 0&&(t=e[SS]=new Set);var n=r+"__bubble";t.has(n)||(NO(e,r,2,!1),t.add(n))}function gg(r,e,t){var n=0;e&&(n|=4),NO(t,r,n,e)}var Yf="_reactListening"+Math.random().toString(36).slice(2);function yd(r){if(!r[Yf]){r[Yf]=!0,Vx.forEach(function(t){t!=="selectionchange"&&(Oj.has(t)||gg(t,!1,r),gg(t,!0,r))});var e=r.nodeType===9?r:r.ownerDocument;e===null||e[Yf]||(e[Yf]=!0,gg("selectionchange",!1,e))}}function NO(r,e,t,n){switch(yO(e)){case 1:var i=W2;break;case 4:i=q2;break;default:i=tE}t=i.bind(null,e,t,r),i=void 0,!lS||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(i=!0),n?i!==void 0?r.addEventListener(e,t,{capture:!0,passive:i}):r.addEventListener(e,t,!0):i!==void 0?r.addEventListener(e,t,{passive:i}):r.addEventListener(e,t,!1)}function yg(r,e,t,n,i){var o=n;if(!(e&1)&&!(e&2)&&n!==null)e:for(;;){if(n===null)return;var s=n.tag;if(s===3||s===4){var a=n.stateNode.containerInfo;if(a===i||a.nodeType===8&&a.parentNode===i)break;if(s===4)for(s=n.return;s!==null;){var l=s.tag;if((l===3||l===4)&&(l=s.stateNode.containerInfo,l===i||l.nodeType===8&&l.parentNode===i))return;s=s.return}for(;a!==null;){if(s=_a(a),s===null)return;if(l=s.tag,l===5||l===6){n=o=s;continue e}a=a.parentNode}}n=n.return}iO(function(){var c=o,u=X_(t),d=[];e:{var f=AO.get(r);if(f!==void 0){var p=nE,h=r;switch(r){case"keypress":if(Fh(t)===0)break e;case"keydown":case"keyup":p=sj;break;case"focusin":h="focus",p=dg;break;case"focusout":h="blur",p=dg;break;case"beforeblur":case"afterblur":p=dg;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":p=rT;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":p=z2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":p=cj;break;case xO:case OO:case PO:p=X2;break;case MO:p=dj;break;case"scroll":p=G2;break;case"wheel":p=hj;break;case"copy":case"cut":case"paste":p=Z2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":p=iT}var m=(e&4)!==0,E=!m&&r==="scroll",y=m?f!==null?f+"Capture":null:f;m=[];for(var S=c,R;S!==null;){R=S;var k=R.stateNode;if(R.tag===5&&k!==null&&(R=k,y!==null&&(k=fd(S,y),k!=null&&m.push(Sd(S,k,R)))),E)break;S=S.return}0<m.length&&(f=new p(f,h,null,t,u),d.push({event:f,listeners:m}))}}if(!(e&7)){e:{if(f=r==="mouseover"||r==="pointerover",p=r==="mouseout"||r==="pointerout",f&&t!==sS&&(h=t.relatedTarget||t.fromElement)&&(_a(h)||h[Po]))break e;if((p||f)&&(f=u.window===u?u:(f=u.ownerDocument)?f.defaultView||f.parentWindow:window,p?(h=t.relatedTarget||t.toElement,p=c,h=h?_a(h):null,h!==null&&(E=Ha(h),h!==E||h.tag!==5&&h.tag!==6)&&(h=null)):(p=null,h=c),p!==h)){if(m=rT,k="onMouseLeave",y="onMouseEnter",S="mouse",(r==="pointerout"||r==="pointerover")&&(m=iT,k="onPointerLeave",y="onPointerEnter",S="pointer"),E=p==null?f:Ml(p),R=h==null?f:Ml(h),f=new m(k,S+"leave",p,t,u),f.target=E,f.relatedTarget=R,k=null,_a(u)===c&&(m=new m(y,S+"enter",h,t,u),m.target=R,m.relatedTarget=E,k=m),E=k,p&&h)t:{for(m=p,y=h,S=0,R=m;R;R=il(R))S++;for(R=0,k=y;k;k=il(k))R++;for(;0<S-R;)m=il(m),S--;for(;0<R-S;)y=il(y),R--;for(;S--;){if(m===y||y!==null&&m===y.alternate)break t;m=il(m),y=il(y)}m=null}else m=null;p!==null&&vT(d,f,p,m,!1),h!==null&&E!==null&&vT(d,E,h,m,!0)}}e:{if(f=c?Ml(c):window,p=f.nodeName&&f.nodeName.toLowerCase(),p==="select"||p==="input"&&f.type==="file")var x=bj;else if(aT(f))if(TO)x=Tj;else{x=Ej;var T=_j}else(p=f.nodeName)&&p.toLowerCase()==="input"&&(f.type==="checkbox"||f.type==="radio")&&(x=wj);if(x&&(x=x(r,c))){wO(d,x,t,u);break e}T&&T(r,f,c),r==="focusout"&&(T=f._wrapperState)&&T.controlled&&f.type==="number"&&tS(f,"number",f.value)}switch(T=c?Ml(c):window,r){case"focusin":(aT(T)||T.contentEditable==="true")&&(Ol=T,hS=c,Hu=null);break;case"focusout":Hu=hS=Ol=null;break;case"mousedown":pS=!0;break;case"contextmenu":case"mouseup":case"dragend":pS=!1,fT(d,t,u);break;case"selectionchange":if(kj)break;case"keydown":case"keyup":fT(d,t,u)}var O;if(oE)e:{switch(r){case"compositionstart":var C="onCompositionStart";break e;case"compositionend":C="onCompositionEnd";break e;case"compositionupdate":C="onCompositionUpdate";break e}C=void 0}else xl?_O(r,t)&&(C="onCompositionEnd"):r==="keydown"&&t.keyCode===229&&(C="onCompositionStart");C&&(bO&&t.locale!=="ko"&&(xl||C!=="onCompositionStart"?C==="onCompositionEnd"&&xl&&(O=SO()):(ps=u,rE="value"in ps?ps.value:ps.textContent,xl=!0)),T=Tp(c,C),0<T.length&&(C=new nT(C,r,null,t,u),d.push({event:C,listeners:T}),O?C.data=O:(O=EO(t),O!==null&&(C.data=O)))),(O=vj?mj(r,t):gj(r,t))&&(c=Tp(c,"onBeforeInput"),0<c.length&&(u=new nT("onBeforeInput","beforeinput",null,t,u),d.push({event:u,listeners:c}),u.data=O))}DO(d,e)})}function Sd(r,e,t){return{instance:r,listener:e,currentTarget:t}}function Tp(r,e){for(var t=e+"Capture",n=[];r!==null;){var i=r,o=i.stateNode;i.tag===5&&o!==null&&(i=o,o=fd(r,t),o!=null&&n.unshift(Sd(r,o,i)),o=fd(r,e),o!=null&&n.push(Sd(r,o,i))),r=r.return}return n}function il(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function vT(r,e,t,n,i){for(var o=e._reactName,s=[];t!==null&&t!==n;){var a=t,l=a.alternate,c=a.stateNode;if(l!==null&&l===n)break;a.tag===5&&c!==null&&(a=c,i?(l=fd(t,o),l!=null&&s.unshift(Sd(t,l,a))):i||(l=fd(t,o),l!=null&&s.push(Sd(t,l,a)))),t=t.return}s.length!==0&&r.push({event:e,listeners:s})}var Pj=/\r\n?/g,Mj=/\u0000|\uFFFD/g;function mT(r){return(typeof r=="string"?r:""+r).replace(Pj,`
38
- `).replace(Mj,"")}function Jf(r,e,t){if(e=mT(e),mT(r)!==e&&t)throw Error(he(425))}function Rp(){}var vS=null,mS=null;function gS(r,e){return r==="textarea"||r==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var yS=typeof setTimeout=="function"?setTimeout:void 0,Aj=typeof clearTimeout=="function"?clearTimeout:void 0,gT=typeof Promise=="function"?Promise:void 0,Dj=typeof queueMicrotask=="function"?queueMicrotask:typeof gT<"u"?function(r){return gT.resolve(null).then(r).catch(Nj)}:yS;function Nj(r){setTimeout(function(){throw r})}function Sg(r,e){var t=e,n=0;do{var i=t.nextSibling;if(r.removeChild(t),i&&i.nodeType===8)if(t=i.data,t==="/$"){if(n===0){r.removeChild(i),vd(e);return}n--}else t!=="$"&&t!=="$?"&&t!=="$!"||n++;t=i}while(t);vd(e)}function _s(r){for(;r!=null;r=r.nextSibling){var e=r.nodeType;if(e===1||e===3)break;if(e===8){if(e=r.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return r}function yT(r){r=r.previousSibling;for(var e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="$"||t==="$!"||t==="$?"){if(e===0)return r;e--}else t==="/$"&&e++}r=r.previousSibling}return null}var Ac=Math.random().toString(36).slice(2),qi="__reactFiber$"+Ac,bd="__reactProps$"+Ac,Po="__reactContainer$"+Ac,SS="__reactEvents$"+Ac,Lj="__reactListeners$"+Ac,Uj="__reactHandles$"+Ac;function _a(r){var e=r[qi];if(e)return e;for(var t=r.parentNode;t;){if(e=t[Po]||t[qi]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(r=yT(r);r!==null;){if(t=r[qi])return t;r=yT(r)}return e}r=t,t=r.parentNode}return null}function of(r){return r=r[qi]||r[Po],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function Ml(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(he(33))}function Av(r){return r[bd]||null}var bS=[],Al=-1;function Fs(r){return{current:r}}function It(r){0>Al||(r.current=bS[Al],bS[Al]=null,Al--)}function wt(r,e){Al++,bS[Al]=r.current,r.current=e}var Os={},qr=Fs(Os),_n=Fs(!1),Pa=Os;function ac(r,e){var t=r.type.contextTypes;if(!t)return Os;var n=r.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in t)i[o]=e[o];return n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=e,r.__reactInternalMemoizedMaskedChildContext=i),i}function En(r){return r=r.childContextTypes,r!=null}function Cp(){It(_n),It(qr)}function ST(r,e,t){if(qr.current!==Os)throw Error(he(168));wt(qr,e),wt(_n,t)}function LO(r,e,t){var n=r.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return t;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(he(108,_2(r)||"Unknown",i));return Ft({},t,n)}function kp(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||Os,Pa=qr.current,wt(qr,r),wt(_n,_n.current),!0}function bT(r,e,t){var n=r.stateNode;if(!n)throw Error(he(169));t?(r=LO(r,e,Pa),n.__reactInternalMemoizedMergedChildContext=r,It(_n),It(qr),wt(qr,r)):It(_n),wt(_n,t)}var yo=null,Dv=!1,bg=!1;function UO(r){yo===null?yo=[r]:yo.push(r)}function jj(r){Dv=!0,UO(r)}function Bs(){if(!bg&&yo!==null){bg=!0;var r=0,e=ft;try{var t=yo;for(ft=1;r<t.length;r++){var n=t[r];do n=n(!0);while(n!==null)}yo=null,Dv=!1}catch(i){throw yo!==null&&(yo=yo.slice(r+1)),lO(Q_,Bs),i}finally{ft=e,bg=!1}}return null}var Dl=[],Nl=0,Ip=null,xp=0,Wn=[],qn=0,Ma=null,_o=1,Eo="";function aa(r,e){Dl[Nl++]=xp,Dl[Nl++]=Ip,Ip=r,xp=e}function jO(r,e,t){Wn[qn++]=_o,Wn[qn++]=Eo,Wn[qn++]=Ma,Ma=r;var n=_o;r=Eo;var i=32-Si(n)-1;n&=~(1<<i),t+=1;var o=32-Si(e)+i;if(30<o){var s=i-i%5;o=(n&(1<<s)-1).toString(32),n>>=s,i-=s,_o=1<<32-Si(e)+i|t<<i|n,Eo=o+r}else _o=1<<o|t<<i|n,Eo=r}function aE(r){r.return!==null&&(aa(r,1),jO(r,1,0))}function lE(r){for(;r===Ip;)Ip=Dl[--Nl],Dl[Nl]=null,xp=Dl[--Nl],Dl[Nl]=null;for(;r===Ma;)Ma=Wn[--qn],Wn[qn]=null,Eo=Wn[--qn],Wn[qn]=null,_o=Wn[--qn],Wn[qn]=null}var jn=null,Un=null,Mt=!1,vi=null;function FO(r,e){var t=Gn(5,null,null,0);t.elementType="DELETED",t.stateNode=e,t.return=r,e=r.deletions,e===null?(r.deletions=[t],r.flags|=16):e.push(t)}function _T(r,e){switch(r.tag){case 5:var t=r.type;return e=e.nodeType!==1||t.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(r.stateNode=e,jn=r,Un=_s(e.firstChild),!0):!1;case 6:return e=r.pendingProps===""||e.nodeType!==3?null:e,e!==null?(r.stateNode=e,jn=r,Un=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=Ma!==null?{id:_o,overflow:Eo}:null,r.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=Gn(18,null,null,0),t.stateNode=e,t.return=r,r.child=t,jn=r,Un=null,!0):!1;default:return!1}}function _S(r){return(r.mode&1)!==0&&(r.flags&128)===0}function ES(r){if(Mt){var e=Un;if(e){var t=e;if(!_T(r,e)){if(_S(r))throw Error(he(418));e=_s(t.nextSibling);var n=jn;e&&_T(r,e)?FO(n,t):(r.flags=r.flags&-4097|2,Mt=!1,jn=r)}}else{if(_S(r))throw Error(he(418));r.flags=r.flags&-4097|2,Mt=!1,jn=r}}}function ET(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;jn=r}function Xf(r){if(r!==jn)return!1;if(!Mt)return ET(r),Mt=!0,!1;var e;if((e=r.tag!==3)&&!(e=r.tag!==5)&&(e=r.type,e=e!=="head"&&e!=="body"&&!gS(r.type,r.memoizedProps)),e&&(e=Un)){if(_S(r))throw BO(),Error(he(418));for(;e;)FO(r,e),e=_s(e.nextSibling)}if(ET(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(he(317));e:{for(r=r.nextSibling,e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="/$"){if(e===0){Un=_s(r.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}r=r.nextSibling}Un=null}}else Un=jn?_s(r.stateNode.nextSibling):null;return!0}function BO(){for(var r=Un;r;)r=_s(r.nextSibling)}function lc(){Un=jn=null,Mt=!1}function cE(r){vi===null?vi=[r]:vi.push(r)}var Fj=Uo.ReactCurrentBatchConfig;function nu(r,e,t){if(r=t.ref,r!==null&&typeof r!="function"&&typeof r!="object"){if(t._owner){if(t=t._owner,t){if(t.tag!==1)throw Error(he(309));var n=t.stateNode}if(!n)throw Error(he(147,r));var i=n,o=""+r;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===o?e.ref:(e=function(s){var a=i.refs;s===null?delete a[o]:a[o]=s},e._stringRef=o,e)}if(typeof r!="string")throw Error(he(284));if(!t._owner)throw Error(he(290,r))}return r}function Qf(r,e){throw r=Object.prototype.toString.call(e),Error(he(31,r==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":r))}function wT(r){var e=r._init;return e(r._payload)}function KO(r){function e(y,S){if(r){var R=y.deletions;R===null?(y.deletions=[S],y.flags|=16):R.push(S)}}function t(y,S){if(!r)return null;for(;S!==null;)e(y,S),S=S.sibling;return null}function n(y,S){for(y=new Map;S!==null;)S.key!==null?y.set(S.key,S):y.set(S.index,S),S=S.sibling;return y}function i(y,S){return y=Rs(y,S),y.index=0,y.sibling=null,y}function o(y,S,R){return y.index=R,r?(R=y.alternate,R!==null?(R=R.index,R<S?(y.flags|=2,S):R):(y.flags|=2,S)):(y.flags|=1048576,S)}function s(y){return r&&y.alternate===null&&(y.flags|=2),y}function a(y,S,R,k){return S===null||S.tag!==6?(S=kg(R,y.mode,k),S.return=y,S):(S=i(S,R),S.return=y,S)}function l(y,S,R,k){var x=R.type;return x===Il?u(y,S,R.props.children,k,R.key):S!==null&&(S.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===as&&wT(x)===S.type)?(k=i(S,R.props),k.ref=nu(y,S,R),k.return=y,k):(k=Gh(R.type,R.key,R.props,null,y.mode,k),k.ref=nu(y,S,R),k.return=y,k)}function c(y,S,R,k){return S===null||S.tag!==4||S.stateNode.containerInfo!==R.containerInfo||S.stateNode.implementation!==R.implementation?(S=Ig(R,y.mode,k),S.return=y,S):(S=i(S,R.children||[]),S.return=y,S)}function u(y,S,R,k,x){return S===null||S.tag!==7?(S=Ca(R,y.mode,k,x),S.return=y,S):(S=i(S,R),S.return=y,S)}function d(y,S,R){if(typeof S=="string"&&S!==""||typeof S=="number")return S=kg(""+S,y.mode,R),S.return=y,S;if(typeof S=="object"&&S!==null){switch(S.$$typeof){case Kf:return R=Gh(S.type,S.key,S.props,null,y.mode,R),R.ref=nu(y,null,S),R.return=y,R;case kl:return S=Ig(S,y.mode,R),S.return=y,S;case as:var k=S._init;return d(y,k(S._payload),R)}if(Iu(S)||Qc(S))return S=Ca(S,y.mode,R,null),S.return=y,S;Qf(y,S)}return null}function f(y,S,R,k){var x=S!==null?S.key:null;if(typeof R=="string"&&R!==""||typeof R=="number")return x!==null?null:a(y,S,""+R,k);if(typeof R=="object"&&R!==null){switch(R.$$typeof){case Kf:return R.key===x?l(y,S,R,k):null;case kl:return R.key===x?c(y,S,R,k):null;case as:return x=R._init,f(y,S,x(R._payload),k)}if(Iu(R)||Qc(R))return x!==null?null:u(y,S,R,k,null);Qf(y,R)}return null}function p(y,S,R,k,x){if(typeof k=="string"&&k!==""||typeof k=="number")return y=y.get(R)||null,a(S,y,""+k,x);if(typeof k=="object"&&k!==null){switch(k.$$typeof){case Kf:return y=y.get(k.key===null?R:k.key)||null,l(S,y,k,x);case kl:return y=y.get(k.key===null?R:k.key)||null,c(S,y,k,x);case as:var T=k._init;return p(y,S,R,T(k._payload),x)}if(Iu(k)||Qc(k))return y=y.get(R)||null,u(S,y,k,x,null);Qf(S,k)}return null}function h(y,S,R,k){for(var x=null,T=null,O=S,C=S=0,N=null;O!==null&&C<R.length;C++){O.index>C?(N=O,O=null):N=O.sibling;var F=f(y,O,R[C],k);if(F===null){O===null&&(O=N);break}r&&O&&F.alternate===null&&e(y,O),S=o(F,S,C),T===null?x=F:T.sibling=F,T=F,O=N}if(C===R.length)return t(y,O),Mt&&aa(y,C),x;if(O===null){for(;C<R.length;C++)O=d(y,R[C],k),O!==null&&(S=o(O,S,C),T===null?x=O:T.sibling=O,T=O);return Mt&&aa(y,C),x}for(O=n(y,O);C<R.length;C++)N=p(O,y,C,R[C],k),N!==null&&(r&&N.alternate!==null&&O.delete(N.key===null?C:N.key),S=o(N,S,C),T===null?x=N:T.sibling=N,T=N);return r&&O.forEach(function(H){return e(y,H)}),Mt&&aa(y,C),x}function m(y,S,R,k){var x=Qc(R);if(typeof x!="function")throw Error(he(150));if(R=x.call(R),R==null)throw Error(he(151));for(var T=x=null,O=S,C=S=0,N=null,F=R.next();O!==null&&!F.done;C++,F=R.next()){O.index>C?(N=O,O=null):N=O.sibling;var H=f(y,O,F.value,k);if(H===null){O===null&&(O=N);break}r&&O&&H.alternate===null&&e(y,O),S=o(H,S,C),T===null?x=H:T.sibling=H,T=H,O=N}if(F.done)return t(y,O),Mt&&aa(y,C),x;if(O===null){for(;!F.done;C++,F=R.next())F=d(y,F.value,k),F!==null&&(S=o(F,S,C),T===null?x=F:T.sibling=F,T=F);return Mt&&aa(y,C),x}for(O=n(y,O);!F.done;C++,F=R.next())F=p(O,y,C,F.value,k),F!==null&&(r&&F.alternate!==null&&O.delete(F.key===null?C:F.key),S=o(F,S,C),T===null?x=F:T.sibling=F,T=F);return r&&O.forEach(function(ie){return e(y,ie)}),Mt&&aa(y,C),x}function E(y,S,R,k){if(typeof R=="object"&&R!==null&&R.type===Il&&R.key===null&&(R=R.props.children),typeof R=="object"&&R!==null){switch(R.$$typeof){case Kf:e:{for(var x=R.key,T=S;T!==null;){if(T.key===x){if(x=R.type,x===Il){if(T.tag===7){t(y,T.sibling),S=i(T,R.props.children),S.return=y,y=S;break e}}else if(T.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===as&&wT(x)===T.type){t(y,T.sibling),S=i(T,R.props),S.ref=nu(y,T,R),S.return=y,y=S;break e}t(y,T);break}else e(y,T);T=T.sibling}R.type===Il?(S=Ca(R.props.children,y.mode,k,R.key),S.return=y,y=S):(k=Gh(R.type,R.key,R.props,null,y.mode,k),k.ref=nu(y,S,R),k.return=y,y=k)}return s(y);case kl:e:{for(T=R.key;S!==null;){if(S.key===T)if(S.tag===4&&S.stateNode.containerInfo===R.containerInfo&&S.stateNode.implementation===R.implementation){t(y,S.sibling),S=i(S,R.children||[]),S.return=y,y=S;break e}else{t(y,S);break}else e(y,S);S=S.sibling}S=Ig(R,y.mode,k),S.return=y,y=S}return s(y);case as:return T=R._init,E(y,S,T(R._payload),k)}if(Iu(R))return h(y,S,R,k);if(Qc(R))return m(y,S,R,k);Qf(y,R)}return typeof R=="string"&&R!==""||typeof R=="number"?(R=""+R,S!==null&&S.tag===6?(t(y,S.sibling),S=i(S,R),S.return=y,y=S):(t(y,S),S=kg(R,y.mode,k),S.return=y,y=S),s(y)):t(y,S)}return E}var cc=KO(!0),VO=KO(!1),Op=Fs(null),Pp=null,Ll=null,uE=null;function dE(){uE=Ll=Pp=null}function fE(r){var e=Op.current;It(Op),r._currentValue=e}function wS(r,e,t){for(;r!==null;){var n=r.alternate;if((r.childLanes&e)!==e?(r.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),r===t)break;r=r.return}}function Gl(r,e){Pp=r,uE=Ll=null,r=r.dependencies,r!==null&&r.firstContext!==null&&(r.lanes&e&&(Sn=!0),r.firstContext=null)}function Xn(r){var e=r._currentValue;if(uE!==r)if(r={context:r,memoizedValue:e,next:null},Ll===null){if(Pp===null)throw Error(he(308));Ll=r,Pp.dependencies={lanes:0,firstContext:r}}else Ll=Ll.next=r;return e}var Ea=null;function hE(r){Ea===null?Ea=[r]:Ea.push(r)}function $O(r,e,t,n){var i=e.interleaved;return i===null?(t.next=t,hE(e)):(t.next=i.next,i.next=t),e.interleaved=t,Mo(r,n)}function Mo(r,e){r.lanes|=e;var t=r.alternate;for(t!==null&&(t.lanes|=e),t=r,r=r.return;r!==null;)r.childLanes|=e,t=r.alternate,t!==null&&(t.childLanes|=e),t=r,r=r.return;return t.tag===3?t.stateNode:null}var ls=!1;function pE(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function WO(r,e){r=r.updateQueue,e.updateQueue===r&&(e.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function Co(r,e){return{eventTime:r,lane:e,tag:0,payload:null,callback:null,next:null}}function Es(r,e,t){var n=r.updateQueue;if(n===null)return null;if(n=n.shared,st&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Mo(r,t)}return i=n.interleaved,i===null?(e.next=e,hE(n)):(e.next=i.next,i.next=e),n.interleaved=e,Mo(r,t)}function Bh(r,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194240)!==0)){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,Z_(r,t)}}function TT(r,e){var t=r.updateQueue,n=r.alternate;if(n!==null&&(n=n.updateQueue,t===n)){var i=null,o=null;if(t=t.firstBaseUpdate,t!==null){do{var s={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};o===null?i=o=s:o=o.next=s,t=t.next}while(t!==null);o===null?i=o=e:o=o.next=e}else i=o=e;t={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:n.shared,effects:n.effects},r.updateQueue=t;return}r=t.lastBaseUpdate,r===null?t.firstBaseUpdate=e:r.next=e,t.lastBaseUpdate=e}function Mp(r,e,t,n){var i=r.updateQueue;ls=!1;var o=i.firstBaseUpdate,s=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var l=a,c=l.next;l.next=null,s===null?o=c:s.next=c,s=l;var u=r.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==s&&(a===null?u.firstBaseUpdate=c:a.next=c,u.lastBaseUpdate=l))}if(o!==null){var d=i.baseState;s=0,u=c=l=null,a=o;do{var f=a.lane,p=a.eventTime;if((n&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var h=r,m=a;switch(f=e,p=t,m.tag){case 1:if(h=m.payload,typeof h=="function"){d=h.call(p,d,f);break e}d=h;break e;case 3:h.flags=h.flags&-65537|128;case 0:if(h=m.payload,f=typeof h=="function"?h.call(p,d,f):h,f==null)break e;d=Ft({},d,f);break e;case 2:ls=!0}}a.callback!==null&&a.lane!==0&&(r.flags|=64,f=i.effects,f===null?i.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(c=u=p,l=d):u=u.next=p,s|=f;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;f=a,a=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(u===null&&(l=d),i.baseState=l,i.firstBaseUpdate=c,i.lastBaseUpdate=u,e=i.shared.interleaved,e!==null){i=e;do s|=i.lane,i=i.next;while(i!==e)}else o===null&&(i.shared.lanes=0);Da|=s,r.lanes=s,r.memoizedState=d}}function RT(r,e,t){if(r=e.effects,e.effects=null,r!==null)for(e=0;e<r.length;e++){var n=r[e],i=n.callback;if(i!==null){if(n.callback=null,n=t,typeof i!="function")throw Error(he(191,i));i.call(n)}}}var sf={},Ji=Fs(sf),_d=Fs(sf),Ed=Fs(sf);function wa(r){if(r===sf)throw Error(he(174));return r}function vE(r,e){switch(wt(Ed,e),wt(_d,r),wt(Ji,sf),r=e.nodeType,r){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:nS(null,"");break;default:r=r===8?e.parentNode:e,e=r.namespaceURI||null,r=r.tagName,e=nS(e,r)}It(Ji),wt(Ji,e)}function uc(){It(Ji),It(_d),It(Ed)}function qO(r){wa(Ed.current);var e=wa(Ji.current),t=nS(e,r.type);e!==t&&(wt(_d,r),wt(Ji,t))}function mE(r){_d.current===r&&(It(Ji),It(_d))}var Ut=Fs(0);function Ap(r){for(var e=r;e!==null;){if(e.tag===13){var t=e.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var _g=[];function gE(){for(var r=0;r<_g.length;r++)_g[r]._workInProgressVersionPrimary=null;_g.length=0}var Kh=Uo.ReactCurrentDispatcher,Eg=Uo.ReactCurrentBatchConfig,Aa=0,jt=null,ur=null,_r=null,Dp=!1,zu=!1,wd=0,Bj=0;function jr(){throw Error(he(321))}function yE(r,e){if(e===null)return!1;for(var t=0;t<e.length&&t<r.length;t++)if(!Ti(r[t],e[t]))return!1;return!0}function SE(r,e,t,n,i,o){if(Aa=o,jt=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,Kh.current=r===null||r.memoizedState===null?Wj:qj,r=t(n,i),zu){o=0;do{if(zu=!1,wd=0,25<=o)throw Error(he(301));o+=1,_r=ur=null,e.updateQueue=null,Kh.current=Gj,r=t(n,i)}while(zu)}if(Kh.current=Np,e=ur!==null&&ur.next!==null,Aa=0,_r=ur=jt=null,Dp=!1,e)throw Error(he(300));return r}function bE(){var r=wd!==0;return wd=0,r}function ji(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return _r===null?jt.memoizedState=_r=r:_r=_r.next=r,_r}function Qn(){if(ur===null){var r=jt.alternate;r=r!==null?r.memoizedState:null}else r=ur.next;var e=_r===null?jt.memoizedState:_r.next;if(e!==null)_r=e,ur=r;else{if(r===null)throw Error(he(310));ur=r,r={memoizedState:ur.memoizedState,baseState:ur.baseState,baseQueue:ur.baseQueue,queue:ur.queue,next:null},_r===null?jt.memoizedState=_r=r:_r=_r.next=r}return _r}function Td(r,e){return typeof e=="function"?e(r):e}function wg(r){var e=Qn(),t=e.queue;if(t===null)throw Error(he(311));t.lastRenderedReducer=r;var n=ur,i=n.baseQueue,o=t.pending;if(o!==null){if(i!==null){var s=i.next;i.next=o.next,o.next=s}n.baseQueue=i=o,t.pending=null}if(i!==null){o=i.next,n=n.baseState;var a=s=null,l=null,c=o;do{var u=c.lane;if((Aa&u)===u)l!==null&&(l=l.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),n=c.hasEagerState?c.eagerState:r(n,c.action);else{var d={lane:u,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};l===null?(a=l=d,s=n):l=l.next=d,jt.lanes|=u,Da|=u}c=c.next}while(c!==null&&c!==o);l===null?s=n:l.next=a,Ti(n,e.memoizedState)||(Sn=!0),e.memoizedState=n,e.baseState=s,e.baseQueue=l,t.lastRenderedState=n}if(r=t.interleaved,r!==null){i=r;do o=i.lane,jt.lanes|=o,Da|=o,i=i.next;while(i!==r)}else i===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function Tg(r){var e=Qn(),t=e.queue;if(t===null)throw Error(he(311));t.lastRenderedReducer=r;var n=t.dispatch,i=t.pending,o=e.memoizedState;if(i!==null){t.pending=null;var s=i=i.next;do o=r(o,s.action),s=s.next;while(s!==i);Ti(o,e.memoizedState)||(Sn=!0),e.memoizedState=o,e.baseQueue===null&&(e.baseState=o),t.lastRenderedState=o}return[o,n]}function GO(){}function HO(r,e){var t=jt,n=Qn(),i=e(),o=!Ti(n.memoizedState,i);if(o&&(n.memoizedState=i,Sn=!0),n=n.queue,_E(JO.bind(null,t,n,r),[r]),n.getSnapshot!==e||o||_r!==null&&_r.memoizedState.tag&1){if(t.flags|=2048,Rd(9,YO.bind(null,t,n,i,e),void 0,null),Tr===null)throw Error(he(349));Aa&30||zO(t,e,i)}return i}function zO(r,e,t){r.flags|=16384,r={getSnapshot:e,value:t},e=jt.updateQueue,e===null?(e={lastEffect:null,stores:null},jt.updateQueue=e,e.stores=[r]):(t=e.stores,t===null?e.stores=[r]:t.push(r))}function YO(r,e,t,n){e.value=t,e.getSnapshot=n,XO(e)&&QO(r)}function JO(r,e,t){return t(function(){XO(e)&&QO(r)})}function XO(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!Ti(r,t)}catch{return!0}}function QO(r){var e=Mo(r,1);e!==null&&bi(e,r,1,-1)}function CT(r){var e=ji();return typeof r=="function"&&(r=r()),e.memoizedState=e.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Td,lastRenderedState:r},e.queue=r,r=r.dispatch=$j.bind(null,jt,r),[e.memoizedState,r]}function Rd(r,e,t,n){return r={tag:r,create:e,destroy:t,deps:n,next:null},e=jt.updateQueue,e===null?(e={lastEffect:null,stores:null},jt.updateQueue=e,e.lastEffect=r.next=r):(t=e.lastEffect,t===null?e.lastEffect=r.next=r:(n=t.next,t.next=r,r.next=n,e.lastEffect=r)),r}function ZO(){return Qn().memoizedState}function Vh(r,e,t,n){var i=ji();jt.flags|=r,i.memoizedState=Rd(1|e,t,void 0,n===void 0?null:n)}function Nv(r,e,t,n){var i=Qn();n=n===void 0?null:n;var o=void 0;if(ur!==null){var s=ur.memoizedState;if(o=s.destroy,n!==null&&yE(n,s.deps)){i.memoizedState=Rd(e,t,o,n);return}}jt.flags|=r,i.memoizedState=Rd(1|e,t,o,n)}function kT(r,e){return Vh(8390656,8,r,e)}function _E(r,e){return Nv(2048,8,r,e)}function eP(r,e){return Nv(4,2,r,e)}function tP(r,e){return Nv(4,4,r,e)}function rP(r,e){if(typeof e=="function")return r=r(),e(r),function(){e(null)};if(e!=null)return r=r(),e.current=r,function(){e.current=null}}function nP(r,e,t){return t=t!=null?t.concat([r]):null,Nv(4,4,rP.bind(null,e,r),t)}function EE(){}function iP(r,e){var t=Qn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&yE(e,n[1])?n[0]:(t.memoizedState=[r,e],r)}function oP(r,e){var t=Qn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&yE(e,n[1])?n[0]:(r=r(),t.memoizedState=[r,e],r)}function sP(r,e,t){return Aa&21?(Ti(t,e)||(t=dO(),jt.lanes|=t,Da|=t,r.baseState=!0),e):(r.baseState&&(r.baseState=!1,Sn=!0),r.memoizedState=t)}function Kj(r,e){var t=ft;ft=t!==0&&4>t?t:4,r(!0);var n=Eg.transition;Eg.transition={};try{r(!1),e()}finally{ft=t,Eg.transition=n}}function aP(){return Qn().memoizedState}function Vj(r,e,t){var n=Ts(r);if(t={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null},lP(r))cP(e,t);else if(t=$O(r,e,t,n),t!==null){var i=en();bi(t,r,n,i),uP(t,e,n)}}function $j(r,e,t){var n=Ts(r),i={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null};if(lP(r))cP(e,i);else{var o=r.alternate;if(r.lanes===0&&(o===null||o.lanes===0)&&(o=e.lastRenderedReducer,o!==null))try{var s=e.lastRenderedState,a=o(s,t);if(i.hasEagerState=!0,i.eagerState=a,Ti(a,s)){var l=e.interleaved;l===null?(i.next=i,hE(e)):(i.next=l.next,l.next=i),e.interleaved=i;return}}catch{}finally{}t=$O(r,e,i,n),t!==null&&(i=en(),bi(t,r,n,i),uP(t,e,n))}}function lP(r){var e=r.alternate;return r===jt||e!==null&&e===jt}function cP(r,e){zu=Dp=!0;var t=r.pending;t===null?e.next=e:(e.next=t.next,t.next=e),r.pending=e}function uP(r,e,t){if(t&4194240){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,Z_(r,t)}}var Np={readContext:Xn,useCallback:jr,useContext:jr,useEffect:jr,useImperativeHandle:jr,useInsertionEffect:jr,useLayoutEffect:jr,useMemo:jr,useReducer:jr,useRef:jr,useState:jr,useDebugValue:jr,useDeferredValue:jr,useTransition:jr,useMutableSource:jr,useSyncExternalStore:jr,useId:jr,unstable_isNewReconciler:!1},Wj={readContext:Xn,useCallback:function(r,e){return ji().memoizedState=[r,e===void 0?null:e],r},useContext:Xn,useEffect:kT,useImperativeHandle:function(r,e,t){return t=t!=null?t.concat([r]):null,Vh(4194308,4,rP.bind(null,e,r),t)},useLayoutEffect:function(r,e){return Vh(4194308,4,r,e)},useInsertionEffect:function(r,e){return Vh(4,2,r,e)},useMemo:function(r,e){var t=ji();return e=e===void 0?null:e,r=r(),t.memoizedState=[r,e],r},useReducer:function(r,e,t){var n=ji();return e=t!==void 0?t(e):e,n.memoizedState=n.baseState=e,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:e},n.queue=r,r=r.dispatch=Vj.bind(null,jt,r),[n.memoizedState,r]},useRef:function(r){var e=ji();return r={current:r},e.memoizedState=r},useState:CT,useDebugValue:EE,useDeferredValue:function(r){return ji().memoizedState=r},useTransition:function(){var r=CT(!1),e=r[0];return r=Kj.bind(null,r[1]),ji().memoizedState=r,[e,r]},useMutableSource:function(){},useSyncExternalStore:function(r,e,t){var n=jt,i=ji();if(Mt){if(t===void 0)throw Error(he(407));t=t()}else{if(t=e(),Tr===null)throw Error(he(349));Aa&30||zO(n,e,t)}i.memoizedState=t;var o={value:t,getSnapshot:e};return i.queue=o,kT(JO.bind(null,n,o,r),[r]),n.flags|=2048,Rd(9,YO.bind(null,n,o,t,e),void 0,null),t},useId:function(){var r=ji(),e=Tr.identifierPrefix;if(Mt){var t=Eo,n=_o;t=(n&~(1<<32-Si(n)-1)).toString(32)+t,e=":"+e+"R"+t,t=wd++,0<t&&(e+="H"+t.toString(32)),e+=":"}else t=Bj++,e=":"+e+"r"+t.toString(32)+":";return r.memoizedState=e},unstable_isNewReconciler:!1},qj={readContext:Xn,useCallback:iP,useContext:Xn,useEffect:_E,useImperativeHandle:nP,useInsertionEffect:eP,useLayoutEffect:tP,useMemo:oP,useReducer:wg,useRef:ZO,useState:function(){return wg(Td)},useDebugValue:EE,useDeferredValue:function(r){var e=Qn();return sP(e,ur.memoizedState,r)},useTransition:function(){var r=wg(Td)[0],e=Qn().memoizedState;return[r,e]},useMutableSource:GO,useSyncExternalStore:HO,useId:aP,unstable_isNewReconciler:!1},Gj={readContext:Xn,useCallback:iP,useContext:Xn,useEffect:_E,useImperativeHandle:nP,useInsertionEffect:eP,useLayoutEffect:tP,useMemo:oP,useReducer:Tg,useRef:ZO,useState:function(){return Tg(Td)},useDebugValue:EE,useDeferredValue:function(r){var e=Qn();return ur===null?e.memoizedState=r:sP(e,ur.memoizedState,r)},useTransition:function(){var r=Tg(Td)[0],e=Qn().memoizedState;return[r,e]},useMutableSource:GO,useSyncExternalStore:HO,useId:aP,unstable_isNewReconciler:!1};function ui(r,e){if(r&&r.defaultProps){e=Ft({},e),r=r.defaultProps;for(var t in r)e[t]===void 0&&(e[t]=r[t]);return e}return e}function TS(r,e,t,n){e=r.memoizedState,t=t(n,e),t=t==null?e:Ft({},e,t),r.memoizedState=t,r.lanes===0&&(r.updateQueue.baseState=t)}var Lv={isMounted:function(r){return(r=r._reactInternals)?Ha(r)===r:!1},enqueueSetState:function(r,e,t){r=r._reactInternals;var n=en(),i=Ts(r),o=Co(n,i);o.payload=e,t!=null&&(o.callback=t),e=Es(r,o,i),e!==null&&(bi(e,r,i,n),Bh(e,r,i))},enqueueReplaceState:function(r,e,t){r=r._reactInternals;var n=en(),i=Ts(r),o=Co(n,i);o.tag=1,o.payload=e,t!=null&&(o.callback=t),e=Es(r,o,i),e!==null&&(bi(e,r,i,n),Bh(e,r,i))},enqueueForceUpdate:function(r,e){r=r._reactInternals;var t=en(),n=Ts(r),i=Co(t,n);i.tag=2,e!=null&&(i.callback=e),e=Es(r,i,n),e!==null&&(bi(e,r,n,t),Bh(e,r,n))}};function IT(r,e,t,n,i,o,s){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(n,o,s):e.prototype&&e.prototype.isPureReactComponent?!gd(t,n)||!gd(i,o):!0}function dP(r,e,t){var n=!1,i=Os,o=e.contextType;return typeof o=="object"&&o!==null?o=Xn(o):(i=En(e)?Pa:qr.current,n=e.contextTypes,o=(n=n!=null)?ac(r,i):Os),e=new e(t,o),r.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=Lv,r.stateNode=e,e._reactInternals=r,n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=o),e}function xT(r,e,t,n){r=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(t,n),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(t,n),e.state!==r&&Lv.enqueueReplaceState(e,e.state,null)}function RS(r,e,t,n){var i=r.stateNode;i.props=t,i.state=r.memoizedState,i.refs={},pE(r);var o=e.contextType;typeof o=="object"&&o!==null?i.context=Xn(o):(o=En(e)?Pa:qr.current,i.context=ac(r,o)),i.state=r.memoizedState,o=e.getDerivedStateFromProps,typeof o=="function"&&(TS(r,e,o,t),i.state=r.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(e=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),e!==i.state&&Lv.enqueueReplaceState(i,i.state,null),Mp(r,t,i,n),i.state=r.memoizedState),typeof i.componentDidMount=="function"&&(r.flags|=4194308)}function dc(r,e){try{var t="",n=e;do t+=b2(n),n=n.return;while(n);var i=t}catch(o){i=`
39
- Error generating stack: `+o.message+`
40
- `+o.stack}return{value:r,source:e,stack:i,digest:null}}function Rg(r,e,t){return{value:r,source:null,stack:t??null,digest:e??null}}function CS(r,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var Hj=typeof WeakMap=="function"?WeakMap:Map;function fP(r,e,t){t=Co(-1,t),t.tag=3,t.payload={element:null};var n=e.value;return t.callback=function(){Up||(Up=!0,LS=n),CS(r,e)},t}function hP(r,e,t){t=Co(-1,t),t.tag=3;var n=r.type.getDerivedStateFromError;if(typeof n=="function"){var i=e.value;t.payload=function(){return n(i)},t.callback=function(){CS(r,e)}}var o=r.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(t.callback=function(){CS(r,e),typeof n!="function"&&(ws===null?ws=new Set([this]):ws.add(this));var s=e.stack;this.componentDidCatch(e.value,{componentStack:s!==null?s:""})}),t}function OT(r,e,t){var n=r.pingCache;if(n===null){n=r.pingCache=new Hj;var i=new Set;n.set(e,i)}else i=n.get(e),i===void 0&&(i=new Set,n.set(e,i));i.has(t)||(i.add(t),r=aF.bind(null,r,e,t),e.then(r,r))}function PT(r){do{var e;if((e=r.tag===13)&&(e=r.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return r;r=r.return}while(r!==null);return null}function MT(r,e,t,n,i){return r.mode&1?(r.flags|=65536,r.lanes=i,r):(r===e?r.flags|=65536:(r.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(e=Co(-1,1),e.tag=2,Es(t,e,1))),t.lanes|=1),r)}var zj=Uo.ReactCurrentOwner,Sn=!1;function Jr(r,e,t,n){e.child=r===null?VO(e,null,t,n):cc(e,r.child,t,n)}function AT(r,e,t,n,i){t=t.render;var o=e.ref;return Gl(e,i),n=SE(r,e,t,n,o,i),t=bE(),r!==null&&!Sn?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,Ao(r,e,i)):(Mt&&t&&aE(e),e.flags|=1,Jr(r,e,n,i),e.child)}function DT(r,e,t,n,i){if(r===null){var o=t.type;return typeof o=="function"&&!OE(o)&&o.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=o,pP(r,e,o,n,i)):(r=Gh(t.type,null,n,e,e.mode,i),r.ref=e.ref,r.return=e,e.child=r)}if(o=r.child,!(r.lanes&i)){var s=o.memoizedProps;if(t=t.compare,t=t!==null?t:gd,t(s,n)&&r.ref===e.ref)return Ao(r,e,i)}return e.flags|=1,r=Rs(o,n),r.ref=e.ref,r.return=e,e.child=r}function pP(r,e,t,n,i){if(r!==null){var o=r.memoizedProps;if(gd(o,n)&&r.ref===e.ref)if(Sn=!1,e.pendingProps=n=o,(r.lanes&i)!==0)r.flags&131072&&(Sn=!0);else return e.lanes=r.lanes,Ao(r,e,i)}return kS(r,e,t,n,i)}function vP(r,e,t){var n=e.pendingProps,i=n.children,o=r!==null?r.memoizedState:null;if(n.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},wt(jl,Dn),Dn|=t;else{if(!(t&1073741824))return r=o!==null?o.baseLanes|t:t,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:r,cachePool:null,transitions:null},e.updateQueue=null,wt(jl,Dn),Dn|=r,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=o!==null?o.baseLanes:t,wt(jl,Dn),Dn|=n}else o!==null?(n=o.baseLanes|t,e.memoizedState=null):n=t,wt(jl,Dn),Dn|=n;return Jr(r,e,i,t),e.child}function mP(r,e){var t=e.ref;(r===null&&t!==null||r!==null&&r.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function kS(r,e,t,n,i){var o=En(t)?Pa:qr.current;return o=ac(e,o),Gl(e,i),t=SE(r,e,t,n,o,i),n=bE(),r!==null&&!Sn?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,Ao(r,e,i)):(Mt&&n&&aE(e),e.flags|=1,Jr(r,e,t,i),e.child)}function NT(r,e,t,n,i){if(En(t)){var o=!0;kp(e)}else o=!1;if(Gl(e,i),e.stateNode===null)$h(r,e),dP(e,t,n),RS(e,t,n,i),n=!0;else if(r===null){var s=e.stateNode,a=e.memoizedProps;s.props=a;var l=s.context,c=t.contextType;typeof c=="object"&&c!==null?c=Xn(c):(c=En(t)?Pa:qr.current,c=ac(e,c));var u=t.getDerivedStateFromProps,d=typeof u=="function"||typeof s.getSnapshotBeforeUpdate=="function";d||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==n||l!==c)&&xT(e,s,n,c),ls=!1;var f=e.memoizedState;s.state=f,Mp(e,n,s,i),l=e.memoizedState,a!==n||f!==l||_n.current||ls?(typeof u=="function"&&(TS(e,t,u,n),l=e.memoizedState),(a=ls||IT(e,t,a,n,f,l,c))?(d||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount()),typeof s.componentDidMount=="function"&&(e.flags|=4194308)):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=n,e.memoizedState=l),s.props=n,s.state=l,s.context=c,n=a):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),n=!1)}else{s=e.stateNode,WO(r,e),a=e.memoizedProps,c=e.type===e.elementType?a:ui(e.type,a),s.props=c,d=e.pendingProps,f=s.context,l=t.contextType,typeof l=="object"&&l!==null?l=Xn(l):(l=En(t)?Pa:qr.current,l=ac(e,l));var p=t.getDerivedStateFromProps;(u=typeof p=="function"||typeof s.getSnapshotBeforeUpdate=="function")||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==d||f!==l)&&xT(e,s,n,l),ls=!1,f=e.memoizedState,s.state=f,Mp(e,n,s,i);var h=e.memoizedState;a!==d||f!==h||_n.current||ls?(typeof p=="function"&&(TS(e,t,p,n),h=e.memoizedState),(c=ls||IT(e,t,c,n,f,h,l)||!1)?(u||typeof s.UNSAFE_componentWillUpdate!="function"&&typeof s.componentWillUpdate!="function"||(typeof s.componentWillUpdate=="function"&&s.componentWillUpdate(n,h,l),typeof s.UNSAFE_componentWillUpdate=="function"&&s.UNSAFE_componentWillUpdate(n,h,l)),typeof s.componentDidUpdate=="function"&&(e.flags|=4),typeof s.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof s.componentDidUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=1024),e.memoizedProps=n,e.memoizedState=h),s.props=n,s.state=h,s.context=l,n=c):(typeof s.componentDidUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&f===r.memoizedState||(e.flags|=1024),n=!1)}return IS(r,e,t,n,o,i)}function IS(r,e,t,n,i,o){mP(r,e);var s=(e.flags&128)!==0;if(!n&&!s)return i&&bT(e,t,!1),Ao(r,e,o);n=e.stateNode,zj.current=e;var a=s&&typeof t.getDerivedStateFromError!="function"?null:n.render();return e.flags|=1,r!==null&&s?(e.child=cc(e,r.child,null,o),e.child=cc(e,null,a,o)):Jr(r,e,a,o),e.memoizedState=n.state,i&&bT(e,t,!0),e.child}function gP(r){var e=r.stateNode;e.pendingContext?ST(r,e.pendingContext,e.pendingContext!==e.context):e.context&&ST(r,e.context,!1),vE(r,e.containerInfo)}function LT(r,e,t,n,i){return lc(),cE(i),e.flags|=256,Jr(r,e,t,n),e.child}var xS={dehydrated:null,treeContext:null,retryLane:0};function OS(r){return{baseLanes:r,cachePool:null,transitions:null}}function yP(r,e,t){var n=e.pendingProps,i=Ut.current,o=!1,s=(e.flags&128)!==0,a;if((a=s)||(a=r!==null&&r.memoizedState===null?!1:(i&2)!==0),a?(o=!0,e.flags&=-129):(r===null||r.memoizedState!==null)&&(i|=1),wt(Ut,i&1),r===null)return ES(e),r=e.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?(e.mode&1?r.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(s=n.children,r=n.fallback,o?(n=e.mode,o=e.child,s={mode:"hidden",children:s},!(n&1)&&o!==null?(o.childLanes=0,o.pendingProps=s):o=Fv(s,n,0,null),r=Ca(r,n,t,null),o.return=e,r.return=e,o.sibling=r,e.child=o,e.child.memoizedState=OS(t),e.memoizedState=xS,r):wE(e,s));if(i=r.memoizedState,i!==null&&(a=i.dehydrated,a!==null))return Yj(r,e,s,n,a,i,t);if(o){o=n.fallback,s=e.mode,i=r.child,a=i.sibling;var l={mode:"hidden",children:n.children};return!(s&1)&&e.child!==i?(n=e.child,n.childLanes=0,n.pendingProps=l,e.deletions=null):(n=Rs(i,l),n.subtreeFlags=i.subtreeFlags&14680064),a!==null?o=Rs(a,o):(o=Ca(o,s,t,null),o.flags|=2),o.return=e,n.return=e,n.sibling=o,e.child=n,n=o,o=e.child,s=r.child.memoizedState,s=s===null?OS(t):{baseLanes:s.baseLanes|t,cachePool:null,transitions:s.transitions},o.memoizedState=s,o.childLanes=r.childLanes&~t,e.memoizedState=xS,n}return o=r.child,r=o.sibling,n=Rs(o,{mode:"visible",children:n.children}),!(e.mode&1)&&(n.lanes=t),n.return=e,n.sibling=null,r!==null&&(t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)),e.child=n,e.memoizedState=null,n}function wE(r,e){return e=Fv({mode:"visible",children:e},r.mode,0,null),e.return=r,r.child=e}function Zf(r,e,t,n){return n!==null&&cE(n),cc(e,r.child,null,t),r=wE(e,e.pendingProps.children),r.flags|=2,e.memoizedState=null,r}function Yj(r,e,t,n,i,o,s){if(t)return e.flags&256?(e.flags&=-257,n=Rg(Error(he(422))),Zf(r,e,s,n)):e.memoizedState!==null?(e.child=r.child,e.flags|=128,null):(o=n.fallback,i=e.mode,n=Fv({mode:"visible",children:n.children},i,0,null),o=Ca(o,i,s,null),o.flags|=2,n.return=e,o.return=e,n.sibling=o,e.child=n,e.mode&1&&cc(e,r.child,null,s),e.child.memoizedState=OS(s),e.memoizedState=xS,o);if(!(e.mode&1))return Zf(r,e,s,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var a=n.dgst;return n=a,o=Error(he(419)),n=Rg(o,n,void 0),Zf(r,e,s,n)}if(a=(s&r.childLanes)!==0,Sn||a){if(n=Tr,n!==null){switch(s&-s){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(n.suspendedLanes|s)?0:i,i!==0&&i!==o.retryLane&&(o.retryLane=i,Mo(r,i),bi(n,r,i,-1))}return xE(),n=Rg(Error(he(421))),Zf(r,e,s,n)}return i.data==="$?"?(e.flags|=128,e.child=r.child,e=lF.bind(null,r),i._reactRetry=e,null):(r=o.treeContext,Un=_s(i.nextSibling),jn=e,Mt=!0,vi=null,r!==null&&(Wn[qn++]=_o,Wn[qn++]=Eo,Wn[qn++]=Ma,_o=r.id,Eo=r.overflow,Ma=e),e=wE(e,n.children),e.flags|=4096,e)}function UT(r,e,t){r.lanes|=e;var n=r.alternate;n!==null&&(n.lanes|=e),wS(r.return,e,t)}function Cg(r,e,t,n,i){var o=r.memoizedState;o===null?r.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:n,tail:t,tailMode:i}:(o.isBackwards=e,o.rendering=null,o.renderingStartTime=0,o.last=n,o.tail=t,o.tailMode=i)}function SP(r,e,t){var n=e.pendingProps,i=n.revealOrder,o=n.tail;if(Jr(r,e,n.children,t),n=Ut.current,n&2)n=n&1|2,e.flags|=128;else{if(r!==null&&r.flags&128)e:for(r=e.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&UT(r,t,e);else if(r.tag===19)UT(r,t,e);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===e)break e;for(;r.sibling===null;){if(r.return===null||r.return===e)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}n&=1}if(wt(Ut,n),!(e.mode&1))e.memoizedState=null;else switch(i){case"forwards":for(t=e.child,i=null;t!==null;)r=t.alternate,r!==null&&Ap(r)===null&&(i=t),t=t.sibling;t=i,t===null?(i=e.child,e.child=null):(i=t.sibling,t.sibling=null),Cg(e,!1,i,t,o);break;case"backwards":for(t=null,i=e.child,e.child=null;i!==null;){if(r=i.alternate,r!==null&&Ap(r)===null){e.child=i;break}r=i.sibling,i.sibling=t,t=i,i=r}Cg(e,!0,t,null,o);break;case"together":Cg(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function $h(r,e){!(e.mode&1)&&r!==null&&(r.alternate=null,e.alternate=null,e.flags|=2)}function Ao(r,e,t){if(r!==null&&(e.dependencies=r.dependencies),Da|=e.lanes,!(t&e.childLanes))return null;if(r!==null&&e.child!==r.child)throw Error(he(153));if(e.child!==null){for(r=e.child,t=Rs(r,r.pendingProps),e.child=t,t.return=e;r.sibling!==null;)r=r.sibling,t=t.sibling=Rs(r,r.pendingProps),t.return=e;t.sibling=null}return e.child}function Jj(r,e,t){switch(e.tag){case 3:gP(e),lc();break;case 5:qO(e);break;case 1:En(e.type)&&kp(e);break;case 4:vE(e,e.stateNode.containerInfo);break;case 10:var n=e.type._context,i=e.memoizedProps.value;wt(Op,n._currentValue),n._currentValue=i;break;case 13:if(n=e.memoizedState,n!==null)return n.dehydrated!==null?(wt(Ut,Ut.current&1),e.flags|=128,null):t&e.child.childLanes?yP(r,e,t):(wt(Ut,Ut.current&1),r=Ao(r,e,t),r!==null?r.sibling:null);wt(Ut,Ut.current&1);break;case 19:if(n=(t&e.childLanes)!==0,r.flags&128){if(n)return SP(r,e,t);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),wt(Ut,Ut.current),n)break;return null;case 22:case 23:return e.lanes=0,vP(r,e,t)}return Ao(r,e,t)}var bP,PS,_P,EP;bP=function(r,e){for(var t=e.child;t!==null;){if(t.tag===5||t.tag===6)r.appendChild(t.stateNode);else if(t.tag!==4&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}};PS=function(){};_P=function(r,e,t,n){var i=r.memoizedProps;if(i!==n){r=e.stateNode,wa(Ji.current);var o=null;switch(t){case"input":i=Zy(r,i),n=Zy(r,n),o=[];break;case"select":i=Ft({},i,{value:void 0}),n=Ft({},n,{value:void 0}),o=[];break;case"textarea":i=rS(r,i),n=rS(r,n),o=[];break;default:typeof i.onClick!="function"&&typeof n.onClick=="function"&&(r.onclick=Rp)}iS(t,n);var s;t=null;for(c in i)if(!n.hasOwnProperty(c)&&i.hasOwnProperty(c)&&i[c]!=null)if(c==="style"){var a=i[c];for(s in a)a.hasOwnProperty(s)&&(t||(t={}),t[s]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(ud.hasOwnProperty(c)?o||(o=[]):(o=o||[]).push(c,null));for(c in n){var l=n[c];if(a=i!=null?i[c]:void 0,n.hasOwnProperty(c)&&l!==a&&(l!=null||a!=null))if(c==="style")if(a){for(s in a)!a.hasOwnProperty(s)||l&&l.hasOwnProperty(s)||(t||(t={}),t[s]="");for(s in l)l.hasOwnProperty(s)&&a[s]!==l[s]&&(t||(t={}),t[s]=l[s])}else t||(o||(o=[]),o.push(c,t)),t=l;else c==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(o=o||[]).push(c,l)):c==="children"?typeof l!="string"&&typeof l!="number"||(o=o||[]).push(c,""+l):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(ud.hasOwnProperty(c)?(l!=null&&c==="onScroll"&&Ct("scroll",r),o||a===l||(o=[])):(o=o||[]).push(c,l))}t&&(o=o||[]).push("style",t);var c=o;(e.updateQueue=c)&&(e.flags|=4)}};EP=function(r,e,t,n){t!==n&&(e.flags|=4)};function iu(r,e){if(!Mt)switch(r.tailMode){case"hidden":e=r.tail;for(var t=null;e!==null;)e.alternate!==null&&(t=e),e=e.sibling;t===null?r.tail=null:t.sibling=null;break;case"collapsed":t=r.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e||r.tail===null?r.tail=null:r.tail.sibling=null:n.sibling=null}}function Fr(r){var e=r.alternate!==null&&r.alternate.child===r.child,t=0,n=0;if(e)for(var i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags&14680064,n|=i.flags&14680064,i.return=r,i=i.sibling;else for(i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags,n|=i.flags,i.return=r,i=i.sibling;return r.subtreeFlags|=n,r.childLanes=t,e}function Xj(r,e,t){var n=e.pendingProps;switch(lE(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Fr(e),null;case 1:return En(e.type)&&Cp(),Fr(e),null;case 3:return n=e.stateNode,uc(),It(_n),It(qr),gE(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(r===null||r.child===null)&&(Xf(e)?e.flags|=4:r===null||r.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,vi!==null&&(FS(vi),vi=null))),PS(r,e),Fr(e),null;case 5:mE(e);var i=wa(Ed.current);if(t=e.type,r!==null&&e.stateNode!=null)_P(r,e,t,n,i),r.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!n){if(e.stateNode===null)throw Error(he(166));return Fr(e),null}if(r=wa(Ji.current),Xf(e)){n=e.stateNode,t=e.type;var o=e.memoizedProps;switch(n[qi]=e,n[bd]=o,r=(e.mode&1)!==0,t){case"dialog":Ct("cancel",n),Ct("close",n);break;case"iframe":case"object":case"embed":Ct("load",n);break;case"video":case"audio":for(i=0;i<Ou.length;i++)Ct(Ou[i],n);break;case"source":Ct("error",n);break;case"img":case"image":case"link":Ct("error",n),Ct("load",n);break;case"details":Ct("toggle",n);break;case"input":G0(n,o),Ct("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!o.multiple},Ct("invalid",n);break;case"textarea":z0(n,o),Ct("invalid",n)}iS(t,o),i=null;for(var s in o)if(o.hasOwnProperty(s)){var a=o[s];s==="children"?typeof a=="string"?n.textContent!==a&&(o.suppressHydrationWarning!==!0&&Jf(n.textContent,a,r),i=["children",a]):typeof a=="number"&&n.textContent!==""+a&&(o.suppressHydrationWarning!==!0&&Jf(n.textContent,a,r),i=["children",""+a]):ud.hasOwnProperty(s)&&a!=null&&s==="onScroll"&&Ct("scroll",n)}switch(t){case"input":Vf(n),H0(n,o,!0);break;case"textarea":Vf(n),Y0(n);break;case"select":case"option":break;default:typeof o.onClick=="function"&&(n.onclick=Rp)}n=i,e.updateQueue=n,n!==null&&(e.flags|=4)}else{s=i.nodeType===9?i:i.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=Jx(t)),r==="http://www.w3.org/1999/xhtml"?t==="script"?(r=s.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof n.is=="string"?r=s.createElement(t,{is:n.is}):(r=s.createElement(t),t==="select"&&(s=r,n.multiple?s.multiple=!0:n.size&&(s.size=n.size))):r=s.createElementNS(r,t),r[qi]=e,r[bd]=n,bP(r,e,!1,!1),e.stateNode=r;e:{switch(s=oS(t,n),t){case"dialog":Ct("cancel",r),Ct("close",r),i=n;break;case"iframe":case"object":case"embed":Ct("load",r),i=n;break;case"video":case"audio":for(i=0;i<Ou.length;i++)Ct(Ou[i],r);i=n;break;case"source":Ct("error",r),i=n;break;case"img":case"image":case"link":Ct("error",r),Ct("load",r),i=n;break;case"details":Ct("toggle",r),i=n;break;case"input":G0(r,n),i=Zy(r,n),Ct("invalid",r);break;case"option":i=n;break;case"select":r._wrapperState={wasMultiple:!!n.multiple},i=Ft({},n,{value:void 0}),Ct("invalid",r);break;case"textarea":z0(r,n),i=rS(r,n),Ct("invalid",r);break;default:i=n}iS(t,i),a=i;for(o in a)if(a.hasOwnProperty(o)){var l=a[o];o==="style"?Zx(r,l):o==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&Xx(r,l)):o==="children"?typeof l=="string"?(t!=="textarea"||l!=="")&&dd(r,l):typeof l=="number"&&dd(r,""+l):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(ud.hasOwnProperty(o)?l!=null&&o==="onScroll"&&Ct("scroll",r):l!=null&&H_(r,o,l,s))}switch(t){case"input":Vf(r),H0(r,n,!1);break;case"textarea":Vf(r),Y0(r);break;case"option":n.value!=null&&r.setAttribute("value",""+xs(n.value));break;case"select":r.multiple=!!n.multiple,o=n.value,o!=null?Vl(r,!!n.multiple,o,!1):n.defaultValue!=null&&Vl(r,!!n.multiple,n.defaultValue,!0);break;default:typeof i.onClick=="function"&&(r.onclick=Rp)}switch(t){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return Fr(e),null;case 6:if(r&&e.stateNode!=null)EP(r,e,r.memoizedProps,n);else{if(typeof n!="string"&&e.stateNode===null)throw Error(he(166));if(t=wa(Ed.current),wa(Ji.current),Xf(e)){if(n=e.stateNode,t=e.memoizedProps,n[qi]=e,(o=n.nodeValue!==t)&&(r=jn,r!==null))switch(r.tag){case 3:Jf(n.nodeValue,t,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&Jf(n.nodeValue,t,(r.mode&1)!==0)}o&&(e.flags|=4)}else n=(t.nodeType===9?t:t.ownerDocument).createTextNode(n),n[qi]=e,e.stateNode=n}return Fr(e),null;case 13:if(It(Ut),n=e.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(Mt&&Un!==null&&e.mode&1&&!(e.flags&128))BO(),lc(),e.flags|=98560,o=!1;else if(o=Xf(e),n!==null&&n.dehydrated!==null){if(r===null){if(!o)throw Error(he(318));if(o=e.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(he(317));o[qi]=e}else lc(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Fr(e),o=!1}else vi!==null&&(FS(vi),vi=null),o=!0;if(!o)return e.flags&65536?e:null}return e.flags&128?(e.lanes=t,e):(n=n!==null,n!==(r!==null&&r.memoizedState!==null)&&n&&(e.child.flags|=8192,e.mode&1&&(r===null||Ut.current&1?fr===0&&(fr=3):xE())),e.updateQueue!==null&&(e.flags|=4),Fr(e),null);case 4:return uc(),PS(r,e),r===null&&yd(e.stateNode.containerInfo),Fr(e),null;case 10:return fE(e.type._context),Fr(e),null;case 17:return En(e.type)&&Cp(),Fr(e),null;case 19:if(It(Ut),o=e.memoizedState,o===null)return Fr(e),null;if(n=(e.flags&128)!==0,s=o.rendering,s===null)if(n)iu(o,!1);else{if(fr!==0||r!==null&&r.flags&128)for(r=e.child;r!==null;){if(s=Ap(r),s!==null){for(e.flags|=128,iu(o,!1),n=s.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),e.subtreeFlags=0,n=t,t=e.child;t!==null;)o=t,r=n,o.flags&=14680066,s=o.alternate,s===null?(o.childLanes=0,o.lanes=r,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=s.childLanes,o.lanes=s.lanes,o.child=s.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=s.memoizedProps,o.memoizedState=s.memoizedState,o.updateQueue=s.updateQueue,o.type=s.type,r=s.dependencies,o.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),t=t.sibling;return wt(Ut,Ut.current&1|2),e.child}r=r.sibling}o.tail!==null&&Jt()>fc&&(e.flags|=128,n=!0,iu(o,!1),e.lanes=4194304)}else{if(!n)if(r=Ap(s),r!==null){if(e.flags|=128,n=!0,t=r.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),iu(o,!0),o.tail===null&&o.tailMode==="hidden"&&!s.alternate&&!Mt)return Fr(e),null}else 2*Jt()-o.renderingStartTime>fc&&t!==1073741824&&(e.flags|=128,n=!0,iu(o,!1),e.lanes=4194304);o.isBackwards?(s.sibling=e.child,e.child=s):(t=o.last,t!==null?t.sibling=s:e.child=s,o.last=s)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=Jt(),e.sibling=null,t=Ut.current,wt(Ut,n?t&1|2:t&1),e):(Fr(e),null);case 22:case 23:return IE(),n=e.memoizedState!==null,r!==null&&r.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Dn&1073741824&&(Fr(e),e.subtreeFlags&6&&(e.flags|=8192)):Fr(e),null;case 24:return null;case 25:return null}throw Error(he(156,e.tag))}function Qj(r,e){switch(lE(e),e.tag){case 1:return En(e.type)&&Cp(),r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 3:return uc(),It(_n),It(qr),gE(),r=e.flags,r&65536&&!(r&128)?(e.flags=r&-65537|128,e):null;case 5:return mE(e),null;case 13:if(It(Ut),r=e.memoizedState,r!==null&&r.dehydrated!==null){if(e.alternate===null)throw Error(he(340));lc()}return r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 19:return It(Ut),null;case 4:return uc(),null;case 10:return fE(e.type._context),null;case 22:case 23:return IE(),null;case 24:return null;default:return null}}var eh=!1,$r=!1,Zj=typeof WeakSet=="function"?WeakSet:Set,xe=null;function Ul(r,e){var t=r.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(n){qt(r,e,n)}else t.current=null}function MS(r,e,t){try{t()}catch(n){qt(r,e,n)}}var jT=!1;function eF(r,e){if(vS=Ep,r=kO(),sE(r)){if("selectionStart"in r)var t={start:r.selectionStart,end:r.selectionEnd};else e:{t=(t=r.ownerDocument)&&t.defaultView||window;var n=t.getSelection&&t.getSelection();if(n&&n.rangeCount!==0){t=n.anchorNode;var i=n.anchorOffset,o=n.focusNode;n=n.focusOffset;try{t.nodeType,o.nodeType}catch{t=null;break e}var s=0,a=-1,l=-1,c=0,u=0,d=r,f=null;t:for(;;){for(var p;d!==t||i!==0&&d.nodeType!==3||(a=s+i),d!==o||n!==0&&d.nodeType!==3||(l=s+n),d.nodeType===3&&(s+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===r)break t;if(f===t&&++c===i&&(a=s),f===o&&++u===n&&(l=s),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(mS={focusedElem:r,selectionRange:t},Ep=!1,xe=e;xe!==null;)if(e=xe,r=e.child,(e.subtreeFlags&1028)!==0&&r!==null)r.return=e,xe=r;else for(;xe!==null;){e=xe;try{var h=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(h!==null){var m=h.memoizedProps,E=h.memoizedState,y=e.stateNode,S=y.getSnapshotBeforeUpdate(e.elementType===e.type?m:ui(e.type,m),E);y.__reactInternalSnapshotBeforeUpdate=S}break;case 3:var R=e.stateNode.containerInfo;R.nodeType===1?R.textContent="":R.nodeType===9&&R.documentElement&&R.removeChild(R.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(he(163))}}catch(k){qt(e,e.return,k)}if(r=e.sibling,r!==null){r.return=e.return,xe=r;break}xe=e.return}return h=jT,jT=!1,h}function Yu(r,e,t){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&r)===r){var o=i.destroy;i.destroy=void 0,o!==void 0&&MS(e,t,o)}i=i.next}while(i!==n)}}function Uv(r,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var t=e=e.next;do{if((t.tag&r)===r){var n=t.create;t.destroy=n()}t=t.next}while(t!==e)}}function AS(r){var e=r.ref;if(e!==null){var t=r.stateNode;switch(r.tag){case 5:r=t;break;default:r=t}typeof e=="function"?e(r):e.current=r}}function wP(r){var e=r.alternate;e!==null&&(r.alternate=null,wP(e)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(e=r.stateNode,e!==null&&(delete e[qi],delete e[bd],delete e[SS],delete e[Lj],delete e[Uj])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function TP(r){return r.tag===5||r.tag===3||r.tag===4}function FT(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||TP(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function DS(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.nodeType===8?t.parentNode.insertBefore(r,e):t.insertBefore(r,e):(t.nodeType===8?(e=t.parentNode,e.insertBefore(r,t)):(e=t,e.appendChild(r)),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=Rp));else if(n!==4&&(r=r.child,r!==null))for(DS(r,e,t),r=r.sibling;r!==null;)DS(r,e,t),r=r.sibling}function NS(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.insertBefore(r,e):t.appendChild(r);else if(n!==4&&(r=r.child,r!==null))for(NS(r,e,t),r=r.sibling;r!==null;)NS(r,e,t),r=r.sibling}var xr=null,fi=!1;function qo(r,e,t){for(t=t.child;t!==null;)RP(r,e,t),t=t.sibling}function RP(r,e,t){if(Yi&&typeof Yi.onCommitFiberUnmount=="function")try{Yi.onCommitFiberUnmount(xv,t)}catch{}switch(t.tag){case 5:$r||Ul(t,e);case 6:var n=xr,i=fi;xr=null,qo(r,e,t),xr=n,fi=i,xr!==null&&(fi?(r=xr,t=t.stateNode,r.nodeType===8?r.parentNode.removeChild(t):r.removeChild(t)):xr.removeChild(t.stateNode));break;case 18:xr!==null&&(fi?(r=xr,t=t.stateNode,r.nodeType===8?Sg(r.parentNode,t):r.nodeType===1&&Sg(r,t),vd(r)):Sg(xr,t.stateNode));break;case 4:n=xr,i=fi,xr=t.stateNode.containerInfo,fi=!0,qo(r,e,t),xr=n,fi=i;break;case 0:case 11:case 14:case 15:if(!$r&&(n=t.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var o=i,s=o.destroy;o=o.tag,s!==void 0&&(o&2||o&4)&&MS(t,e,s),i=i.next}while(i!==n)}qo(r,e,t);break;case 1:if(!$r&&(Ul(t,e),n=t.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=t.memoizedProps,n.state=t.memoizedState,n.componentWillUnmount()}catch(a){qt(t,e,a)}qo(r,e,t);break;case 21:qo(r,e,t);break;case 22:t.mode&1?($r=(n=$r)||t.memoizedState!==null,qo(r,e,t),$r=n):qo(r,e,t);break;default:qo(r,e,t)}}function BT(r){var e=r.updateQueue;if(e!==null){r.updateQueue=null;var t=r.stateNode;t===null&&(t=r.stateNode=new Zj),e.forEach(function(n){var i=cF.bind(null,r,n);t.has(n)||(t.add(n),n.then(i,i))})}}function oi(r,e){var t=e.deletions;if(t!==null)for(var n=0;n<t.length;n++){var i=t[n];try{var o=r,s=e,a=s;e:for(;a!==null;){switch(a.tag){case 5:xr=a.stateNode,fi=!1;break e;case 3:xr=a.stateNode.containerInfo,fi=!0;break e;case 4:xr=a.stateNode.containerInfo,fi=!0;break e}a=a.return}if(xr===null)throw Error(he(160));RP(o,s,i),xr=null,fi=!1;var l=i.alternate;l!==null&&(l.return=null),i.return=null}catch(c){qt(i,e,c)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)CP(e,r),e=e.sibling}function CP(r,e){var t=r.alternate,n=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(oi(e,r),Mi(r),n&4){try{Yu(3,r,r.return),Uv(3,r)}catch(m){qt(r,r.return,m)}try{Yu(5,r,r.return)}catch(m){qt(r,r.return,m)}}break;case 1:oi(e,r),Mi(r),n&512&&t!==null&&Ul(t,t.return);break;case 5:if(oi(e,r),Mi(r),n&512&&t!==null&&Ul(t,t.return),r.flags&32){var i=r.stateNode;try{dd(i,"")}catch(m){qt(r,r.return,m)}}if(n&4&&(i=r.stateNode,i!=null)){var o=r.memoizedProps,s=t!==null?t.memoizedProps:o,a=r.type,l=r.updateQueue;if(r.updateQueue=null,l!==null)try{a==="input"&&o.type==="radio"&&o.name!=null&&zx(i,o),oS(a,s);var c=oS(a,o);for(s=0;s<l.length;s+=2){var u=l[s],d=l[s+1];u==="style"?Zx(i,d):u==="dangerouslySetInnerHTML"?Xx(i,d):u==="children"?dd(i,d):H_(i,u,d,c)}switch(a){case"input":eS(i,o);break;case"textarea":Yx(i,o);break;case"select":var f=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!o.multiple;var p=o.value;p!=null?Vl(i,!!o.multiple,p,!1):f!==!!o.multiple&&(o.defaultValue!=null?Vl(i,!!o.multiple,o.defaultValue,!0):Vl(i,!!o.multiple,o.multiple?[]:"",!1))}i[bd]=o}catch(m){qt(r,r.return,m)}}break;case 6:if(oi(e,r),Mi(r),n&4){if(r.stateNode===null)throw Error(he(162));i=r.stateNode,o=r.memoizedProps;try{i.nodeValue=o}catch(m){qt(r,r.return,m)}}break;case 3:if(oi(e,r),Mi(r),n&4&&t!==null&&t.memoizedState.isDehydrated)try{vd(e.containerInfo)}catch(m){qt(r,r.return,m)}break;case 4:oi(e,r),Mi(r);break;case 13:oi(e,r),Mi(r),i=r.child,i.flags&8192&&(o=i.memoizedState!==null,i.stateNode.isHidden=o,!o||i.alternate!==null&&i.alternate.memoizedState!==null||(CE=Jt())),n&4&&BT(r);break;case 22:if(u=t!==null&&t.memoizedState!==null,r.mode&1?($r=(c=$r)||u,oi(e,r),$r=c):oi(e,r),Mi(r),n&8192){if(c=r.memoizedState!==null,(r.stateNode.isHidden=c)&&!u&&r.mode&1)for(xe=r,u=r.child;u!==null;){for(d=xe=u;xe!==null;){switch(f=xe,p=f.child,f.tag){case 0:case 11:case 14:case 15:Yu(4,f,f.return);break;case 1:Ul(f,f.return);var h=f.stateNode;if(typeof h.componentWillUnmount=="function"){n=f,t=f.return;try{e=n,h.props=e.memoizedProps,h.state=e.memoizedState,h.componentWillUnmount()}catch(m){qt(n,t,m)}}break;case 5:Ul(f,f.return);break;case 22:if(f.memoizedState!==null){VT(d);continue}}p!==null?(p.return=f,xe=p):VT(d)}u=u.sibling}e:for(u=null,d=r;;){if(d.tag===5){if(u===null){u=d;try{i=d.stateNode,c?(o=i.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none"):(a=d.stateNode,l=d.memoizedProps.style,s=l!=null&&l.hasOwnProperty("display")?l.display:null,a.style.display=Qx("display",s))}catch(m){qt(r,r.return,m)}}}else if(d.tag===6){if(u===null)try{d.stateNode.nodeValue=c?"":d.memoizedProps}catch(m){qt(r,r.return,m)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===r)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===r)break e;for(;d.sibling===null;){if(d.return===null||d.return===r)break e;u===d&&(u=null),d=d.return}u===d&&(u=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:oi(e,r),Mi(r),n&4&&BT(r);break;case 21:break;default:oi(e,r),Mi(r)}}function Mi(r){var e=r.flags;if(e&2){try{e:{for(var t=r.return;t!==null;){if(TP(t)){var n=t;break e}t=t.return}throw Error(he(160))}switch(n.tag){case 5:var i=n.stateNode;n.flags&32&&(dd(i,""),n.flags&=-33);var o=FT(r);NS(r,o,i);break;case 3:case 4:var s=n.stateNode.containerInfo,a=FT(r);DS(r,a,s);break;default:throw Error(he(161))}}catch(l){qt(r,r.return,l)}r.flags&=-3}e&4096&&(r.flags&=-4097)}function tF(r,e,t){xe=r,kP(r)}function kP(r,e,t){for(var n=(r.mode&1)!==0;xe!==null;){var i=xe,o=i.child;if(i.tag===22&&n){var s=i.memoizedState!==null||eh;if(!s){var a=i.alternate,l=a!==null&&a.memoizedState!==null||$r;a=eh;var c=$r;if(eh=s,($r=l)&&!c)for(xe=i;xe!==null;)s=xe,l=s.child,s.tag===22&&s.memoizedState!==null?$T(i):l!==null?(l.return=s,xe=l):$T(i);for(;o!==null;)xe=o,kP(o),o=o.sibling;xe=i,eh=a,$r=c}KT(r)}else i.subtreeFlags&8772&&o!==null?(o.return=i,xe=o):KT(r)}}function KT(r){for(;xe!==null;){var e=xe;if(e.flags&8772){var t=e.alternate;try{if(e.flags&8772)switch(e.tag){case 0:case 11:case 15:$r||Uv(5,e);break;case 1:var n=e.stateNode;if(e.flags&4&&!$r)if(t===null)n.componentDidMount();else{var i=e.elementType===e.type?t.memoizedProps:ui(e.type,t.memoizedProps);n.componentDidUpdate(i,t.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var o=e.updateQueue;o!==null&&RT(e,o,n);break;case 3:var s=e.updateQueue;if(s!==null){if(t=null,e.child!==null)switch(e.child.tag){case 5:t=e.child.stateNode;break;case 1:t=e.child.stateNode}RT(e,s,t)}break;case 5:var a=e.stateNode;if(t===null&&e.flags&4){t=a;var l=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&t.focus();break;case"img":l.src&&(t.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var c=e.alternate;if(c!==null){var u=c.memoizedState;if(u!==null){var d=u.dehydrated;d!==null&&vd(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(he(163))}$r||e.flags&512&&AS(e)}catch(f){qt(e,e.return,f)}}if(e===r){xe=null;break}if(t=e.sibling,t!==null){t.return=e.return,xe=t;break}xe=e.return}}function VT(r){for(;xe!==null;){var e=xe;if(e===r){xe=null;break}var t=e.sibling;if(t!==null){t.return=e.return,xe=t;break}xe=e.return}}function $T(r){for(;xe!==null;){var e=xe;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{Uv(4,e)}catch(l){qt(e,t,l)}break;case 1:var n=e.stateNode;if(typeof n.componentDidMount=="function"){var i=e.return;try{n.componentDidMount()}catch(l){qt(e,i,l)}}var o=e.return;try{AS(e)}catch(l){qt(e,o,l)}break;case 5:var s=e.return;try{AS(e)}catch(l){qt(e,s,l)}}}catch(l){qt(e,e.return,l)}if(e===r){xe=null;break}var a=e.sibling;if(a!==null){a.return=e.return,xe=a;break}xe=e.return}}var rF=Math.ceil,Lp=Uo.ReactCurrentDispatcher,TE=Uo.ReactCurrentOwner,zn=Uo.ReactCurrentBatchConfig,st=0,Tr=null,nr=null,Nr=0,Dn=0,jl=Fs(0),fr=0,Cd=null,Da=0,jv=0,RE=0,Ju=null,yn=null,CE=0,fc=1/0,vo=null,Up=!1,LS=null,ws=null,th=!1,vs=null,jp=0,Xu=0,US=null,Wh=-1,qh=0;function en(){return st&6?Jt():Wh!==-1?Wh:Wh=Jt()}function Ts(r){return r.mode&1?st&2&&Nr!==0?Nr&-Nr:Fj.transition!==null?(qh===0&&(qh=dO()),qh):(r=ft,r!==0||(r=window.event,r=r===void 0?16:yO(r.type)),r):1}function bi(r,e,t,n){if(50<Xu)throw Xu=0,US=null,Error(he(185));rf(r,t,n),(!(st&2)||r!==Tr)&&(r===Tr&&(!(st&2)&&(jv|=t),fr===4&&fs(r,Nr)),wn(r,n),t===1&&st===0&&!(e.mode&1)&&(fc=Jt()+500,Dv&&Bs()))}function wn(r,e){var t=r.callbackNode;F2(r,e);var n=_p(r,r===Tr?Nr:0);if(n===0)t!==null&&Q0(t),r.callbackNode=null,r.callbackPriority=0;else if(e=n&-n,r.callbackPriority!==e){if(t!=null&&Q0(t),e===1)r.tag===0?jj(WT.bind(null,r)):UO(WT.bind(null,r)),Dj(function(){!(st&6)&&Bs()}),t=null;else{switch(fO(n)){case 1:t=Q_;break;case 4:t=cO;break;case 16:t=bp;break;case 536870912:t=uO;break;default:t=bp}t=NP(t,IP.bind(null,r))}r.callbackPriority=e,r.callbackNode=t}}function IP(r,e){if(Wh=-1,qh=0,st&6)throw Error(he(327));var t=r.callbackNode;if(Hl()&&r.callbackNode!==t)return null;var n=_p(r,r===Tr?Nr:0);if(n===0)return null;if(n&30||n&r.expiredLanes||e)e=Fp(r,n);else{e=n;var i=st;st|=2;var o=OP();(Tr!==r||Nr!==e)&&(vo=null,fc=Jt()+500,Ra(r,e));do try{oF();break}catch(a){xP(r,a)}while(!0);dE(),Lp.current=o,st=i,nr!==null?e=0:(Tr=null,Nr=0,e=fr)}if(e!==0){if(e===2&&(i=uS(r),i!==0&&(n=i,e=jS(r,i))),e===1)throw t=Cd,Ra(r,0),fs(r,n),wn(r,Jt()),t;if(e===6)fs(r,n);else{if(i=r.current.alternate,!(n&30)&&!nF(i)&&(e=Fp(r,n),e===2&&(o=uS(r),o!==0&&(n=o,e=jS(r,o))),e===1))throw t=Cd,Ra(r,0),fs(r,n),wn(r,Jt()),t;switch(r.finishedWork=i,r.finishedLanes=n,e){case 0:case 1:throw Error(he(345));case 2:la(r,yn,vo);break;case 3:if(fs(r,n),(n&130023424)===n&&(e=CE+500-Jt(),10<e)){if(_p(r,0)!==0)break;if(i=r.suspendedLanes,(i&n)!==n){en(),r.pingedLanes|=r.suspendedLanes&i;break}r.timeoutHandle=yS(la.bind(null,r,yn,vo),e);break}la(r,yn,vo);break;case 4:if(fs(r,n),(n&4194240)===n)break;for(e=r.eventTimes,i=-1;0<n;){var s=31-Si(n);o=1<<s,s=e[s],s>i&&(i=s),n&=~o}if(n=i,n=Jt()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*rF(n/1960))-n,10<n){r.timeoutHandle=yS(la.bind(null,r,yn,vo),n);break}la(r,yn,vo);break;case 5:la(r,yn,vo);break;default:throw Error(he(329))}}}return wn(r,Jt()),r.callbackNode===t?IP.bind(null,r):null}function jS(r,e){var t=Ju;return r.current.memoizedState.isDehydrated&&(Ra(r,e).flags|=256),r=Fp(r,e),r!==2&&(e=yn,yn=t,e!==null&&FS(e)),r}function FS(r){yn===null?yn=r:yn.push.apply(yn,r)}function nF(r){for(var e=r;;){if(e.flags&16384){var t=e.updateQueue;if(t!==null&&(t=t.stores,t!==null))for(var n=0;n<t.length;n++){var i=t[n],o=i.getSnapshot;i=i.value;try{if(!Ti(o(),i))return!1}catch{return!1}}}if(t=e.child,e.subtreeFlags&16384&&t!==null)t.return=e,e=t;else{if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function fs(r,e){for(e&=~RE,e&=~jv,r.suspendedLanes|=e,r.pingedLanes&=~e,r=r.expirationTimes;0<e;){var t=31-Si(e),n=1<<t;r[t]=-1,e&=~n}}function WT(r){if(st&6)throw Error(he(327));Hl();var e=_p(r,0);if(!(e&1))return wn(r,Jt()),null;var t=Fp(r,e);if(r.tag!==0&&t===2){var n=uS(r);n!==0&&(e=n,t=jS(r,n))}if(t===1)throw t=Cd,Ra(r,0),fs(r,e),wn(r,Jt()),t;if(t===6)throw Error(he(345));return r.finishedWork=r.current.alternate,r.finishedLanes=e,la(r,yn,vo),wn(r,Jt()),null}function kE(r,e){var t=st;st|=1;try{return r(e)}finally{st=t,st===0&&(fc=Jt()+500,Dv&&Bs())}}function Na(r){vs!==null&&vs.tag===0&&!(st&6)&&Hl();var e=st;st|=1;var t=zn.transition,n=ft;try{if(zn.transition=null,ft=1,r)return r()}finally{ft=n,zn.transition=t,st=e,!(st&6)&&Bs()}}function IE(){Dn=jl.current,It(jl)}function Ra(r,e){r.finishedWork=null,r.finishedLanes=0;var t=r.timeoutHandle;if(t!==-1&&(r.timeoutHandle=-1,Aj(t)),nr!==null)for(t=nr.return;t!==null;){var n=t;switch(lE(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&Cp();break;case 3:uc(),It(_n),It(qr),gE();break;case 5:mE(n);break;case 4:uc();break;case 13:It(Ut);break;case 19:It(Ut);break;case 10:fE(n.type._context);break;case 22:case 23:IE()}t=t.return}if(Tr=r,nr=r=Rs(r.current,null),Nr=Dn=e,fr=0,Cd=null,RE=jv=Da=0,yn=Ju=null,Ea!==null){for(e=0;e<Ea.length;e++)if(t=Ea[e],n=t.interleaved,n!==null){t.interleaved=null;var i=n.next,o=t.pending;if(o!==null){var s=o.next;o.next=i,n.next=s}t.pending=n}Ea=null}return r}function xP(r,e){do{var t=nr;try{if(dE(),Kh.current=Np,Dp){for(var n=jt.memoizedState;n!==null;){var i=n.queue;i!==null&&(i.pending=null),n=n.next}Dp=!1}if(Aa=0,_r=ur=jt=null,zu=!1,wd=0,TE.current=null,t===null||t.return===null){fr=1,Cd=e,nr=null;break}e:{var o=r,s=t.return,a=t,l=e;if(e=Nr,a.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var c=l,u=a,d=u.tag;if(!(u.mode&1)&&(d===0||d===11||d===15)){var f=u.alternate;f?(u.updateQueue=f.updateQueue,u.memoizedState=f.memoizedState,u.lanes=f.lanes):(u.updateQueue=null,u.memoizedState=null)}var p=PT(s);if(p!==null){p.flags&=-257,MT(p,s,a,o,e),p.mode&1&&OT(o,c,e),e=p,l=c;var h=e.updateQueue;if(h===null){var m=new Set;m.add(l),e.updateQueue=m}else h.add(l);break e}else{if(!(e&1)){OT(o,c,e),xE();break e}l=Error(he(426))}}else if(Mt&&a.mode&1){var E=PT(s);if(E!==null){!(E.flags&65536)&&(E.flags|=256),MT(E,s,a,o,e),cE(dc(l,a));break e}}o=l=dc(l,a),fr!==4&&(fr=2),Ju===null?Ju=[o]:Ju.push(o),o=s;do{switch(o.tag){case 3:o.flags|=65536,e&=-e,o.lanes|=e;var y=fP(o,l,e);TT(o,y);break e;case 1:a=l;var S=o.type,R=o.stateNode;if(!(o.flags&128)&&(typeof S.getDerivedStateFromError=="function"||R!==null&&typeof R.componentDidCatch=="function"&&(ws===null||!ws.has(R)))){o.flags|=65536,e&=-e,o.lanes|=e;var k=hP(o,a,e);TT(o,k);break e}}o=o.return}while(o!==null)}MP(t)}catch(x){e=x,nr===t&&t!==null&&(nr=t=t.return);continue}break}while(!0)}function OP(){var r=Lp.current;return Lp.current=Np,r===null?Np:r}function xE(){(fr===0||fr===3||fr===2)&&(fr=4),Tr===null||!(Da&268435455)&&!(jv&268435455)||fs(Tr,Nr)}function Fp(r,e){var t=st;st|=2;var n=OP();(Tr!==r||Nr!==e)&&(vo=null,Ra(r,e));do try{iF();break}catch(i){xP(r,i)}while(!0);if(dE(),st=t,Lp.current=n,nr!==null)throw Error(he(261));return Tr=null,Nr=0,fr}function iF(){for(;nr!==null;)PP(nr)}function oF(){for(;nr!==null&&!O2();)PP(nr)}function PP(r){var e=DP(r.alternate,r,Dn);r.memoizedProps=r.pendingProps,e===null?MP(r):nr=e,TE.current=null}function MP(r){var e=r;do{var t=e.alternate;if(r=e.return,e.flags&32768){if(t=Qj(t,e),t!==null){t.flags&=32767,nr=t;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{fr=6,nr=null;return}}else if(t=Xj(t,e,Dn),t!==null){nr=t;return}if(e=e.sibling,e!==null){nr=e;return}nr=e=r}while(e!==null);fr===0&&(fr=5)}function la(r,e,t){var n=ft,i=zn.transition;try{zn.transition=null,ft=1,sF(r,e,t,n)}finally{zn.transition=i,ft=n}return null}function sF(r,e,t,n){do Hl();while(vs!==null);if(st&6)throw Error(he(327));t=r.finishedWork;var i=r.finishedLanes;if(t===null)return null;if(r.finishedWork=null,r.finishedLanes=0,t===r.current)throw Error(he(177));r.callbackNode=null,r.callbackPriority=0;var o=t.lanes|t.childLanes;if(B2(r,o),r===Tr&&(nr=Tr=null,Nr=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||th||(th=!0,NP(bp,function(){return Hl(),null})),o=(t.flags&15990)!==0,t.subtreeFlags&15990||o){o=zn.transition,zn.transition=null;var s=ft;ft=1;var a=st;st|=4,TE.current=null,eF(r,t),CP(t,r),Cj(mS),Ep=!!vS,mS=vS=null,r.current=t,tF(t),P2(),st=a,ft=s,zn.transition=o}else r.current=t;if(th&&(th=!1,vs=r,jp=i),o=r.pendingLanes,o===0&&(ws=null),D2(t.stateNode),wn(r,Jt()),e!==null)for(n=r.onRecoverableError,t=0;t<e.length;t++)i=e[t],n(i.value,{componentStack:i.stack,digest:i.digest});if(Up)throw Up=!1,r=LS,LS=null,r;return jp&1&&r.tag!==0&&Hl(),o=r.pendingLanes,o&1?r===US?Xu++:(Xu=0,US=r):Xu=0,Bs(),null}function Hl(){if(vs!==null){var r=fO(jp),e=zn.transition,t=ft;try{if(zn.transition=null,ft=16>r?16:r,vs===null)var n=!1;else{if(r=vs,vs=null,jp=0,st&6)throw Error(he(331));var i=st;for(st|=4,xe=r.current;xe!==null;){var o=xe,s=o.child;if(xe.flags&16){var a=o.deletions;if(a!==null){for(var l=0;l<a.length;l++){var c=a[l];for(xe=c;xe!==null;){var u=xe;switch(u.tag){case 0:case 11:case 15:Yu(8,u,o)}var d=u.child;if(d!==null)d.return=u,xe=d;else for(;xe!==null;){u=xe;var f=u.sibling,p=u.return;if(wP(u),u===c){xe=null;break}if(f!==null){f.return=p,xe=f;break}xe=p}}}var h=o.alternate;if(h!==null){var m=h.child;if(m!==null){h.child=null;do{var E=m.sibling;m.sibling=null,m=E}while(m!==null)}}xe=o}}if(o.subtreeFlags&2064&&s!==null)s.return=o,xe=s;else e:for(;xe!==null;){if(o=xe,o.flags&2048)switch(o.tag){case 0:case 11:case 15:Yu(9,o,o.return)}var y=o.sibling;if(y!==null){y.return=o.return,xe=y;break e}xe=o.return}}var S=r.current;for(xe=S;xe!==null;){s=xe;var R=s.child;if(s.subtreeFlags&2064&&R!==null)R.return=s,xe=R;else e:for(s=S;xe!==null;){if(a=xe,a.flags&2048)try{switch(a.tag){case 0:case 11:case 15:Uv(9,a)}}catch(x){qt(a,a.return,x)}if(a===s){xe=null;break e}var k=a.sibling;if(k!==null){k.return=a.return,xe=k;break e}xe=a.return}}if(st=i,Bs(),Yi&&typeof Yi.onPostCommitFiberRoot=="function")try{Yi.onPostCommitFiberRoot(xv,r)}catch{}n=!0}return n}finally{ft=t,zn.transition=e}}return!1}function qT(r,e,t){e=dc(t,e),e=fP(r,e,1),r=Es(r,e,1),e=en(),r!==null&&(rf(r,1,e),wn(r,e))}function qt(r,e,t){if(r.tag===3)qT(r,r,t);else for(;e!==null;){if(e.tag===3){qT(e,r,t);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(ws===null||!ws.has(n))){r=dc(t,r),r=hP(e,r,1),e=Es(e,r,1),r=en(),e!==null&&(rf(e,1,r),wn(e,r));break}}e=e.return}}function aF(r,e,t){var n=r.pingCache;n!==null&&n.delete(e),e=en(),r.pingedLanes|=r.suspendedLanes&t,Tr===r&&(Nr&t)===t&&(fr===4||fr===3&&(Nr&130023424)===Nr&&500>Jt()-CE?Ra(r,0):RE|=t),wn(r,e)}function AP(r,e){e===0&&(r.mode&1?(e=qf,qf<<=1,!(qf&130023424)&&(qf=4194304)):e=1);var t=en();r=Mo(r,e),r!==null&&(rf(r,e,t),wn(r,t))}function lF(r){var e=r.memoizedState,t=0;e!==null&&(t=e.retryLane),AP(r,t)}function cF(r,e){var t=0;switch(r.tag){case 13:var n=r.stateNode,i=r.memoizedState;i!==null&&(t=i.retryLane);break;case 19:n=r.stateNode;break;default:throw Error(he(314))}n!==null&&n.delete(e),AP(r,t)}var DP;DP=function(r,e,t){if(r!==null)if(r.memoizedProps!==e.pendingProps||_n.current)Sn=!0;else{if(!(r.lanes&t)&&!(e.flags&128))return Sn=!1,Jj(r,e,t);Sn=!!(r.flags&131072)}else Sn=!1,Mt&&e.flags&1048576&&jO(e,xp,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;$h(r,e),r=e.pendingProps;var i=ac(e,qr.current);Gl(e,t),i=SE(null,e,n,r,i,t);var o=bE();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,En(n)?(o=!0,kp(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,pE(e),i.updater=Lv,e.stateNode=i,i._reactInternals=e,RS(e,n,r,t),e=IS(null,e,n,!0,o,t)):(e.tag=0,Mt&&o&&aE(e),Jr(null,e,i,t),e=e.child),e;case 16:n=e.elementType;e:{switch($h(r,e),r=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=dF(n),r=ui(n,r),i){case 0:e=kS(null,e,n,r,t);break e;case 1:e=NT(null,e,n,r,t);break e;case 11:e=AT(null,e,n,r,t);break e;case 14:e=DT(null,e,n,ui(n.type,r),t);break e}throw Error(he(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),kS(r,e,n,i,t);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),NT(r,e,n,i,t);case 3:e:{if(gP(e),r===null)throw Error(he(387));n=e.pendingProps,o=e.memoizedState,i=o.element,WO(r,e),Mp(e,n,null,t);var s=e.memoizedState;if(n=s.element,o.isDehydrated)if(o={element:n,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},e.updateQueue.baseState=o,e.memoizedState=o,e.flags&256){i=dc(Error(he(423)),e),e=LT(r,e,n,t,i);break e}else if(n!==i){i=dc(Error(he(424)),e),e=LT(r,e,n,t,i);break e}else for(Un=_s(e.stateNode.containerInfo.firstChild),jn=e,Mt=!0,vi=null,t=VO(e,null,n,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(lc(),n===i){e=Ao(r,e,t);break e}Jr(r,e,n,t)}e=e.child}return e;case 5:return qO(e),r===null&&ES(e),n=e.type,i=e.pendingProps,o=r!==null?r.memoizedProps:null,s=i.children,gS(n,i)?s=null:o!==null&&gS(n,o)&&(e.flags|=32),mP(r,e),Jr(r,e,s,t),e.child;case 6:return r===null&&ES(e),null;case 13:return yP(r,e,t);case 4:return vE(e,e.stateNode.containerInfo),n=e.pendingProps,r===null?e.child=cc(e,null,n,t):Jr(r,e,n,t),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),AT(r,e,n,i,t);case 7:return Jr(r,e,e.pendingProps,t),e.child;case 8:return Jr(r,e,e.pendingProps.children,t),e.child;case 12:return Jr(r,e,e.pendingProps.children,t),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,o=e.memoizedProps,s=i.value,wt(Op,n._currentValue),n._currentValue=s,o!==null)if(Ti(o.value,s)){if(o.children===i.children&&!_n.current){e=Ao(r,e,t);break e}}else for(o=e.child,o!==null&&(o.return=e);o!==null;){var a=o.dependencies;if(a!==null){s=o.child;for(var l=a.firstContext;l!==null;){if(l.context===n){if(o.tag===1){l=Co(-1,t&-t),l.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?l.next=l:(l.next=u.next,u.next=l),c.pending=l}}o.lanes|=t,l=o.alternate,l!==null&&(l.lanes|=t),wS(o.return,t,e),a.lanes|=t;break}l=l.next}}else if(o.tag===10)s=o.type===e.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(he(341));s.lanes|=t,a=s.alternate,a!==null&&(a.lanes|=t),wS(s,t,e),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===e){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}Jr(r,e,i.children,t),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,Gl(e,t),i=Xn(i),n=n(i),e.flags|=1,Jr(r,e,n,t),e.child;case 14:return n=e.type,i=ui(n,e.pendingProps),i=ui(n.type,i),DT(r,e,n,i,t);case 15:return pP(r,e,e.type,e.pendingProps,t);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:ui(n,i),$h(r,e),e.tag=1,En(n)?(r=!0,kp(e)):r=!1,Gl(e,t),dP(e,n,i),RS(e,n,i,t),IS(null,e,n,!0,r,t);case 19:return SP(r,e,t);case 22:return vP(r,e,t)}throw Error(he(156,e.tag))};function NP(r,e){return lO(r,e)}function uF(r,e,t,n){this.tag=r,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Gn(r,e,t,n){return new uF(r,e,t,n)}function OE(r){return r=r.prototype,!(!r||!r.isReactComponent)}function dF(r){if(typeof r=="function")return OE(r)?1:0;if(r!=null){if(r=r.$$typeof,r===Y_)return 11;if(r===J_)return 14}return 2}function Rs(r,e){var t=r.alternate;return t===null?(t=Gn(r.tag,e,r.key,r.mode),t.elementType=r.elementType,t.type=r.type,t.stateNode=r.stateNode,t.alternate=r,r.alternate=t):(t.pendingProps=e,t.type=r.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=r.flags&14680064,t.childLanes=r.childLanes,t.lanes=r.lanes,t.child=r.child,t.memoizedProps=r.memoizedProps,t.memoizedState=r.memoizedState,t.updateQueue=r.updateQueue,e=r.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=r.sibling,t.index=r.index,t.ref=r.ref,t}function Gh(r,e,t,n,i,o){var s=2;if(n=r,typeof r=="function")OE(r)&&(s=1);else if(typeof r=="string")s=5;else e:switch(r){case Il:return Ca(t.children,i,o,e);case z_:s=8,i|=8;break;case Yy:return r=Gn(12,t,e,i|2),r.elementType=Yy,r.lanes=o,r;case Jy:return r=Gn(13,t,e,i),r.elementType=Jy,r.lanes=o,r;case Xy:return r=Gn(19,t,e,i),r.elementType=Xy,r.lanes=o,r;case qx:return Fv(t,i,o,e);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case $x:s=10;break e;case Wx:s=9;break e;case Y_:s=11;break e;case J_:s=14;break e;case as:s=16,n=null;break e}throw Error(he(130,r==null?r:typeof r,""))}return e=Gn(s,t,e,i),e.elementType=r,e.type=n,e.lanes=o,e}function Ca(r,e,t,n){return r=Gn(7,r,n,e),r.lanes=t,r}function Fv(r,e,t,n){return r=Gn(22,r,n,e),r.elementType=qx,r.lanes=t,r.stateNode={isHidden:!1},r}function kg(r,e,t){return r=Gn(6,r,null,e),r.lanes=t,r}function Ig(r,e,t){return e=Gn(4,r.children!==null?r.children:[],r.key,e),e.lanes=t,e.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},e}function fF(r,e,t,n,i){this.tag=e,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=lg(0),this.expirationTimes=lg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=lg(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function PE(r,e,t,n,i,o,s,a,l){return r=new fF(r,e,t,a,l),e===1?(e=1,o===!0&&(e|=8)):e=0,o=Gn(3,null,null,e),r.current=o,o.stateNode=r,o.memoizedState={element:n,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},pE(o),r}function hF(r,e,t){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:kl,key:n==null?null:""+n,children:r,containerInfo:e,implementation:t}}function LP(r){if(!r)return Os;r=r._reactInternals;e:{if(Ha(r)!==r||r.tag!==1)throw Error(he(170));var e=r;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(En(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(he(171))}if(r.tag===1){var t=r.type;if(En(t))return LO(r,t,e)}return e}function UP(r,e,t,n,i,o,s,a,l){return r=PE(t,n,!0,r,i,o,s,a,l),r.context=LP(null),t=r.current,n=en(),i=Ts(t),o=Co(n,i),o.callback=e??null,Es(t,o,i),r.current.lanes=i,rf(r,i,n),wn(r,n),r}function Bv(r,e,t,n){var i=e.current,o=en(),s=Ts(i);return t=LP(t),e.context===null?e.context=t:e.pendingContext=t,e=Co(o,s),e.payload={element:r},n=n===void 0?null:n,n!==null&&(e.callback=n),r=Es(i,e,s),r!==null&&(bi(r,i,s,o),Bh(r,i,s)),s}function Bp(r){if(r=r.current,!r.child)return null;switch(r.child.tag){case 5:return r.child.stateNode;default:return r.child.stateNode}}function GT(r,e){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var t=r.retryLane;r.retryLane=t!==0&&t<e?t:e}}function ME(r,e){GT(r,e),(r=r.alternate)&&GT(r,e)}function pF(){return null}var jP=typeof reportError=="function"?reportError:function(r){console.error(r)};function AE(r){this._internalRoot=r}Kv.prototype.render=AE.prototype.render=function(r){var e=this._internalRoot;if(e===null)throw Error(he(409));Bv(r,e,null,null)};Kv.prototype.unmount=AE.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var e=r.containerInfo;Na(function(){Bv(null,r,null,null)}),e[Po]=null}};function Kv(r){this._internalRoot=r}Kv.prototype.unstable_scheduleHydration=function(r){if(r){var e=vO();r={blockedOn:null,target:r,priority:e};for(var t=0;t<ds.length&&e!==0&&e<ds[t].priority;t++);ds.splice(t,0,r),t===0&&gO(r)}};function DE(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Vv(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function HT(){}function vF(r,e,t,n,i){if(i){if(typeof n=="function"){var o=n;n=function(){var c=Bp(s);o.call(c)}}var s=UP(e,n,r,0,null,!1,!1,"",HT);return r._reactRootContainer=s,r[Po]=s.current,yd(r.nodeType===8?r.parentNode:r),Na(),s}for(;i=r.lastChild;)r.removeChild(i);if(typeof n=="function"){var a=n;n=function(){var c=Bp(l);a.call(c)}}var l=PE(r,0,!1,null,null,!1,!1,"",HT);return r._reactRootContainer=l,r[Po]=l.current,yd(r.nodeType===8?r.parentNode:r),Na(function(){Bv(e,l,t,n)}),l}function $v(r,e,t,n,i){var o=t._reactRootContainer;if(o){var s=o;if(typeof i=="function"){var a=i;i=function(){var l=Bp(s);a.call(l)}}Bv(e,s,r,i)}else s=vF(t,e,r,i,n);return Bp(s)}hO=function(r){switch(r.tag){case 3:var e=r.stateNode;if(e.current.memoizedState.isDehydrated){var t=xu(e.pendingLanes);t!==0&&(Z_(e,t|1),wn(e,Jt()),!(st&6)&&(fc=Jt()+500,Bs()))}break;case 13:Na(function(){var n=Mo(r,1);if(n!==null){var i=en();bi(n,r,1,i)}}),ME(r,1)}};eE=function(r){if(r.tag===13){var e=Mo(r,134217728);if(e!==null){var t=en();bi(e,r,134217728,t)}ME(r,134217728)}};pO=function(r){if(r.tag===13){var e=Ts(r),t=Mo(r,e);if(t!==null){var n=en();bi(t,r,e,n)}ME(r,e)}};vO=function(){return ft};mO=function(r,e){var t=ft;try{return ft=r,e()}finally{ft=t}};aS=function(r,e,t){switch(e){case"input":if(eS(r,t),e=t.name,t.type==="radio"&&e!=null){for(t=r;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<t.length;e++){var n=t[e];if(n!==r&&n.form===r.form){var i=Av(n);if(!i)throw Error(he(90));Hx(n),eS(n,i)}}}break;case"textarea":Yx(r,t);break;case"select":e=t.value,e!=null&&Vl(r,!!t.multiple,e,!1)}};rO=kE;nO=Na;var mF={usingClientEntryPoint:!1,Events:[of,Ml,Av,eO,tO,kE]},ou={findFiberByHostInstance:_a,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},gF={bundleType:ou.bundleType,version:ou.version,rendererPackageName:ou.rendererPackageName,rendererConfig:ou.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Uo.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=sO(r),r===null?null:r.stateNode},findFiberByHostInstance:ou.findFiberByHostInstance||pF,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var rh=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!rh.isDisabled&&rh.supportsFiber)try{xv=rh.inject(gF),Yi=rh}catch{}}Kn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=mF;Kn.createPortal=function(r,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!DE(e))throw Error(he(200));return hF(r,e,null,t)};Kn.createRoot=function(r,e){if(!DE(r))throw Error(he(299));var t=!1,n="",i=jP;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(n=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=PE(r,1,!1,null,null,t,!1,n,i),r[Po]=e.current,yd(r.nodeType===8?r.parentNode:r),new AE(e)};Kn.findDOMNode=function(r){if(r==null)return null;if(r.nodeType===1)return r;var e=r._reactInternals;if(e===void 0)throw typeof r.render=="function"?Error(he(188)):(r=Object.keys(r).join(","),Error(he(268,r)));return r=sO(e),r=r===null?null:r.stateNode,r};Kn.flushSync=function(r){return Na(r)};Kn.hydrate=function(r,e,t){if(!Vv(e))throw Error(he(200));return $v(null,r,e,!0,t)};Kn.hydrateRoot=function(r,e,t){if(!DE(r))throw Error(he(405));var n=t!=null&&t.hydratedSources||null,i=!1,o="",s=jP;if(t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onRecoverableError!==void 0&&(s=t.onRecoverableError)),e=UP(e,null,r,1,t??null,i,!1,o,s),r[Po]=e.current,yd(r),n)for(r=0;r<n.length;r++)t=n[r],i=t._getVersion,i=i(t._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[t,i]:e.mutableSourceEagerHydrationData.push(t,i);return new Kv(e)};Kn.render=function(r,e,t){if(!Vv(e))throw Error(he(200));return $v(null,r,e,!1,t)};Kn.unmountComponentAtNode=function(r){if(!Vv(r))throw Error(he(40));return r._reactRootContainer?(Na(function(){$v(null,null,r,!1,function(){r._reactRootContainer=null,r[Po]=null})}),!0):!1};Kn.unstable_batchedUpdates=kE;Kn.unstable_renderSubtreeIntoContainer=function(r,e,t,n){if(!Vv(t))throw Error(he(200));if(r==null||r._reactInternals===void 0)throw Error(he(38));return $v(r,e,t,!1,n)};Kn.version="18.3.1-next-f1338f8080-20240426";function FP(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(FP)}catch(r){console.error(r)}}FP(),Fx.exports=Kn;var Wv=Fx.exports;const BP=qa(Wv);var KP,zT=Wv;KP=zT.createRoot,zT.hydrateRoot;/**
41
- * @remix-run/router v1.23.2
42
- *
43
- * Copyright (c) Remix Software Inc.
44
- *
45
- * This source code is licensed under the MIT license found in the
46
- * LICENSE.md file in the root directory of this source tree.
47
- *
48
- * @license MIT
49
- */function kd(){return kd=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},kd.apply(this,arguments)}var Hn;(function(r){r.Pop="POP",r.Push="PUSH",r.Replace="REPLACE"})(Hn||(Hn={}));const YT="popstate";function yF(r){r===void 0&&(r={});let{initialEntries:e=["/"],initialIndex:t,v5Compat:n=!1}=r,i;i=e.map((p,h)=>u(p,typeof p=="string"?null:p.state,h===0?"default":void 0));let o=l(t??i.length-1),s=Hn.Pop,a=null;function l(p){return Math.min(Math.max(p,0),i.length-1)}function c(){return i[o]}function u(p,h,m){h===void 0&&(h=null);let E=Kp(i?c().pathname:"/",p,h,m);return qv(E.pathname.charAt(0)==="/","relative pathnames are not supported in memory history: "+JSON.stringify(p)),E}function d(p){return typeof p=="string"?p:Id(p)}return{get index(){return o},get action(){return s},get location(){return c()},createHref:d,createURL(p){return new URL(d(p),"http://localhost")},encodeLocation(p){let h=typeof p=="string"?za(p):p;return{pathname:h.pathname||"",search:h.search||"",hash:h.hash||""}},push(p,h){s=Hn.Push;let m=u(p,h);o+=1,i.splice(o,i.length,m),n&&a&&a({action:s,location:m,delta:1})},replace(p,h){s=Hn.Replace;let m=u(p,h);i[o]=m,n&&a&&a({action:s,location:m,delta:0})},go(p){s=Hn.Pop;let h=l(o+p),m=i[h];o=h,a&&a({action:s,location:m,delta:p})},listen(p){return a=p,()=>{a=null}}}}function SF(r){r===void 0&&(r={});function e(n,i){let{pathname:o,search:s,hash:a}=n.location;return Kp("",{pathname:o,search:s,hash:a},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function t(n,i){return typeof i=="string"?i:Id(i)}return _F(e,t,null,r)}function Ht(r,e){if(r===!1||r===null||typeof r>"u")throw new Error(e)}function qv(r,e){if(!r){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function bF(){return Math.random().toString(36).substr(2,8)}function JT(r,e){return{usr:r.state,key:r.key,idx:e}}function Kp(r,e,t,n){return t===void 0&&(t=null),kd({pathname:typeof r=="string"?r:r.pathname,search:"",hash:""},typeof e=="string"?za(e):e,{state:t,key:e&&e.key||n||bF()})}function Id(r){let{pathname:e="/",search:t="",hash:n=""}=r;return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function za(r){let e={};if(r){let t=r.indexOf("#");t>=0&&(e.hash=r.substr(t),r=r.substr(0,t));let n=r.indexOf("?");n>=0&&(e.search=r.substr(n),r=r.substr(0,n)),r&&(e.pathname=r)}return e}function _F(r,e,t,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:o=!1}=n,s=i.history,a=Hn.Pop,l=null,c=u();c==null&&(c=0,s.replaceState(kd({},s.state,{idx:c}),""));function u(){return(s.state||{idx:null}).idx}function d(){a=Hn.Pop;let E=u(),y=E==null?null:E-c;c=E,l&&l({action:a,location:m.location,delta:y})}function f(E,y){a=Hn.Push;let S=Kp(m.location,E,y);c=u()+1;let R=JT(S,c),k=m.createHref(S);try{s.pushState(R,"",k)}catch(x){if(x instanceof DOMException&&x.name==="DataCloneError")throw x;i.location.assign(k)}o&&l&&l({action:a,location:m.location,delta:1})}function p(E,y){a=Hn.Replace;let S=Kp(m.location,E,y);c=u();let R=JT(S,c),k=m.createHref(S);s.replaceState(R,"",k),o&&l&&l({action:a,location:m.location,delta:0})}function h(E){let y=i.location.origin!=="null"?i.location.origin:i.location.href,S=typeof E=="string"?E:Id(E);return S=S.replace(/ $/,"%20"),Ht(y,"No window.location.(origin|href) available to create URL for href: "+S),new URL(S,y)}let m={get action(){return a},get location(){return r(i,s)},listen(E){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(YT,d),l=E,()=>{i.removeEventListener(YT,d),l=null}},createHref(E){return e(i,E)},createURL:h,encodeLocation(E){let y=h(E);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:f,replace:p,go(E){return s.go(E)}};return m}var XT;(function(r){r.data="data",r.deferred="deferred",r.redirect="redirect",r.error="error"})(XT||(XT={}));function EF(r,e,t){return t===void 0&&(t="/"),wF(r,e,t)}function wF(r,e,t,n){let i=typeof e=="string"?za(e):e,o=NE(i.pathname||"/",t);if(o==null)return null;let s=VP(r);TF(s);let a=null;for(let l=0;a==null&&l<s.length;++l){let c=qP(o);a=AF(s[l],c)}return a}function VP(r,e,t,n){e===void 0&&(e=[]),t===void 0&&(t=[]),n===void 0&&(n="");let i=(o,s,a)=>{let l={relativePath:a===void 0?o.path||"":a,caseSensitive:o.caseSensitive===!0,childrenIndex:s,route:o};l.relativePath.startsWith("/")&&(Ht(l.relativePath.startsWith(n),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(n.length));let c=Cs([n,l.relativePath]),u=t.concat(l);o.children&&o.children.length>0&&(Ht(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),VP(o.children,e,u,c)),!(o.path==null&&!o.index)&&e.push({path:c,score:PF(c,o.index),routesMeta:u})};return r.forEach((o,s)=>{var a;if(o.path===""||!((a=o.path)!=null&&a.includes("?")))i(o,s);else for(let l of $P(o.path))i(o,s,l)}),e}function $P(r){let e=r.split("/");if(e.length===0)return[];let[t,...n]=e,i=t.endsWith("?"),o=t.replace(/\?$/,"");if(n.length===0)return i?[o,""]:[o];let s=$P(n.join("/")),a=[];return a.push(...s.map(l=>l===""?o:[o,l].join("/"))),i&&a.push(...s),a.map(l=>r.startsWith("/")&&l===""?"/":l)}function TF(r){r.sort((e,t)=>e.score!==t.score?t.score-e.score:MF(e.routesMeta.map(n=>n.childrenIndex),t.routesMeta.map(n=>n.childrenIndex)))}const RF=/^:[\w-]+$/,CF=3,kF=2,IF=1,xF=10,OF=-2,QT=r=>r==="*";function PF(r,e){let t=r.split("/"),n=t.length;return t.some(QT)&&(n+=OF),e&&(n+=kF),t.filter(i=>!QT(i)).reduce((i,o)=>i+(RF.test(o)?CF:o===""?IF:xF),n)}function MF(r,e){return r.length===e.length&&r.slice(0,-1).every((n,i)=>n===e[i])?r[r.length-1]-e[e.length-1]:0}function AF(r,e,t){let{routesMeta:n}=r,i={},o="/",s=[];for(let a=0;a<n.length;++a){let l=n[a],c=a===n.length-1,u=o==="/"?e:e.slice(o.length)||"/",d=WP({path:l.relativePath,caseSensitive:l.caseSensitive,end:c},u),f=l.route;if(!d)return null;Object.assign(i,d.params),s.push({params:i,pathname:Cs([o,d.pathname]),pathnameBase:FF(Cs([o,d.pathnameBase])),route:f}),d.pathnameBase!=="/"&&(o=Cs([o,d.pathnameBase]))}return s}function WP(r,e){typeof r=="string"&&(r={path:r,caseSensitive:!1,end:!0});let[t,n]=DF(r.path,r.caseSensitive,r.end),i=e.match(t);if(!i)return null;let o=i[0],s=o.replace(/(.)\/+$/,"$1"),a=i.slice(1);return{params:n.reduce((c,u,d)=>{let{paramName:f,isOptional:p}=u;if(f==="*"){let m=a[d]||"";s=o.slice(0,o.length-m.length).replace(/(.)\/+$/,"$1")}const h=a[d];return p&&!h?c[f]=void 0:c[f]=(h||"").replace(/%2F/g,"/"),c},{}),pathname:o,pathnameBase:s,pattern:r}}function DF(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!0),qv(r==="*"||!r.endsWith("*")||r.endsWith("/*"),'Route path "'+r+'" will be treated as if it were '+('"'+r.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+r.replace(/\*$/,"/*")+'".'));let n=[],i="^"+r.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(s,a,l)=>(n.push({paramName:a,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return r.endsWith("*")?(n.push({paramName:"*"}),i+=r==="*"||r==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?i+="\\/*$":r!==""&&r!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),n]}function qP(r){try{return r.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return qv(!1,'The URL path "'+r+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),r}}function NE(r,e){if(e==="/")return r;if(!r.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,n=r.charAt(t);return n&&n!=="/"?null:r.slice(t)||"/"}const NF=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,LF=r=>NF.test(r);function UF(r,e){e===void 0&&(e="/");let{pathname:t,search:n="",hash:i=""}=typeof r=="string"?za(r):r,o;if(t)if(LF(t))o=t;else{if(t.includes("//")){let s=t;t=t.replace(/\/\/+/g,"/"),qv(!1,"Pathnames cannot have embedded double slashes - normalizing "+(s+" -> "+t))}t.startsWith("/")?o=ZT(t.substring(1),"/"):o=ZT(t,e)}else o=e;return{pathname:o,search:BF(n),hash:KF(i)}}function ZT(r,e){let t=e.replace(/\/+$/,"").split("/");return r.split("/").forEach(i=>{i===".."?t.length>1&&t.pop():i!=="."&&t.push(i)}),t.length>1?t.join("/"):"/"}function xg(r,e,t,n){return"Cannot include a '"+r+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+t+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function jF(r){return r.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function LE(r,e){let t=jF(r);return e?t.map((n,i)=>i===t.length-1?n.pathname:n.pathnameBase):t.map(n=>n.pathnameBase)}function UE(r,e,t,n){n===void 0&&(n=!1);let i;typeof r=="string"?i=za(r):(i=kd({},r),Ht(!i.pathname||!i.pathname.includes("?"),xg("?","pathname","search",i)),Ht(!i.pathname||!i.pathname.includes("#"),xg("#","pathname","hash",i)),Ht(!i.search||!i.search.includes("#"),xg("#","search","hash",i)));let o=r===""||i.pathname==="",s=o?"/":i.pathname,a;if(s==null)a=t;else{let d=e.length-1;if(!n&&s.startsWith("..")){let f=s.split("/");for(;f[0]==="..";)f.shift(),d-=1;i.pathname=f.join("/")}a=d>=0?e[d]:"/"}let l=UF(i,a),c=s&&s!=="/"&&s.endsWith("/"),u=(o||s===".")&&t.endsWith("/");return!l.pathname.endsWith("/")&&(c||u)&&(l.pathname+="/"),l}const Cs=r=>r.join("/").replace(/\/\/+/g,"/"),FF=r=>r.replace(/\/+$/,"").replace(/^\/*/,"/"),BF=r=>!r||r==="?"?"":r.startsWith("?")?r:"?"+r,KF=r=>!r||r==="#"?"":r.startsWith("#")?r:"#"+r;function VF(r){return r!=null&&typeof r.status=="number"&&typeof r.statusText=="string"&&typeof r.internal=="boolean"&&"data"in r}const GP=["post","put","patch","delete"];new Set(GP);const $F=["get",...GP];new Set($F);/**
50
- * React Router v6.30.3
51
- *
52
- * Copyright (c) Remix Software Inc.
53
- *
54
- * This source code is licensed under the MIT license found in the
55
- * LICENSE.md file in the root directory of this source tree.
56
- *
57
- * @license MIT
58
- */function xd(){return xd=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},xd.apply(this,arguments)}const jE=_.createContext(null),WF=_.createContext(null),Ks=_.createContext(null),Gv=_.createContext(null),to=_.createContext({outlet:null,matches:[],isDataRoute:!1}),HP=_.createContext(null);function qF(r,e){let{relative:t}=e===void 0?{}:e;Ya()||Ht(!1);let{basename:n,navigator:i}=_.useContext(Ks),{hash:o,pathname:s,search:a}=XP(r,{relative:t}),l=s;return n!=="/"&&(l=s==="/"?n:Cs([n,s])),i.createHref({pathname:l,search:a,hash:o})}function Ya(){return _.useContext(Gv)!=null}function Ja(){return Ya()||Ht(!1),_.useContext(Gv).location}function zP(r){Ya()||Ht(!1);let{pathname:e}=Ja();return _.useMemo(()=>WP(r,qP(e)),[e,r])}function YP(r){_.useContext(Ks).static||_.useLayoutEffect(r)}function Vs(){let{isDataRoute:r}=_.useContext(to);return r?aB():GF()}function GF(){Ya()||Ht(!1);let r=_.useContext(jE),{basename:e,future:t,navigator:n}=_.useContext(Ks),{matches:i}=_.useContext(to),{pathname:o}=Ja(),s=JSON.stringify(LE(i,t.v7_relativeSplatPath)),a=_.useRef(!1);return YP(()=>{a.current=!0}),_.useCallback(function(c,u){if(u===void 0&&(u={}),!a.current)return;if(typeof c=="number"){n.go(c);return}let d=UE(c,JSON.parse(s),o,u.relative==="path");r==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:Cs([e,d.pathname])),(u.replace?n.replace:n.push)(d,u.state,u)},[e,n,s,o,r])}const JP=_.createContext(null);function HF(){return _.useContext(JP)}function zF(r){let e=_.useContext(to).outlet;return e&&_.createElement(JP.Provider,{value:r},e)}function YF(){let{matches:r}=_.useContext(to),e=r[r.length-1];return e?e.params:{}}function XP(r,e){let{relative:t}=e===void 0?{}:e,{future:n}=_.useContext(Ks),{matches:i}=_.useContext(to),{pathname:o}=Ja(),s=JSON.stringify(LE(i,n.v7_relativeSplatPath));return _.useMemo(()=>UE(r,JSON.parse(s),o,t==="path"),[r,s,o,t])}function JF(r,e){return XF(r,e)}function XF(r,e,t,n){Ya()||Ht(!1);let{navigator:i}=_.useContext(Ks),{matches:o}=_.useContext(to),s=o[o.length-1],a=s?s.params:{};s&&s.pathname;let l=s?s.pathnameBase:"/";s&&s.route;let c=Ja(),u;if(e){var d;let E=typeof e=="string"?za(e):e;l==="/"||(d=E.pathname)!=null&&d.startsWith(l)||Ht(!1),u=E}else u=c;let f=u.pathname||"/",p=f;if(l!=="/"){let E=l.replace(/^\//,"").split("/");p="/"+f.replace(/^\//,"").split("/").slice(E.length).join("/")}let h=EF(r,{pathname:p}),m=rB(h&&h.map(E=>Object.assign({},E,{params:Object.assign({},a,E.params),pathname:Cs([l,i.encodeLocation?i.encodeLocation(E.pathname).pathname:E.pathname]),pathnameBase:E.pathnameBase==="/"?l:Cs([l,i.encodeLocation?i.encodeLocation(E.pathnameBase).pathname:E.pathnameBase])})),o,t,n);return e&&m?_.createElement(Gv.Provider,{value:{location:xd({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:Hn.Pop}},m):m}function QF(){let r=sB(),e=VF(r)?r.status+" "+r.statusText:r instanceof Error?r.message:JSON.stringify(r),t=r instanceof Error?r.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return _.createElement(_.Fragment,null,_.createElement("h2",null,"Unexpected Application Error!"),_.createElement("h3",{style:{fontStyle:"italic"}},e),t?_.createElement("pre",{style:i},t):null,null)}const ZF=_.createElement(QF,null);class eB extends _.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return this.state.error!==void 0?_.createElement(to.Provider,{value:this.props.routeContext},_.createElement(HP.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function tB(r){let{routeContext:e,match:t,children:n}=r,i=_.useContext(jE);return i&&i.static&&i.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=t.route.id),_.createElement(to.Provider,{value:e},n)}function rB(r,e,t,n){var i;if(e===void 0&&(e=[]),t===void 0&&(t=null),n===void 0&&(n=null),r==null){var o;if(!t)return null;if(t.errors)r=t.matches;else if((o=n)!=null&&o.v7_partialHydration&&e.length===0&&!t.initialized&&t.matches.length>0)r=t.matches;else return null}let s=r,a=(i=t)==null?void 0:i.errors;if(a!=null){let u=s.findIndex(d=>d.route.id&&(a==null?void 0:a[d.route.id])!==void 0);u>=0||Ht(!1),s=s.slice(0,Math.min(s.length,u+1))}let l=!1,c=-1;if(t&&n&&n.v7_partialHydration)for(let u=0;u<s.length;u++){let d=s[u];if((d.route.HydrateFallback||d.route.hydrateFallbackElement)&&(c=u),d.route.id){let{loaderData:f,errors:p}=t,h=d.route.loader&&f[d.route.id]===void 0&&(!p||p[d.route.id]===void 0);if(d.route.lazy||h){l=!0,c>=0?s=s.slice(0,c+1):s=[s[0]];break}}}return s.reduceRight((u,d,f)=>{let p,h=!1,m=null,E=null;t&&(p=a&&d.route.id?a[d.route.id]:void 0,m=d.route.errorElement||ZF,l&&(c<0&&f===0?(lB("route-fallback"),h=!0,E=null):c===f&&(h=!0,E=d.route.hydrateFallbackElement||null)));let y=e.concat(s.slice(0,f+1)),S=()=>{let R;return p?R=m:h?R=E:d.route.Component?R=_.createElement(d.route.Component,null):d.route.element?R=d.route.element:R=u,_.createElement(tB,{match:d,routeContext:{outlet:u,matches:y,isDataRoute:t!=null},children:R})};return t&&(d.route.ErrorBoundary||d.route.errorElement||f===0)?_.createElement(eB,{location:t.location,revalidation:t.revalidation,component:m,error:p,children:S(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):S()},null)}var QP=function(r){return r.UseBlocker="useBlocker",r.UseRevalidator="useRevalidator",r.UseNavigateStable="useNavigate",r}(QP||{}),ZP=function(r){return r.UseBlocker="useBlocker",r.UseLoaderData="useLoaderData",r.UseActionData="useActionData",r.UseRouteError="useRouteError",r.UseNavigation="useNavigation",r.UseRouteLoaderData="useRouteLoaderData",r.UseMatches="useMatches",r.UseRevalidator="useRevalidator",r.UseNavigateStable="useNavigate",r.UseRouteId="useRouteId",r}(ZP||{});function nB(r){let e=_.useContext(jE);return e||Ht(!1),e}function iB(r){let e=_.useContext(WF);return e||Ht(!1),e}function oB(r){let e=_.useContext(to);return e||Ht(!1),e}function eM(r){let e=oB(),t=e.matches[e.matches.length-1];return t.route.id||Ht(!1),t.route.id}function sB(){var r;let e=_.useContext(HP),t=iB(),n=eM();return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function aB(){let{router:r}=nB(QP.UseNavigateStable),e=eM(ZP.UseNavigateStable),t=_.useRef(!1);return YP(()=>{t.current=!0}),_.useCallback(function(i,o){o===void 0&&(o={}),t.current&&(typeof i=="number"?r.navigate(i):r.navigate(i,xd({fromRouteId:e},o)))},[r,e])}const eR={};function lB(r,e,t){eR[r]||(eR[r]=!0)}function tM(r,e){r==null||r.v7_startTransition,r==null||r.v7_relativeSplatPath}const cB="startTransition",tR=Iv[cB];function uB(r){let{basename:e,children:t,initialEntries:n,initialIndex:i,future:o}=r,s=_.useRef();s.current==null&&(s.current=yF({initialEntries:n,initialIndex:i,v5Compat:!0}));let a=s.current,[l,c]=_.useState({action:a.action,location:a.location}),{v7_startTransition:u}=o||{},d=_.useCallback(f=>{u&&tR?tR(()=>c(f)):c(f)},[c,u]);return _.useLayoutEffect(()=>a.listen(d),[a,d]),_.useEffect(()=>tM(o),[o]),_.createElement(rM,{basename:e,children:t,location:l.location,navigationType:l.action,navigator:a,future:o})}function Vp(r){let{to:e,replace:t,state:n,relative:i}=r;Ya()||Ht(!1);let{future:o,static:s}=_.useContext(Ks),{matches:a}=_.useContext(to),{pathname:l}=Ja(),c=Vs(),u=UE(e,LE(a,o.v7_relativeSplatPath),l,i==="path"),d=JSON.stringify(u);return _.useEffect(()=>c(JSON.parse(d),{replace:t,state:n,relative:i}),[c,d,i,t,n]),null}function dB(r){return zF(r.context)}function ca(r){Ht(!1)}function rM(r){let{basename:e="/",children:t=null,location:n,navigationType:i=Hn.Pop,navigator:o,static:s=!1,future:a}=r;Ya()&&Ht(!1);let l=e.replace(/^\/*/,"/"),c=_.useMemo(()=>({basename:l,navigator:o,static:s,future:xd({v7_relativeSplatPath:!1},a)}),[l,a,o,s]);typeof n=="string"&&(n=za(n));let{pathname:u="/",search:d="",hash:f="",state:p=null,key:h="default"}=n,m=_.useMemo(()=>{let E=NE(u,l);return E==null?null:{location:{pathname:E,search:d,hash:f,state:p,key:h},navigationType:i}},[l,u,d,f,p,h,i]);return m==null?null:_.createElement(Ks.Provider,{value:c},_.createElement(Gv.Provider,{children:t,value:m}))}function fB(r){let{children:e,location:t}=r;return JF(BS(e),t)}new Promise(()=>{});function BS(r,e){e===void 0&&(e=[]);let t=[];return _.Children.forEach(r,(n,i)=>{if(!_.isValidElement(n))return;let o=[...e,i];if(n.type===_.Fragment){t.push.apply(t,BS(n.props.children,o));return}n.type!==ca&&Ht(!1),!n.props.index||!n.props.children||Ht(!1);let s={id:n.props.id||o.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(s.children=BS(n.props.children,o)),t.push(s)}),t}/**
59
- * React Router DOM v6.30.3
60
- *
61
- * Copyright (c) Remix Software Inc.
62
- *
63
- * This source code is licensed under the MIT license found in the
64
- * LICENSE.md file in the root directory of this source tree.
65
- *
66
- * @license MIT
67
- */function KS(){return KS=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},KS.apply(this,arguments)}function hB(r,e){if(r==null)return{};var t={},n=Object.keys(r),i,o;for(o=0;o<n.length;o++)i=n[o],!(e.indexOf(i)>=0)&&(t[i]=r[i]);return t}function pB(r){return!!(r.metaKey||r.altKey||r.ctrlKey||r.shiftKey)}function vB(r,e){return r.button===0&&(!e||e==="_self")&&!pB(r)}function VS(r){return r===void 0&&(r=""),new URLSearchParams(typeof r=="string"||Array.isArray(r)||r instanceof URLSearchParams?r:Object.keys(r).reduce((e,t)=>{let n=r[t];return e.concat(Array.isArray(n)?n.map(i=>[t,i]):[[t,n]])},[]))}function mB(r,e){let t=VS(r);return e&&e.forEach((n,i)=>{t.has(i)||e.getAll(i).forEach(o=>{t.append(i,o)})}),t}const gB=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],yB="6";try{window.__reactRouterVersion=yB}catch{}const SB="startTransition",rR=Iv[SB];function bB(r){let{basename:e,children:t,future:n,window:i}=r,o=_.useRef();o.current==null&&(o.current=SF({window:i,v5Compat:!0}));let s=o.current,[a,l]=_.useState({action:s.action,location:s.location}),{v7_startTransition:c}=n||{},u=_.useCallback(d=>{c&&rR?rR(()=>l(d)):l(d)},[l,c]);return _.useLayoutEffect(()=>s.listen(u),[s,u]),_.useEffect(()=>tM(n),[n]),_.createElement(rM,{basename:e,children:t,location:a.location,navigationType:a.action,navigator:s,future:n})}const _B=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",EB=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,wB=_.forwardRef(function(e,t){let{onClick:n,relative:i,reloadDocument:o,replace:s,state:a,target:l,to:c,preventScrollReset:u,viewTransition:d}=e,f=hB(e,gB),{basename:p}=_.useContext(Ks),h,m=!1;if(typeof c=="string"&&EB.test(c)&&(h=c,_B))try{let R=new URL(window.location.href),k=c.startsWith("//")?new URL(R.protocol+c):new URL(c),x=NE(k.pathname,p);k.origin===R.origin&&x!=null?c=x+k.search+k.hash:m=!0}catch{}let E=qF(c,{relative:i}),y=TB(c,{replace:s,state:a,target:l,preventScrollReset:u,relative:i,viewTransition:d});function S(R){n&&n(R),R.defaultPrevented||y(R)}return _.createElement("a",KS({},f,{href:h||E,onClick:m||o?n:S,ref:t,target:l}))});var nR;(function(r){r.UseScrollRestoration="useScrollRestoration",r.UseSubmit="useSubmit",r.UseSubmitFetcher="useSubmitFetcher",r.UseFetcher="useFetcher",r.useViewTransitionState="useViewTransitionState"})(nR||(nR={}));var iR;(function(r){r.UseFetcher="useFetcher",r.UseFetchers="useFetchers",r.UseScrollRestoration="useScrollRestoration"})(iR||(iR={}));function TB(r,e){let{target:t,replace:n,state:i,preventScrollReset:o,relative:s,viewTransition:a}=e===void 0?{}:e,l=Vs(),c=Ja(),u=XP(r,{relative:s});return _.useCallback(d=>{if(vB(d,t)){d.preventDefault();let f=n!==void 0?n:Id(c)===Id(u);l(r,{replace:f,state:i,preventScrollReset:o,relative:s,viewTransition:a})}},[c,l,u,n,i,t,r,o,s,a])}function nM(r){let e=_.useRef(VS(r)),t=_.useRef(!1),n=Ja(),i=_.useMemo(()=>mB(n.search,t.current?null:e.current),[n.search]),o=Vs(),s=_.useCallback((a,l)=>{const c=VS(typeof a=="function"?a(i):a);t.current=!0,o("?"+c,l)},[o,i]);return[i,s]}var RB=(r,e,t,n,i,o,s,a)=>{let l=document.documentElement,c=["light","dark"];function u(p){(Array.isArray(r)?r:[r]).forEach(h=>{let m=h==="class",E=m&&o?i.map(y=>o[y]||y):i;m?(l.classList.remove(...E),l.classList.add(o&&o[p]?o[p]:p)):l.setAttribute(h,p)}),d(p)}function d(p){a&&c.includes(p)&&(l.style.colorScheme=p)}function f(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(n)u(n);else try{let p=localStorage.getItem(e)||t,h=s&&p==="system"?f():p;u(h)}catch{}},CB=_.createContext(void 0),kB={setTheme:r=>{},themes:[]},IB=()=>{var r;return(r=_.useContext(CB))!=null?r:kB};_.memo(({forcedTheme:r,storageKey:e,attribute:t,enableSystem:n,enableColorScheme:i,defaultTheme:o,value:s,themes:a,nonce:l,scriptProps:c})=>{let u=JSON.stringify([t,e,o,r,a,s,n,i]).slice(1,-1);return _.createElement("script",{...c,suppressHydrationWarning:!0,nonce:typeof window>"u"?l:"",dangerouslySetInnerHTML:{__html:`(${RB.toString()})(${u})`}})});function xB(r){if(typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}const OB=r=>{switch(r){case"success":return AB;case"info":return NB;case"warning":return DB;case"error":return LB;default:return null}},PB=Array(12).fill(0),MB=({visible:r,className:e})=>ve.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":r},ve.createElement("div",{className:"sonner-spinner"},PB.map((t,n)=>ve.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),AB=ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ve.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),DB=ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ve.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),NB=ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ve.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),LB=ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ve.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),UB=ve.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ve.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ve.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),jB=()=>{const[r,e]=ve.useState(document.hidden);return ve.useEffect(()=>{const t=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",t),()=>window.removeEventListener("visibilitychange",t)},[]),r};let $S=1;class FB{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{const t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;const{message:n,...i}=e,o=typeof(e==null?void 0:e.id)=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:$S++,s=this.toasts.find(l=>l.id===o),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),s?this.toasts=this.toasts.map(l=>l.id===o?(this.publish({...l,...e,id:o,title:n}),{...l,...e,id:o,dismissible:a,title:n}):l):this.addToast({title:n,...i,dismissible:a,id:o}),o},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(t=>{this.subscribers.forEach(n=>n({id:t.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));const i=Promise.resolve(e instanceof Function?e():e);let o=n!==void 0,s;const a=i.then(async c=>{if(s=["resolve",c],ve.isValidElement(c))o=!1,this.create({id:n,type:"default",message:c});else if(KB(c)&&!c.ok){o=!1;const d=typeof t.error=="function"?await t.error(`HTTP error! status: ${c.status}`):t.error,f=typeof t.description=="function"?await t.description(`HTTP error! status: ${c.status}`):t.description,h=typeof d=="object"&&!ve.isValidElement(d)?d:{message:d};this.create({id:n,type:"error",description:f,...h})}else if(c instanceof Error){o=!1;const d=typeof t.error=="function"?await t.error(c):t.error,f=typeof t.description=="function"?await t.description(c):t.description,h=typeof d=="object"&&!ve.isValidElement(d)?d:{message:d};this.create({id:n,type:"error",description:f,...h})}else if(t.success!==void 0){o=!1;const d=typeof t.success=="function"?await t.success(c):t.success,f=typeof t.description=="function"?await t.description(c):t.description,h=typeof d=="object"&&!ve.isValidElement(d)?d:{message:d};this.create({id:n,type:"success",description:f,...h})}}).catch(async c=>{if(s=["reject",c],t.error!==void 0){o=!1;const u=typeof t.error=="function"?await t.error(c):t.error,d=typeof t.description=="function"?await t.description(c):t.description,p=typeof u=="object"&&!ve.isValidElement(u)?u:{message:u};this.create({id:n,type:"error",description:d,...p})}}).finally(()=>{o&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),l=()=>new Promise((c,u)=>a.then(()=>s[0]==="reject"?u(s[1]):c(s[1])).catch(u));return typeof n!="string"&&typeof n!="number"?{unwrap:l}:Object.assign(n,{unwrap:l})},this.custom=(e,t)=>{const n=(t==null?void 0:t.id)||$S++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const mn=new FB,BB=(r,e)=>{const t=(e==null?void 0:e.id)||$S++;return mn.addToast({title:r,...e,id:t}),t},KB=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",VB=BB,$B=()=>mn.toasts,WB=()=>mn.getActiveToasts();Object.assign(VB,{success:mn.success,info:mn.info,warning:mn.warning,error:mn.error,custom:mn.custom,message:mn.message,promise:mn.promise,dismiss:mn.dismiss,loading:mn.loading},{getHistory:$B,getToasts:WB});xB("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function nh(r){return r.label!==void 0}const qB=3,GB="24px",HB="16px",oR=4e3,zB=356,YB=14,JB=45,XB=200;function Ai(...r){return r.filter(Boolean).join(" ")}function QB(r){const[e,t]=r.split("-"),n=[];return e&&n.push(e),t&&n.push(t),n}const ZB=r=>{var e,t,n,i,o,s,a,l,c;const{invert:u,toast:d,unstyled:f,interacting:p,setHeights:h,visibleToasts:m,heights:E,index:y,toasts:S,expanded:R,removeToast:k,defaultRichColors:x,closeButton:T,style:O,cancelButtonStyle:C,actionButtonStyle:N,className:F="",descriptionClassName:H="",duration:ie,position:$,gap:X,expandByDefault:oe,classNames:re,icons:ae,closeButtonAriaLabel:q="Close toast"}=r,[z,Q]=ve.useState(null),[Ie,Y]=ve.useState(null),[le,B]=ve.useState(!1),[W,A]=ve.useState(!1),[D,P]=ve.useState(!1),[M,I]=ve.useState(!1),[j,U]=ve.useState(!1),[K,G]=ve.useState(0),[ee,se]=ve.useState(0),Ce=ve.useRef(d.duration||ie||oR),Re=ve.useRef(null),ge=ve.useRef(null),He=y===0,Qe=y+1<=m,$e=d.type,me=d.dismissible!==!1,We=d.className||"",un=d.descriptionClassName||"",Rr=ve.useMemo(()=>E.findIndex(Ue=>Ue.toastId===d.id)||0,[E,d.id]),gt=ve.useMemo(()=>{var Ue;return(Ue=d.closeButton)!=null?Ue:T},[d.closeButton,T]),vr=ve.useMemo(()=>d.duration||ie||oR,[d.duration,ie]),mr=ve.useRef(0),Rt=ve.useRef(0),Cn=ve.useRef(0),ye=ve.useRef(null),[fe,J]=$.split("-"),te=ve.useMemo(()=>E.reduce((Ue,pt,Vt)=>Vt>=Rr?Ue:Ue+pt.height,0),[E,Rr]),ne=jB(),ue=d.invert||u,Ee=$e==="loading";Rt.current=ve.useMemo(()=>Rr*X+te,[Rr,te]),ve.useEffect(()=>{Ce.current=vr},[vr]),ve.useEffect(()=>{B(!0)},[]),ve.useEffect(()=>{const Ue=ge.current;if(Ue){const pt=Ue.getBoundingClientRect().height;return se(pt),h(Vt=>[{toastId:d.id,height:pt,position:d.position},...Vt]),()=>h(Vt=>Vt.filter(Hr=>Hr.toastId!==d.id))}},[h,d.id]),ve.useLayoutEffect(()=>{if(!le)return;const Ue=ge.current,pt=Ue.style.height;Ue.style.height="auto";const Vt=Ue.getBoundingClientRect().height;Ue.style.height=pt,se(Vt),h(Hr=>Hr.find(tt=>tt.toastId===d.id)?Hr.map(tt=>tt.toastId===d.id?{...tt,height:Vt}:tt):[{toastId:d.id,height:Vt,position:d.position},...Hr])},[le,d.title,d.description,h,d.id,d.jsx,d.action,d.cancel]);const Te=ve.useCallback(()=>{A(!0),G(Rt.current),h(Ue=>Ue.filter(pt=>pt.toastId!==d.id)),setTimeout(()=>{k(d)},XB)},[d,k,h,Rt]);ve.useEffect(()=>{if(d.promise&&$e==="loading"||d.duration===1/0||d.type==="loading")return;let Ue;return R||p||ne?(()=>{if(Cn.current<mr.current){const Hr=new Date().getTime()-mr.current;Ce.current=Ce.current-Hr}Cn.current=new Date().getTime()})():(()=>{Ce.current!==1/0&&(mr.current=new Date().getTime(),Ue=setTimeout(()=>{d.onAutoClose==null||d.onAutoClose.call(d,d),Te()},Ce.current))})(),()=>clearTimeout(Ue)},[R,p,d,$e,ne,Te]),ve.useEffect(()=>{d.delete&&(Te(),d.onDismiss==null||d.onDismiss.call(d,d))},[Te,d.delete]);function ze(){var Ue;if(ae!=null&&ae.loading){var pt;return ve.createElement("div",{className:Ai(re==null?void 0:re.loader,d==null||(pt=d.classNames)==null?void 0:pt.loader,"sonner-loader"),"data-visible":$e==="loading"},ae.loading)}return ve.createElement(MB,{className:Ai(re==null?void 0:re.loader,d==null||(Ue=d.classNames)==null?void 0:Ue.loader),visible:$e==="loading"})}const dt=d.icon||(ae==null?void 0:ae[$e])||OB($e);var ht,Kt;return ve.createElement("li",{tabIndex:0,ref:ge,className:Ai(F,We,re==null?void 0:re.toast,d==null||(e=d.classNames)==null?void 0:e.toast,re==null?void 0:re.default,re==null?void 0:re[$e],d==null||(t=d.classNames)==null?void 0:t[$e]),"data-sonner-toast":"","data-rich-colors":(ht=d.richColors)!=null?ht:x,"data-styled":!(d.jsx||d.unstyled||f),"data-mounted":le,"data-promise":!!d.promise,"data-swiped":j,"data-removed":W,"data-visible":Qe,"data-y-position":fe,"data-x-position":J,"data-index":y,"data-front":He,"data-swiping":D,"data-dismissible":me,"data-type":$e,"data-invert":ue,"data-swipe-out":M,"data-swipe-direction":Ie,"data-expanded":!!(R||oe&&le),"data-testid":d.testId,style:{"--index":y,"--toasts-before":y,"--z-index":S.length-y,"--offset":`${W?K:Rt.current}px`,"--initial-height":oe?"auto":`${ee}px`,...O,...d.style},onDragEnd:()=>{P(!1),Q(null),ye.current=null},onPointerDown:Ue=>{Ue.button!==2&&(Ee||!me||(Re.current=new Date,G(Rt.current),Ue.target.setPointerCapture(Ue.pointerId),Ue.target.tagName!=="BUTTON"&&(P(!0),ye.current={x:Ue.clientX,y:Ue.clientY})))},onPointerUp:()=>{var Ue,pt,Vt;if(M||!me)return;ye.current=null;const Hr=Number(((Ue=ge.current)==null?void 0:Ue.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),rl=Number(((pt=ge.current)==null?void 0:pt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),tt=new Date().getTime()-((Vt=Re.current)==null?void 0:Vt.getTime()),or=z==="x"?Hr:rl,nl=Math.abs(or)/tt;if(Math.abs(or)>=JB||nl>.11){G(Rt.current),d.onDismiss==null||d.onDismiss.call(d,d),Y(z==="x"?Hr>0?"right":"left":rl>0?"down":"up"),Te(),I(!0);return}else{var dn,zr;(dn=ge.current)==null||dn.style.setProperty("--swipe-amount-x","0px"),(zr=ge.current)==null||zr.style.setProperty("--swipe-amount-y","0px")}U(!1),P(!1),Q(null)},onPointerMove:Ue=>{var pt,Vt,Hr;if(!ye.current||!me||((pt=window.getSelection())==null?void 0:pt.toString().length)>0)return;const tt=Ue.clientY-ye.current.y,or=Ue.clientX-ye.current.x;var nl;const dn=(nl=r.swipeDirections)!=null?nl:QB($);!z&&(Math.abs(or)>1||Math.abs(tt)>1)&&Q(Math.abs(or)>Math.abs(tt)?"x":"y");let zr={x:0,y:0};const Xc=Pi=>1/(1.5+Math.abs(Pi)/20);if(z==="y"){if(dn.includes("top")||dn.includes("bottom"))if(dn.includes("top")&&tt<0||dn.includes("bottom")&&tt>0)zr.y=tt;else{const Pi=tt*Xc(tt);zr.y=Math.abs(Pi)<Math.abs(tt)?Pi:tt}}else if(z==="x"&&(dn.includes("left")||dn.includes("right")))if(dn.includes("left")&&or<0||dn.includes("right")&&or>0)zr.x=or;else{const Pi=or*Xc(or);zr.x=Math.abs(Pi)<Math.abs(or)?Pi:or}(Math.abs(zr.x)>0||Math.abs(zr.y)>0)&&U(!0),(Vt=ge.current)==null||Vt.style.setProperty("--swipe-amount-x",`${zr.x}px`),(Hr=ge.current)==null||Hr.style.setProperty("--swipe-amount-y",`${zr.y}px`)}},gt&&!d.jsx&&$e!=="loading"?ve.createElement("button",{"aria-label":q,"data-disabled":Ee,"data-close-button":!0,onClick:Ee||!me?()=>{}:()=>{Te(),d.onDismiss==null||d.onDismiss.call(d,d)},className:Ai(re==null?void 0:re.closeButton,d==null||(n=d.classNames)==null?void 0:n.closeButton)},(Kt=ae==null?void 0:ae.close)!=null?Kt:UB):null,($e||d.icon||d.promise)&&d.icon!==null&&((ae==null?void 0:ae[$e])!==null||d.icon)?ve.createElement("div",{"data-icon":"",className:Ai(re==null?void 0:re.icon,d==null||(i=d.classNames)==null?void 0:i.icon)},d.promise||d.type==="loading"&&!d.icon?d.icon||ze():null,d.type!=="loading"?dt:null):null,ve.createElement("div",{"data-content":"",className:Ai(re==null?void 0:re.content,d==null||(o=d.classNames)==null?void 0:o.content)},ve.createElement("div",{"data-title":"",className:Ai(re==null?void 0:re.title,d==null||(s=d.classNames)==null?void 0:s.title)},d.jsx?d.jsx:typeof d.title=="function"?d.title():d.title),d.description?ve.createElement("div",{"data-description":"",className:Ai(H,un,re==null?void 0:re.description,d==null||(a=d.classNames)==null?void 0:a.description)},typeof d.description=="function"?d.description():d.description):null),ve.isValidElement(d.cancel)?d.cancel:d.cancel&&nh(d.cancel)?ve.createElement("button",{"data-button":!0,"data-cancel":!0,style:d.cancelButtonStyle||C,onClick:Ue=>{nh(d.cancel)&&me&&(d.cancel.onClick==null||d.cancel.onClick.call(d.cancel,Ue),Te())},className:Ai(re==null?void 0:re.cancelButton,d==null||(l=d.classNames)==null?void 0:l.cancelButton)},d.cancel.label):null,ve.isValidElement(d.action)?d.action:d.action&&nh(d.action)?ve.createElement("button",{"data-button":!0,"data-action":!0,style:d.actionButtonStyle||N,onClick:Ue=>{nh(d.action)&&(d.action.onClick==null||d.action.onClick.call(d.action,Ue),!Ue.defaultPrevented&&Te())},className:Ai(re==null?void 0:re.actionButton,d==null||(c=d.classNames)==null?void 0:c.actionButton)},d.action.label):null)};function sR(){if(typeof window>"u"||typeof document>"u")return"ltr";const r=document.documentElement.getAttribute("dir");return r==="auto"||!r?window.getComputedStyle(document.documentElement).direction:r}function eK(r,e){const t={};return[r,e].forEach((n,i)=>{const o=i===1,s=o?"--mobile-offset":"--offset",a=o?HB:GB;function l(c){["top","right","bottom","left"].forEach(u=>{t[`${s}-${u}`]=typeof c=="number"?`${c}px`:c})}typeof n=="number"||typeof n=="string"?l(n):typeof n=="object"?["top","right","bottom","left"].forEach(c=>{n[c]===void 0?t[`${s}-${c}`]=a:t[`${s}-${c}`]=typeof n[c]=="number"?`${n[c]}px`:n[c]}):l(a)}),t}const tK=ve.forwardRef(function(e,t){const{id:n,invert:i,position:o="bottom-right",hotkey:s=["altKey","KeyT"],expand:a,closeButton:l,className:c,offset:u,mobileOffset:d,theme:f="light",richColors:p,duration:h,style:m,visibleToasts:E=qB,toastOptions:y,dir:S=sR(),gap:R=YB,icons:k,containerAriaLabel:x="Notifications"}=e,[T,O]=ve.useState([]),C=ve.useMemo(()=>n?T.filter(le=>le.toasterId===n):T.filter(le=>!le.toasterId),[T,n]),N=ve.useMemo(()=>Array.from(new Set([o].concat(C.filter(le=>le.position).map(le=>le.position)))),[C,o]),[F,H]=ve.useState([]),[ie,$]=ve.useState(!1),[X,oe]=ve.useState(!1),[re,ae]=ve.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),q=ve.useRef(null),z=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),Q=ve.useRef(null),Ie=ve.useRef(!1),Y=ve.useCallback(le=>{O(B=>{var W;return(W=B.find(A=>A.id===le.id))!=null&&W.delete||mn.dismiss(le.id),B.filter(({id:A})=>A!==le.id)})},[]);return ve.useEffect(()=>mn.subscribe(le=>{if(le.dismiss){requestAnimationFrame(()=>{O(B=>B.map(W=>W.id===le.id?{...W,delete:!0}:W))});return}setTimeout(()=>{BP.flushSync(()=>{O(B=>{const W=B.findIndex(A=>A.id===le.id);return W!==-1?[...B.slice(0,W),{...B[W],...le},...B.slice(W+1)]:[le,...B]})})})}),[T]),ve.useEffect(()=>{if(f!=="system"){ae(f);return}if(f==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ae("dark"):ae("light")),typeof window>"u")return;const le=window.matchMedia("(prefers-color-scheme: dark)");try{le.addEventListener("change",({matches:B})=>{ae(B?"dark":"light")})}catch{le.addListener(({matches:W})=>{try{ae(W?"dark":"light")}catch(A){console.error(A)}})}},[f]),ve.useEffect(()=>{T.length<=1&&$(!1)},[T]),ve.useEffect(()=>{const le=B=>{var W;if(s.every(P=>B[P]||B.code===P)){var D;$(!0),(D=q.current)==null||D.focus()}B.code==="Escape"&&(document.activeElement===q.current||(W=q.current)!=null&&W.contains(document.activeElement))&&$(!1)};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[s]),ve.useEffect(()=>{if(q.current)return()=>{Q.current&&(Q.current.focus({preventScroll:!0}),Q.current=null,Ie.current=!1)}},[q.current]),ve.createElement("section",{ref:t,"aria-label":`${x} ${z}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},N.map((le,B)=>{var W;const[A,D]=le.split("-");return C.length?ve.createElement("ol",{key:le,dir:S==="auto"?sR():S,tabIndex:-1,ref:q,className:c,"data-sonner-toaster":!0,"data-sonner-theme":re,"data-y-position":A,"data-x-position":D,style:{"--front-toast-height":`${((W=F[0])==null?void 0:W.height)||0}px`,"--width":`${zB}px`,"--gap":`${R}px`,...m,...eK(u,d)},onBlur:P=>{Ie.current&&!P.currentTarget.contains(P.relatedTarget)&&(Ie.current=!1,Q.current&&(Q.current.focus({preventScroll:!0}),Q.current=null))},onFocus:P=>{P.target instanceof HTMLElement&&P.target.dataset.dismissible==="false"||Ie.current||(Ie.current=!0,Q.current=P.relatedTarget)},onMouseEnter:()=>$(!0),onMouseMove:()=>$(!0),onMouseLeave:()=>{X||$(!1)},onDragEnd:()=>$(!1),onPointerDown:P=>{P.target instanceof HTMLElement&&P.target.dataset.dismissible==="false"||oe(!0)},onPointerUp:()=>oe(!1)},C.filter(P=>!P.position&&B===0||P.position===le).map((P,M)=>{var I,j;return ve.createElement(ZB,{key:P.id,icons:k,index:M,toast:P,defaultRichColors:p,duration:(I=y==null?void 0:y.duration)!=null?I:h,className:y==null?void 0:y.className,descriptionClassName:y==null?void 0:y.descriptionClassName,invert:i,visibleToasts:E,closeButton:(j=y==null?void 0:y.closeButton)!=null?j:l,interacting:X,position:le,style:y==null?void 0:y.style,unstyled:y==null?void 0:y.unstyled,classNames:y==null?void 0:y.classNames,cancelButtonStyle:y==null?void 0:y.cancelButtonStyle,actionButtonStyle:y==null?void 0:y.actionButtonStyle,closeButtonAriaLabel:y==null?void 0:y.closeButtonAriaLabel,removeToast:Y,toasts:C.filter(U=>U.position==P.position),heights:F.filter(U=>U.position==P.position),setHeights:H,expandByDefault:a,gap:R,expanded:ie,swipeDirections:e.swipeDirections})})):null}))});/**
68
- * @license lucide-react v1.14.0 - ISC
69
- *
70
- * This source code is licensed under the ISC license.
71
- * See the LICENSE file in the root directory of this source tree.
72
- */const iM=(...r)=>r.filter((e,t,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===t).join(" ").trim();/**
73
- * @license lucide-react v1.14.0 - ISC
74
- *
75
- * This source code is licensed under the ISC license.
76
- * See the LICENSE file in the root directory of this source tree.
77
- */const rK=r=>r.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
78
- * @license lucide-react v1.14.0 - ISC
79
- *
80
- * This source code is licensed under the ISC license.
81
- * See the LICENSE file in the root directory of this source tree.
82
- */const nK=r=>r.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase());/**
83
- * @license lucide-react v1.14.0 - ISC
84
- *
85
- * This source code is licensed under the ISC license.
86
- * See the LICENSE file in the root directory of this source tree.
87
- */const aR=r=>{const e=nK(r);return e.charAt(0).toUpperCase()+e.slice(1)};/**
88
- * @license lucide-react v1.14.0 - ISC
89
- *
90
- * This source code is licensed under the ISC license.
91
- * See the LICENSE file in the root directory of this source tree.
92
- */var Og={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
93
- * @license lucide-react v1.14.0 - ISC
94
- *
95
- * This source code is licensed under the ISC license.
96
- * See the LICENSE file in the root directory of this source tree.
97
- */const iK=r=>{for(const e in r)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},oK=_.createContext({}),sK=()=>_.useContext(oK),aK=_.forwardRef(({color:r,size:e,strokeWidth:t,absoluteStrokeWidth:n,className:i="",children:o,iconNode:s,...a},l)=>{const{size:c=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:f="currentColor",className:p=""}=sK()??{},h=n??d?Number(t??u)*24/Number(e??c):t??u;return _.createElement("svg",{ref:l,...Og,width:e??c??Og.width,height:e??c??Og.height,stroke:r??f,strokeWidth:h,className:iM("lucide",p,i),...!o&&!iK(a)&&{"aria-hidden":"true"},...a},[...s.map(([m,E])=>_.createElement(m,E)),...Array.isArray(o)?o:[o]])});/**
98
- * @license lucide-react v1.14.0 - ISC
99
- *
100
- * This source code is licensed under the ISC license.
101
- * See the LICENSE file in the root directory of this source tree.
102
- */const xt=(r,e)=>{const t=_.forwardRef(({className:n,...i},o)=>_.createElement(aK,{ref:o,iconNode:e,className:iM(`lucide-${rK(aR(r))}`,`lucide-${r}`,n),...i}));return t.displayName=aR(r),t};/**
103
- * @license lucide-react v1.14.0 - ISC
104
- *
105
- * This source code is licensed under the ISC license.
106
- * See the LICENSE file in the root directory of this source tree.
107
- */const lK=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],cK=xt("arrow-left",lK);/**
108
- * @license lucide-react v1.14.0 - ISC
109
- *
110
- * This source code is licensed under the ISC license.
111
- * See the LICENSE file in the root directory of this source tree.
112
- */const uK=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],FE=xt("check",uK);/**
113
- * @license lucide-react v1.14.0 - ISC
114
- *
115
- * This source code is licensed under the ISC license.
116
- * See the LICENSE file in the root directory of this source tree.
117
- */const dK=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],oM=xt("chevron-down",dK);/**
118
- * @license lucide-react v1.14.0 - ISC
119
- *
120
- * This source code is licensed under the ISC license.
121
- * See the LICENSE file in the root directory of this source tree.
122
- */const fK=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],sM=xt("chevron-right",fK);/**
123
- * @license lucide-react v1.14.0 - ISC
124
- *
125
- * This source code is licensed under the ISC license.
126
- * See the LICENSE file in the root directory of this source tree.
127
- */const hK=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],pK=xt("chevrons-up-down",hK);/**
128
- * @license lucide-react v1.14.0 - ISC
129
- *
130
- * This source code is licensed under the ISC license.
131
- * See the LICENSE file in the root directory of this source tree.
132
- */const vK=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],mK=xt("circle-check",vK);/**
133
- * @license lucide-react v1.14.0 - ISC
134
- *
135
- * This source code is licensed under the ISC license.
136
- * See the LICENSE file in the root directory of this source tree.
137
- */const gK=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],yK=xt("compass",gK);/**
138
- * @license lucide-react v1.14.0 - ISC
139
- *
140
- * This source code is licensed under the ISC license.
141
- * See the LICENSE file in the root directory of this source tree.
142
- */const SK=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],bK=xt("ellipsis",SK);/**
143
- * @license lucide-react v1.14.0 - ISC
144
- *
145
- * This source code is licensed under the ISC license.
146
- * See the LICENSE file in the root directory of this source tree.
147
- */const _K=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],EK=xt("file-pen",_K);/**
148
- * @license lucide-react v1.14.0 - ISC
149
- *
150
- * This source code is licensed under the ISC license.
151
- * See the LICENSE file in the root directory of this source tree.
152
- */const wK=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"11.5",cy:"14.5",r:"2.5",key:"1bq0ko"}],["path",{d:"M13.3 16.3 15 18",key:"2quom7"}]],TK=xt("file-search",wK);/**
153
- * @license lucide-react v1.14.0 - ISC
154
- *
155
- * This source code is licensed under the ISC license.
156
- * See the LICENSE file in the root directory of this source tree.
157
- */const RK=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],CK=xt("globe",RK);/**
158
- * @license lucide-react v1.14.0 - ISC
159
- *
160
- * This source code is licensed under the ISC license.
161
- * See the LICENSE file in the root directory of this source tree.
162
- */const kK=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],IK=xt("info",kK);/**
163
- * @license lucide-react v1.14.0 - ISC
164
- *
165
- * This source code is licensed under the ISC license.
166
- * See the LICENSE file in the root directory of this source tree.
167
- */const xK=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]],OK=xt("list-checks",xK);/**
168
- * @license lucide-react v1.14.0 - ISC
169
- *
170
- * This source code is licensed under the ISC license.
171
- * See the LICENSE file in the root directory of this source tree.
172
- */const PK=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Hv=xt("loader-circle",PK);/**
173
- * @license lucide-react v1.14.0 - ISC
174
- *
175
- * This source code is licensed under the ISC license.
176
- * See the LICENSE file in the root directory of this source tree.
177
- */const MK=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],aM=xt("message-square",MK);/**
178
- * @license lucide-react v1.14.0 - ISC
179
- *
180
- * This source code is licensed under the ISC license.
181
- * See the LICENSE file in the root directory of this source tree.
182
- */const AK=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],DK=xt("octagon-x",AK);/**
183
- * @license lucide-react v1.14.0 - ISC
184
- *
185
- * This source code is licensed under the ISC license.
186
- * See the LICENSE file in the root directory of this source tree.
187
- */const NK=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],lM=xt("panel-left",NK);/**
188
- * @license lucide-react v1.14.0 - ISC
189
- *
190
- * This source code is licensed under the ISC license.
191
- * See the LICENSE file in the root directory of this source tree.
192
- */const LK=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],lR=xt("plus",LK);/**
193
- * @license lucide-react v1.14.0 - ISC
194
- *
195
- * This source code is licensed under the ISC license.
196
- * See the LICENSE file in the root directory of this source tree.
197
- */const UK=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],jK=xt("search",UK);/**
198
- * @license lucide-react v1.14.0 - ISC
199
- *
200
- * This source code is licensed under the ISC license.
201
- * See the LICENSE file in the root directory of this source tree.
202
- */const FK=[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]],BK=xt("send-horizontal",FK);/**
203
- * @license lucide-react v1.14.0 - ISC
204
- *
205
- * This source code is licensed under the ISC license.
206
- * See the LICENSE file in the root directory of this source tree.
207
- */const KK=[["path",{d:"M22 11v1a10 10 0 1 1-9-10",key:"ew0xw9"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}],["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}]],VK=xt("smile-plus",KK);/**
208
- * @license lucide-react v1.14.0 - ISC
209
- *
210
- * This source code is licensed under the ISC license.
211
- * See the LICENSE file in the root directory of this source tree.
212
- */const $K=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],WK=xt("star",$K);/**
213
- * @license lucide-react v1.14.0 - ISC
214
- *
215
- * This source code is licensed under the ISC license.
216
- * See the LICENSE file in the root directory of this source tree.
217
- */const qK=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],cR=xt("terminal",qK);/**
218
- * @license lucide-react v1.14.0 - ISC
219
- *
220
- * This source code is licensed under the ISC license.
221
- * See the LICENSE file in the root directory of this source tree.
222
- */const GK=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],zv=xt("triangle-alert",GK);/**
223
- * @license lucide-react v1.14.0 - ISC
224
- *
225
- * This source code is licensed under the ISC license.
226
- * See the LICENSE file in the root directory of this source tree.
227
- */const HK=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],BE=xt("x",HK),uR=({...r})=>{const{theme:e="system"}=IB();return g.jsx(tK,{theme:e,className:"toaster group",icons:{success:g.jsx(mK,{className:"size-4"}),info:g.jsx(IK,{className:"size-4"}),warning:g.jsx(zv,{className:"size-4"}),error:g.jsx(DK,{className:"size-4"}),loading:g.jsx(Hv,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},toastOptions:{classNames:{toast:"cn-toast"}},...r})};function dR(r,e){if(typeof r=="function")return r(e);r!=null&&(r.current=e)}function Do(...r){return e=>{let t=!1;const n=r.map(i=>{const o=dR(i,e);return!t&&typeof o=="function"&&(t=!0),o});if(t)return()=>{for(let i=0;i<n.length;i++){const o=n[i];typeof o=="function"?o():dR(r[i],null)}}}}function _t(...r){return _.useCallback(Do(...r),r)}function La(r){const e=YK(r),t=_.forwardRef((n,i)=>{const{children:o,...s}=n,a=_.Children.toArray(o),l=a.find(XK);if(l){const c=l.props.children,u=a.map(d=>d===l?_.Children.count(c)>1?_.Children.only(null):_.isValidElement(c)?c.props.children:null:d);return g.jsx(e,{...s,ref:i,children:_.isValidElement(c)?_.cloneElement(c,void 0,u):null})}return g.jsx(e,{...s,ref:i,children:o})});return t.displayName=`${r}.Slot`,t}var zK=La("Slot");function YK(r){const e=_.forwardRef((t,n)=>{const{children:i,...o}=t;if(_.isValidElement(i)){const s=ZK(i),a=QK(o,i.props);return i.type!==_.Fragment&&(a.ref=n?Do(n,s):s),_.cloneElement(i,a)}return _.Children.count(i)>1?_.Children.only(null):null});return e.displayName=`${r}.SlotClone`,e}var cM=Symbol("radix.slottable");function JK(r){const e=({children:t})=>g.jsx(g.Fragment,{children:t});return e.displayName=`${r}.Slottable`,e.__radixId=cM,e}function XK(r){return _.isValidElement(r)&&typeof r.type=="function"&&"__radixId"in r.type&&r.type.__radixId===cM}function QK(r,e){const t={...e};for(const n in e){const i=r[n],o=e[n];/^on[A-Z]/.test(n)?i&&o?t[n]=(...a)=>{const l=o(...a);return i(...a),l}:i&&(t[n]=i):n==="style"?t[n]={...i,...o}:n==="className"&&(t[n]=[i,o].filter(Boolean).join(" "))}return{...r,...t}}function ZK(r){var n,i;let e=(n=Object.getOwnPropertyDescriptor(r.props,"ref"))==null?void 0:n.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?r.ref:(e=(i=Object.getOwnPropertyDescriptor(r,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?r.props.ref:r.props.ref||r.ref)}var e5=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Je=e5.reduce((r,e)=>{const t=La(`Primitive.${e}`),n=_.forwardRef((i,o)=>{const{asChild:s,...a}=i,l=s?t:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),g.jsx(l,{...a,ref:o})});return n.displayName=`Primitive.${e}`,{...r,[e]:n}},{});function uM(r,e){r&&Wv.flushSync(()=>r.dispatchEvent(e))}var t5=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"}),r5="VisuallyHidden",dM=_.forwardRef((r,e)=>g.jsx(Je.span,{...r,ref:e,style:{...t5,...r.style}}));dM.displayName=r5;var n5=dM;function i5(r,e){const t=_.createContext(e),n=o=>{const{children:s,...a}=o,l=_.useMemo(()=>a,Object.values(a));return g.jsx(t.Provider,{value:l,children:s})};n.displayName=r+"Provider";function i(o){const s=_.useContext(t);if(s)return s;if(e!==void 0)return e;throw new Error(`\`${o}\` must be used within \`${r}\``)}return[n,i]}function ro(r,e=[]){let t=[];function n(o,s){const a=_.createContext(s),l=t.length;t=[...t,s];const c=d=>{var y;const{scope:f,children:p,...h}=d,m=((y=f==null?void 0:f[r])==null?void 0:y[l])||a,E=_.useMemo(()=>h,Object.values(h));return g.jsx(m.Provider,{value:E,children:p})};c.displayName=o+"Provider";function u(d,f){var m;const p=((m=f==null?void 0:f[r])==null?void 0:m[l])||a,h=_.useContext(p);if(h)return h;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[c,u]}const i=()=>{const o=t.map(s=>_.createContext(s));return function(a){const l=(a==null?void 0:a[r])||o;return _.useMemo(()=>({[`__scope${r}`]:{...a,[r]:l}}),[a,l])}};return i.scopeName=r,[n,o5(i,...e)]}function o5(...r){const e=r[0];if(r.length===1)return e;const t=()=>{const n=r.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(o){const s=n.reduce((a,{useScope:l,scopeName:c})=>{const d=l(o)[`__scope${c}`];return{...a,...d}},{});return _.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return t.scopeName=e.scopeName,t}function fM(r){const e=r+"CollectionProvider",[t,n]=ro(e),[i,o]=t(e,{collectionRef:{current:null},itemMap:new Map}),s=m=>{const{scope:E,children:y}=m,S=ve.useRef(null),R=ve.useRef(new Map).current;return g.jsx(i,{scope:E,itemMap:R,collectionRef:S,children:y})};s.displayName=e;const a=r+"CollectionSlot",l=La(a),c=ve.forwardRef((m,E)=>{const{scope:y,children:S}=m,R=o(a,y),k=_t(E,R.collectionRef);return g.jsx(l,{ref:k,children:S})});c.displayName=a;const u=r+"CollectionItemSlot",d="data-radix-collection-item",f=La(u),p=ve.forwardRef((m,E)=>{const{scope:y,children:S,...R}=m,k=ve.useRef(null),x=_t(E,k),T=o(u,y);return ve.useEffect(()=>(T.itemMap.set(k,{ref:k,...R}),()=>void T.itemMap.delete(k))),g.jsx(f,{[d]:"",ref:x,children:S})});p.displayName=u;function h(m){const E=o(r+"CollectionConsumer",m);return ve.useCallback(()=>{const S=E.collectionRef.current;if(!S)return[];const R=Array.from(S.querySelectorAll(`[${d}]`));return Array.from(E.itemMap.values()).sort((T,O)=>R.indexOf(T.ref.current)-R.indexOf(O.ref.current))},[E.collectionRef,E.itemMap])}return[{Provider:s,Slot:c,ItemSlot:p},h,n]}function Ae(r,e,{checkForDefaultPrevented:t=!0}={}){return function(i){if(r==null||r(i),t===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}var Zn=globalThis!=null&&globalThis.document?_.useLayoutEffect:()=>{},s5=Iv[" useInsertionEffect ".trim().toString()]||Zn;function af({prop:r,defaultProp:e,onChange:t=()=>{},caller:n}){const[i,o,s]=a5({defaultProp:e,onChange:t}),a=r!==void 0,l=a?r:i;{const u=_.useRef(r!==void 0);_.useEffect(()=>{const d=u.current;d!==a&&console.warn(`${n} is changing from ${d?"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.`),u.current=a},[a,n])}const c=_.useCallback(u=>{var d;if(a){const f=l5(u)?u(r):u;f!==r&&((d=s.current)==null||d.call(s,f))}else o(u)},[a,r,o,s]);return[l,c]}function a5({defaultProp:r,onChange:e}){const[t,n]=_.useState(r),i=_.useRef(t),o=_.useRef(e);return s5(()=>{o.current=e},[e]),_.useEffect(()=>{var s;i.current!==t&&((s=o.current)==null||s.call(o,t),i.current=t)},[t,i]),[t,n,o]}function l5(r){return typeof r=="function"}function c5(r,e){return _.useReducer((t,n)=>e[t][n]??t,r)}var Gr=r=>{const{present:e,children:t}=r,n=u5(e),i=typeof t=="function"?t({present:n.isPresent}):_.Children.only(t),o=_t(n.ref,d5(i));return typeof t=="function"||n.isPresent?_.cloneElement(i,{ref:o}):null};Gr.displayName="Presence";function u5(r){const[e,t]=_.useState(),n=_.useRef(null),i=_.useRef(r),o=_.useRef("none"),s=r?"mounted":"unmounted",[a,l]=c5(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return _.useEffect(()=>{const c=ih(n.current);o.current=a==="mounted"?c:"none"},[a]),Zn(()=>{const c=n.current,u=i.current;if(u!==r){const f=o.current,p=ih(c);r?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),i.current=r}},[r,l]),Zn(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,d=p=>{const m=ih(n.current).includes(CSS.escape(p.animationName));if(p.target===e&&m&&(l("ANIMATION_END"),!i.current)){const E=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=E)})}},f=p=>{p.target===e&&(o.current=ih(n.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:_.useCallback(c=>{n.current=c?getComputedStyle(c):null,t(c)},[])}}function ih(r){return(r==null?void 0:r.animationName)||"none"}function d5(r){var n,i;let e=(n=Object.getOwnPropertyDescriptor(r.props,"ref"))==null?void 0:n.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?r.ref:(e=(i=Object.getOwnPropertyDescriptor(r,"ref"))==null?void 0:i.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?r.props.ref:r.props.ref||r.ref)}var f5=Iv[" useId ".trim().toString()]||(()=>{}),h5=0;function Tn(r){const[e,t]=_.useState(f5());return Zn(()=>{t(n=>n??String(h5++))},[r]),r||(e?`radix-${e}`:"")}var p5=_.createContext(void 0);function KE(r){const e=_.useContext(p5);return r||e||"ltr"}function Pr(r){const e=_.useRef(r);return _.useEffect(()=>{e.current=r}),_.useMemo(()=>(...t)=>{var n;return(n=e.current)==null?void 0:n.call(e,...t)},[])}function v5(r,e=globalThis==null?void 0:globalThis.document){const t=Pr(r);_.useEffect(()=>{const n=i=>{i.key==="Escape"&&t(i)};return e.addEventListener("keydown",n,{capture:!0}),()=>e.removeEventListener("keydown",n,{capture:!0})},[t,e])}var m5="DismissableLayer",WS="dismissableLayer.update",g5="dismissableLayer.pointerDownOutside",y5="dismissableLayer.focusOutside",fR,hM=_.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),lf=_.forwardRef((r,e)=>{const{disableOutsidePointerEvents:t=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:s,onDismiss:a,...l}=r,c=_.useContext(hM),[u,d]=_.useState(null),f=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=_.useState({}),h=_t(e,O=>d(O)),m=Array.from(c.layers),[E]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(E),S=u?m.indexOf(u):-1,R=c.layersWithOutsidePointerEventsDisabled.size>0,k=S>=y,x=_5(O=>{const C=O.target,N=[...c.branches].some(F=>F.contains(C));!k||N||(i==null||i(O),s==null||s(O),O.defaultPrevented||a==null||a())},f),T=E5(O=>{const C=O.target;[...c.branches].some(F=>F.contains(C))||(o==null||o(O),s==null||s(O),O.defaultPrevented||a==null||a())},f);return v5(O=>{S===c.layers.size-1&&(n==null||n(O),!O.defaultPrevented&&a&&(O.preventDefault(),a()))},f),_.useEffect(()=>{if(u)return t&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(fR=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),hR(),()=>{t&&c.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=fR)}},[u,f,t,c]),_.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),hR())},[u,c]),_.useEffect(()=>{const O=()=>p({});return document.addEventListener(WS,O),()=>document.removeEventListener(WS,O)},[]),g.jsx(Je.div,{...l,ref:h,style:{pointerEvents:R?k?"auto":"none":void 0,...r.style},onFocusCapture:Ae(r.onFocusCapture,T.onFocusCapture),onBlurCapture:Ae(r.onBlurCapture,T.onBlurCapture),onPointerDownCapture:Ae(r.onPointerDownCapture,x.onPointerDownCapture)})});lf.displayName=m5;var S5="DismissableLayerBranch",b5=_.forwardRef((r,e)=>{const t=_.useContext(hM),n=_.useRef(null),i=_t(e,n);return _.useEffect(()=>{const o=n.current;if(o)return t.branches.add(o),()=>{t.branches.delete(o)}},[t.branches]),g.jsx(Je.div,{...r,ref:i})});b5.displayName=S5;function _5(r,e=globalThis==null?void 0:globalThis.document){const t=Pr(r),n=_.useRef(!1),i=_.useRef(()=>{});return _.useEffect(()=>{const o=a=>{if(a.target&&!n.current){let l=function(){pM(g5,t,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",i.current),i.current=l,e.addEventListener("click",i.current,{once:!0})):l()}else e.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{e.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(s),e.removeEventListener("pointerdown",o),e.removeEventListener("click",i.current)}},[e,t]),{onPointerDownCapture:()=>n.current=!0}}function E5(r,e=globalThis==null?void 0:globalThis.document){const t=Pr(r),n=_.useRef(!1);return _.useEffect(()=>{const i=o=>{o.target&&!n.current&&pM(y5,t,{originalEvent:o},{discrete:!1})};return e.addEventListener("focusin",i),()=>e.removeEventListener("focusin",i)},[e,t]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function hR(){const r=new CustomEvent(WS);document.dispatchEvent(r)}function pM(r,e,t,{discrete:n}){const i=t.originalEvent.target,o=new CustomEvent(r,{bubbles:!1,cancelable:!0,detail:t});e&&i.addEventListener(r,e,{once:!0}),n?uM(i,o):i.dispatchEvent(o)}var Pg="focusScope.autoFocusOnMount",Mg="focusScope.autoFocusOnUnmount",pR={bubbles:!1,cancelable:!0},w5="FocusScope",Yv=_.forwardRef((r,e)=>{const{loop:t=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...s}=r,[a,l]=_.useState(null),c=Pr(i),u=Pr(o),d=_.useRef(null),f=_t(e,m=>l(m)),p=_.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;_.useEffect(()=>{if(n){let m=function(R){if(p.paused||!a)return;const k=R.target;a.contains(k)?d.current=k:Zo(d.current,{select:!0})},E=function(R){if(p.paused||!a)return;const k=R.relatedTarget;k!==null&&(a.contains(k)||Zo(d.current,{select:!0}))},y=function(R){if(document.activeElement===document.body)for(const x of R)x.removedNodes.length>0&&Zo(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",E);const S=new MutationObserver(y);return a&&S.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",E),S.disconnect()}}},[n,a,p.paused]),_.useEffect(()=>{if(a){mR.add(p);const m=document.activeElement;if(!a.contains(m)){const y=new CustomEvent(Pg,pR);a.addEventListener(Pg,c),a.dispatchEvent(y),y.defaultPrevented||(T5(x5(vM(a)),{select:!0}),document.activeElement===m&&Zo(a))}return()=>{a.removeEventListener(Pg,c),setTimeout(()=>{const y=new CustomEvent(Mg,pR);a.addEventListener(Mg,u),a.dispatchEvent(y),y.defaultPrevented||Zo(m??document.body,{select:!0}),a.removeEventListener(Mg,u),mR.remove(p)},0)}}},[a,c,u,p]);const h=_.useCallback(m=>{if(!t&&!n||p.paused)return;const E=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,y=document.activeElement;if(E&&y){const S=m.currentTarget,[R,k]=R5(S);R&&k?!m.shiftKey&&y===k?(m.preventDefault(),t&&Zo(R,{select:!0})):m.shiftKey&&y===R&&(m.preventDefault(),t&&Zo(k,{select:!0})):y===S&&m.preventDefault()}},[t,n,p.paused]);return g.jsx(Je.div,{tabIndex:-1,...s,ref:f,onKeyDown:h})});Yv.displayName=w5;function T5(r,{select:e=!1}={}){const t=document.activeElement;for(const n of r)if(Zo(n,{select:e}),document.activeElement!==t)return}function R5(r){const e=vM(r),t=vR(e,r),n=vR(e.reverse(),r);return[t,n]}function vM(r){const e=[],t=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const i=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||i?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)e.push(t.currentNode);return e}function vR(r,e){for(const t of r)if(!C5(t,{upTo:e}))return t}function C5(r,{upTo:e}){if(getComputedStyle(r).visibility==="hidden")return!0;for(;r;){if(e!==void 0&&r===e)return!1;if(getComputedStyle(r).display==="none")return!0;r=r.parentElement}return!1}function k5(r){return r instanceof HTMLInputElement&&"select"in r}function Zo(r,{select:e=!1}={}){if(r&&r.focus){const t=document.activeElement;r.focus({preventScroll:!0}),r!==t&&k5(r)&&e&&r.select()}}var mR=I5();function I5(){let r=[];return{add(e){const t=r[0];e!==t&&(t==null||t.pause()),r=gR(r,e),r.unshift(e)},remove(e){var t;r=gR(r,e),(t=r[0])==null||t.resume()}}}function gR(r,e){const t=[...r],n=t.indexOf(e);return n!==-1&&t.splice(n,1),t}function x5(r){return r.filter(e=>e.tagName!=="A")}var O5="Portal",cf=_.forwardRef((r,e)=>{var a;const{container:t,...n}=r,[i,o]=_.useState(!1);Zn(()=>o(!0),[]);const s=t||i&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return s?BP.createPortal(g.jsx(Je.div,{...n,ref:e}),s):null});cf.displayName=O5;var Ag=0;function VE(){_.useEffect(()=>{const r=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",r[0]??yR()),document.body.insertAdjacentElement("beforeend",r[1]??yR()),Ag++,()=>{Ag===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Ag--}},[])}function yR(){const r=document.createElement("span");return r.setAttribute("data-radix-focus-guard",""),r.tabIndex=0,r.style.outline="none",r.style.opacity="0",r.style.position="fixed",r.style.pointerEvents="none",r}var Gi=function(){return Gi=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++){t=arguments[n];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},Gi.apply(this,arguments)};function mM(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t}function P5(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,o;n<i;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))}var Hh="right-scroll-bar-position",zh="width-before-scroll-bar",M5="with-scroll-bars-hidden",A5="--removed-body-scroll-bar-size";function Dg(r,e){return typeof r=="function"?r(e):r&&(r.current=e),r}function D5(r,e){var t=_.useState(function(){return{value:r,callback:e,facade:{get current(){return t.value},set current(n){var i=t.value;i!==n&&(t.value=n,t.callback(n,i))}}}})[0];return t.callback=e,t.facade}var N5=typeof window<"u"?_.useLayoutEffect:_.useEffect,SR=new WeakMap;function L5(r,e){var t=D5(null,function(n){return r.forEach(function(i){return Dg(i,n)})});return N5(function(){var n=SR.get(t);if(n){var i=new Set(n),o=new Set(r),s=t.current;i.forEach(function(a){o.has(a)||Dg(a,null)}),o.forEach(function(a){i.has(a)||Dg(a,s)})}SR.set(t,r)},[r]),t}function U5(r){return r}function j5(r,e){e===void 0&&(e=U5);var t=[],n=!1,i={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return t.length?t[t.length-1]:r},useMedium:function(o){var s=e(o,n);return t.push(s),function(){t=t.filter(function(a){return a!==s})}},assignSyncMedium:function(o){for(n=!0;t.length;){var s=t;t=[],s.forEach(o)}t={push:function(a){return o(a)},filter:function(){return t}}},assignMedium:function(o){n=!0;var s=[];if(t.length){var a=t;t=[],a.forEach(o),s=t}var l=function(){var u=s;s=[],u.forEach(o)},c=function(){return Promise.resolve().then(l)};c(),t={push:function(u){s.push(u),c()},filter:function(u){return s=s.filter(u),t}}}};return i}function F5(r){r===void 0&&(r={});var e=j5(null);return e.options=Gi({async:!0,ssr:!1},r),e}var gM=function(r){var e=r.sideCar,t=mM(r,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=e.read();if(!n)throw new Error("Sidecar medium not found");return _.createElement(n,Gi({},t))};gM.isSideCarExport=!0;function B5(r,e){return r.useMedium(e),gM}var yM=F5(),Ng=function(){},Jv=_.forwardRef(function(r,e){var t=_.useRef(null),n=_.useState({onScrollCapture:Ng,onWheelCapture:Ng,onTouchMoveCapture:Ng}),i=n[0],o=n[1],s=r.forwardProps,a=r.children,l=r.className,c=r.removeScrollBar,u=r.enabled,d=r.shards,f=r.sideCar,p=r.noRelative,h=r.noIsolation,m=r.inert,E=r.allowPinchZoom,y=r.as,S=y===void 0?"div":y,R=r.gapMode,k=mM(r,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),x=f,T=L5([t,e]),O=Gi(Gi({},k),i);return _.createElement(_.Fragment,null,u&&_.createElement(x,{sideCar:yM,removeScrollBar:c,shards:d,noRelative:p,noIsolation:h,inert:m,setCallbacks:o,allowPinchZoom:!!E,lockRef:t,gapMode:R}),s?_.cloneElement(_.Children.only(a),Gi(Gi({},O),{ref:T})):_.createElement(S,Gi({},O,{className:l,ref:T}),a))});Jv.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Jv.classNames={fullWidth:zh,zeroRight:Hh};var K5=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function V5(){if(!document)return null;var r=document.createElement("style");r.type="text/css";var e=K5();return e&&r.setAttribute("nonce",e),r}function $5(r,e){r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}function W5(r){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(r)}var q5=function(){var r=0,e=null;return{add:function(t){r==0&&(e=V5())&&($5(e,t),W5(e)),r++},remove:function(){r--,!r&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},G5=function(){var r=q5();return function(e,t){_.useEffect(function(){return r.add(e),function(){r.remove()}},[e&&t])}},SM=function(){var r=G5(),e=function(t){var n=t.styles,i=t.dynamic;return r(n,i),null};return e},H5={left:0,top:0,right:0,gap:0},Lg=function(r){return parseInt(r||"",10)||0},z5=function(r){var e=window.getComputedStyle(document.body),t=e[r==="padding"?"paddingLeft":"marginLeft"],n=e[r==="padding"?"paddingTop":"marginTop"],i=e[r==="padding"?"paddingRight":"marginRight"];return[Lg(t),Lg(n),Lg(i)]},Y5=function(r){if(r===void 0&&(r="margin"),typeof window>"u")return H5;var e=z5(r),t=document.documentElement.clientWidth,n=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,n-t+e[2]-e[0])}},J5=SM(),zl="data-scroll-locked",X5=function(r,e,t,n){var i=r.left,o=r.top,s=r.right,a=r.gap;return t===void 0&&(t="margin"),`
228
- .`.concat(M5,` {
229
- overflow: hidden `).concat(n,`;
230
- padding-right: `).concat(a,"px ").concat(n,`;
231
- }
232
- body[`).concat(zl,`] {
233
- overflow: hidden `).concat(n,`;
234
- overscroll-behavior: contain;
235
- `).concat([e&&"position: relative ".concat(n,";"),t==="margin"&&`
236
- padding-left: `.concat(i,`px;
237
- padding-top: `).concat(o,`px;
238
- padding-right: `).concat(s,`px;
239
- margin-left:0;
240
- margin-top:0;
241
- margin-right: `).concat(a,"px ").concat(n,`;
242
- `),t==="padding"&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),`
243
- }
244
-
245
- .`).concat(Hh,` {
246
- right: `).concat(a,"px ").concat(n,`;
247
- }
248
-
249
- .`).concat(zh,` {
250
- margin-right: `).concat(a,"px ").concat(n,`;
251
- }
252
-
253
- .`).concat(Hh," .").concat(Hh,` {
254
- right: 0 `).concat(n,`;
255
- }
256
-
257
- .`).concat(zh," .").concat(zh,` {
258
- margin-right: 0 `).concat(n,`;
259
- }
260
-
261
- body[`).concat(zl,`] {
262
- `).concat(A5,": ").concat(a,`px;
263
- }
264
- `)},bR=function(){var r=parseInt(document.body.getAttribute(zl)||"0",10);return isFinite(r)?r:0},Q5=function(){_.useEffect(function(){return document.body.setAttribute(zl,(bR()+1).toString()),function(){var r=bR()-1;r<=0?document.body.removeAttribute(zl):document.body.setAttribute(zl,r.toString())}},[])},Z5=function(r){var e=r.noRelative,t=r.noImportant,n=r.gapMode,i=n===void 0?"margin":n;Q5();var o=_.useMemo(function(){return Y5(i)},[i]);return _.createElement(J5,{styles:X5(o,!e,i,t?"":"!important")})},qS=!1;if(typeof window<"u")try{var oh=Object.defineProperty({},"passive",{get:function(){return qS=!0,!0}});window.addEventListener("test",oh,oh),window.removeEventListener("test",oh,oh)}catch{qS=!1}var ol=qS?{passive:!1}:!1,e3=function(r){return r.tagName==="TEXTAREA"},bM=function(r,e){if(!(r instanceof Element))return!1;var t=window.getComputedStyle(r);return t[e]!=="hidden"&&!(t.overflowY===t.overflowX&&!e3(r)&&t[e]==="visible")},t3=function(r){return bM(r,"overflowY")},r3=function(r){return bM(r,"overflowX")},_R=function(r,e){var t=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=_M(r,n);if(i){var o=EM(r,n),s=o[1],a=o[2];if(s>a)return!0}n=n.parentNode}while(n&&n!==t.body);return!1},n3=function(r){var e=r.scrollTop,t=r.scrollHeight,n=r.clientHeight;return[e,t,n]},i3=function(r){var e=r.scrollLeft,t=r.scrollWidth,n=r.clientWidth;return[e,t,n]},_M=function(r,e){return r==="v"?t3(e):r3(e)},EM=function(r,e){return r==="v"?n3(e):i3(e)},o3=function(r,e){return r==="h"&&e==="rtl"?-1:1},s3=function(r,e,t,n,i){var o=o3(r,window.getComputedStyle(e).direction),s=o*n,a=t.target,l=e.contains(a),c=!1,u=s>0,d=0,f=0;do{if(!a)break;var p=EM(r,a),h=p[0],m=p[1],E=p[2],y=m-E-o*h;(h||y)&&_M(r,a)&&(d+=y,f+=h);var S=a.parentNode;a=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!l&&a!==document.body||l&&(e.contains(a)||e===a));return(u&&Math.abs(d)<1||!u&&Math.abs(f)<1)&&(c=!0),c},sh=function(r){return"changedTouches"in r?[r.changedTouches[0].clientX,r.changedTouches[0].clientY]:[0,0]},ER=function(r){return[r.deltaX,r.deltaY]},wR=function(r){return r&&"current"in r?r.current:r},a3=function(r,e){return r[0]===e[0]&&r[1]===e[1]},l3=function(r){return`
265
- .block-interactivity-`.concat(r,` {pointer-events: none;}
266
- .allow-interactivity-`).concat(r,` {pointer-events: all;}
267
- `)},c3=0,sl=[];function u3(r){var e=_.useRef([]),t=_.useRef([0,0]),n=_.useRef(),i=_.useState(c3++)[0],o=_.useState(SM)[0],s=_.useRef(r);_.useEffect(function(){s.current=r},[r]),_.useEffect(function(){if(r.inert){document.body.classList.add("block-interactivity-".concat(i));var m=P5([r.lockRef.current],(r.shards||[]).map(wR),!0).filter(Boolean);return m.forEach(function(E){return E.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),m.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(i))})}}},[r.inert,r.lockRef.current,r.shards]);var a=_.useCallback(function(m,E){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!s.current.allowPinchZoom;var y=sh(m),S=t.current,R="deltaX"in m?m.deltaX:S[0]-y[0],k="deltaY"in m?m.deltaY:S[1]-y[1],x,T=m.target,O=Math.abs(R)>Math.abs(k)?"h":"v";if("touches"in m&&O==="h"&&T.type==="range")return!1;var C=window.getSelection(),N=C&&C.anchorNode,F=N?N===T||N.contains(T):!1;if(F)return!1;var H=_R(O,T);if(!H)return!0;if(H?x=O:(x=O==="v"?"h":"v",H=_R(O,T)),!H)return!1;if(!n.current&&"changedTouches"in m&&(R||k)&&(n.current=x),!x)return!0;var ie=n.current||x;return s3(ie,E,m,ie==="h"?R:k)},[]),l=_.useCallback(function(m){var E=m;if(!(!sl.length||sl[sl.length-1]!==o)){var y="deltaY"in E?ER(E):sh(E),S=e.current.filter(function(x){return x.name===E.type&&(x.target===E.target||E.target===x.shadowParent)&&a3(x.delta,y)})[0];if(S&&S.should){E.cancelable&&E.preventDefault();return}if(!S){var R=(s.current.shards||[]).map(wR).filter(Boolean).filter(function(x){return x.contains(E.target)}),k=R.length>0?a(E,R[0]):!s.current.noIsolation;k&&E.cancelable&&E.preventDefault()}}},[]),c=_.useCallback(function(m,E,y,S){var R={name:m,delta:E,target:y,should:S,shadowParent:d3(y)};e.current.push(R),setTimeout(function(){e.current=e.current.filter(function(k){return k!==R})},1)},[]),u=_.useCallback(function(m){t.current=sh(m),n.current=void 0},[]),d=_.useCallback(function(m){c(m.type,ER(m),m.target,a(m,r.lockRef.current))},[]),f=_.useCallback(function(m){c(m.type,sh(m),m.target,a(m,r.lockRef.current))},[]);_.useEffect(function(){return sl.push(o),r.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,ol),document.addEventListener("touchmove",l,ol),document.addEventListener("touchstart",u,ol),function(){sl=sl.filter(function(m){return m!==o}),document.removeEventListener("wheel",l,ol),document.removeEventListener("touchmove",l,ol),document.removeEventListener("touchstart",u,ol)}},[]);var p=r.removeScrollBar,h=r.inert;return _.createElement(_.Fragment,null,h?_.createElement(o,{styles:l3(i)}):null,p?_.createElement(Z5,{noRelative:r.noRelative,gapMode:r.gapMode}):null)}function d3(r){for(var e=null;r!==null;)r instanceof ShadowRoot&&(e=r.host,r=r.host),r=r.parentNode;return e}const f3=B5(yM,u3);var Xv=_.forwardRef(function(r,e){return _.createElement(Jv,Gi({},r,{ref:e,sideCar:f3}))});Xv.classNames=Jv.classNames;var h3=function(r){if(typeof document>"u")return null;var e=Array.isArray(r)?r[0]:r;return e.ownerDocument.body},al=new WeakMap,ah=new WeakMap,lh={},Ug=0,wM=function(r){return r&&(r.host||wM(r.parentNode))},p3=function(r,e){return e.map(function(t){if(r.contains(t))return t;var n=wM(t);return n&&r.contains(n)?n:(console.error("aria-hidden",t,"in not contained inside",r,". Doing nothing"),null)}).filter(function(t){return!!t})},v3=function(r,e,t,n){var i=p3(e,Array.isArray(r)?r:[r]);lh[t]||(lh[t]=new WeakMap);var o=lh[t],s=[],a=new Set,l=new Set(i),c=function(d){!d||a.has(d)||(a.add(d),c(d.parentNode))};i.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(a.has(f))u(f);else try{var p=f.getAttribute(n),h=p!==null&&p!=="false",m=(al.get(f)||0)+1,E=(o.get(f)||0)+1;al.set(f,m),o.set(f,E),s.push(f),m===1&&h&&ah.set(f,!0),E===1&&f.setAttribute(t,"true"),h||f.setAttribute(n,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return u(e),a.clear(),Ug++,function(){s.forEach(function(d){var f=al.get(d)-1,p=o.get(d)-1;al.set(d,f),o.set(d,p),f||(ah.has(d)||d.removeAttribute(n),ah.delete(d)),p||d.removeAttribute(t)}),Ug--,Ug||(al=new WeakMap,al=new WeakMap,ah=new WeakMap,lh={})}},$E=function(r,e,t){t===void 0&&(t="data-aria-hidden");var n=Array.from(Array.isArray(r)?r:[r]),i=h3(r);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live], script"))),v3(n,i,t,"aria-hidden")):function(){return null}},Qv="Dialog",[TM]=ro(Qv),[m3,Ii]=TM(Qv),RM=r=>{const{__scopeDialog:e,children:t,open:n,defaultOpen:i,onOpenChange:o,modal:s=!0}=r,a=_.useRef(null),l=_.useRef(null),[c,u]=af({prop:n,defaultProp:i??!1,onChange:o,caller:Qv});return g.jsx(m3,{scope:e,triggerRef:a,contentRef:l,contentId:Tn(),titleId:Tn(),descriptionId:Tn(),open:c,onOpenChange:u,onOpenToggle:_.useCallback(()=>u(d=>!d),[u]),modal:s,children:t})};RM.displayName=Qv;var CM="DialogTrigger",g3=_.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(CM,t),o=_t(e,i.triggerRef);return g.jsx(Je.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":GE(i.open),...n,ref:o,onClick:Ae(r.onClick,i.onOpenToggle)})});g3.displayName=CM;var WE="DialogPortal",[y3,kM]=TM(WE,{forceMount:void 0}),IM=r=>{const{__scopeDialog:e,forceMount:t,children:n,container:i}=r,o=Ii(WE,e);return g.jsx(y3,{scope:e,forceMount:t,children:_.Children.map(n,s=>g.jsx(Gr,{present:t||o.open,children:g.jsx(cf,{asChild:!0,container:i,children:s})}))})};IM.displayName=WE;var $p="DialogOverlay",xM=_.forwardRef((r,e)=>{const t=kM($p,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,o=Ii($p,r.__scopeDialog);return o.modal?g.jsx(Gr,{present:n||o.open,children:g.jsx(b3,{...i,ref:e})}):null});xM.displayName=$p;var S3=La("DialogOverlay.RemoveScroll"),b3=_.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii($p,t);return g.jsx(Xv,{as:S3,allowPinchZoom:!0,shards:[i.contentRef],children:g.jsx(Je.div,{"data-state":GE(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),Ua="DialogContent",OM=_.forwardRef((r,e)=>{const t=kM(Ua,r.__scopeDialog),{forceMount:n=t.forceMount,...i}=r,o=Ii(Ua,r.__scopeDialog);return g.jsx(Gr,{present:n||o.open,children:o.modal?g.jsx(_3,{...i,ref:e}):g.jsx(E3,{...i,ref:e})})});OM.displayName=Ua;var _3=_.forwardRef((r,e)=>{const t=Ii(Ua,r.__scopeDialog),n=_.useRef(null),i=_t(e,t.contentRef,n);return _.useEffect(()=>{const o=n.current;if(o)return $E(o)},[]),g.jsx(PM,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ae(r.onCloseAutoFocus,o=>{var s;o.preventDefault(),(s=t.triggerRef.current)==null||s.focus()}),onPointerDownOutside:Ae(r.onPointerDownOutside,o=>{const s=o.detail.originalEvent,a=s.button===0&&s.ctrlKey===!0;(s.button===2||a)&&o.preventDefault()}),onFocusOutside:Ae(r.onFocusOutside,o=>o.preventDefault())})}),E3=_.forwardRef((r,e)=>{const t=Ii(Ua,r.__scopeDialog),n=_.useRef(!1),i=_.useRef(!1);return g.jsx(PM,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var s,a;(s=r.onCloseAutoFocus)==null||s.call(r,o),o.defaultPrevented||(n.current||(a=t.triggerRef.current)==null||a.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var l,c;(l=r.onInteractOutside)==null||l.call(r,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;((c=t.triggerRef.current)==null?void 0:c.contains(s))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),PM=_.forwardRef((r,e)=>{const{__scopeDialog:t,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,...s}=r,a=Ii(Ua,t),l=_.useRef(null),c=_t(e,l);return VE(),g.jsxs(g.Fragment,{children:[g.jsx(Yv,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:g.jsx(lf,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":GE(a.open),...s,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),g.jsxs(g.Fragment,{children:[g.jsx(w3,{titleId:a.titleId}),g.jsx(R3,{contentRef:l,descriptionId:a.descriptionId})]})]})}),qE="DialogTitle",MM=_.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(qE,t);return g.jsx(Je.h2,{id:i.titleId,...n,ref:e})});MM.displayName=qE;var AM="DialogDescription",DM=_.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(AM,t);return g.jsx(Je.p,{id:i.descriptionId,...n,ref:e})});DM.displayName=AM;var NM="DialogClose",LM=_.forwardRef((r,e)=>{const{__scopeDialog:t,...n}=r,i=Ii(NM,t);return g.jsx(Je.button,{type:"button",...n,ref:e,onClick:Ae(r.onClick,()=>i.onOpenChange(!1))})});LM.displayName=NM;function GE(r){return r?"open":"closed"}var UM="DialogTitleWarning",[_re,jM]=i5(UM,{contentName:Ua,titleName:qE,docsSlug:"dialog"}),w3=({titleId:r})=>{const e=jM(UM),t=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users.
268
-
269
- If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
270
-
271
- For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return _.useEffect(()=>{r&&(document.getElementById(r)||console.error(t))},[t,r]),null},T3="DialogDescriptionWarning",R3=({contentRef:r,descriptionId:e})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${jM(T3).contentName}}.`;return _.useEffect(()=>{var o;const i=(o=r.current)==null?void 0:o.getAttribute("aria-describedby");e&&i&&(document.getElementById(e)||console.warn(n))},[n,r,e]),null},HE=RM,zE=IM,YE=xM,JE=OM,FM=MM,BM=DM,XE=LM,KM={exports:{}},VM={};/**
272
- * @license React
273
- * use-sync-external-store-shim.production.js
274
- *
275
- * Copyright (c) Meta Platforms, Inc. and affiliates.
276
- *
277
- * This source code is licensed under the MIT license found in the
278
- * LICENSE file in the root directory of this source tree.
279
- */var hc=_;function C3(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var k3=typeof Object.is=="function"?Object.is:C3,I3=hc.useState,x3=hc.useEffect,O3=hc.useLayoutEffect,P3=hc.useDebugValue;function M3(r,e){var t=e(),n=I3({inst:{value:t,getSnapshot:e}}),i=n[0].inst,o=n[1];return O3(function(){i.value=t,i.getSnapshot=e,jg(i)&&o({inst:i})},[r,t,e]),x3(function(){return jg(i)&&o({inst:i}),r(function(){jg(i)&&o({inst:i})})},[r]),P3(t),t}function jg(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!k3(r,t)}catch{return!0}}function A3(r,e){return e()}var D3=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?A3:M3;VM.useSyncExternalStore=hc.useSyncExternalStore!==void 0?hc.useSyncExternalStore:D3;KM.exports=VM;var N3=KM.exports;function L3(){return N3.useSyncExternalStore(U3,()=>!0,()=>!1)}function U3(){return()=>{}}var QE="Avatar",[j3]=ro(QE),[F3,$M]=j3(QE),WM=_.forwardRef((r,e)=>{const{__scopeAvatar:t,...n}=r,[i,o]=_.useState("idle");return g.jsx(F3,{scope:t,imageLoadingStatus:i,onImageLoadingStatusChange:o,children:g.jsx(Je.span,{...n,ref:e})})});WM.displayName=QE;var qM="AvatarImage",B3=_.forwardRef((r,e)=>{const{__scopeAvatar:t,src:n,onLoadingStatusChange:i=()=>{},...o}=r,s=$M(qM,t),a=K3(n,o),l=Pr(c=>{i(c),s.onImageLoadingStatusChange(c)});return Zn(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?g.jsx(Je.img,{...o,ref:e,src:n}):null});B3.displayName=qM;var GM="AvatarFallback",HM=_.forwardRef((r,e)=>{const{__scopeAvatar:t,delayMs:n,...i}=r,o=$M(GM,t),[s,a]=_.useState(n===void 0);return _.useEffect(()=>{if(n!==void 0){const l=window.setTimeout(()=>a(!0),n);return()=>window.clearTimeout(l)}},[n]),s&&o.imageLoadingStatus!=="loaded"?g.jsx(Je.span,{...i,ref:e}):null});HM.displayName=GM;function TR(r,e){return r?e?(r.src!==e&&(r.src=e),r.complete&&r.naturalWidth>0?"loaded":"loading"):"error":"idle"}function K3(r,{referrerPolicy:e,crossOrigin:t}){const n=L3(),i=_.useRef(null),o=n?(i.current||(i.current=new window.Image),i.current):null,[s,a]=_.useState(()=>TR(o,r));return Zn(()=>{a(TR(o,r))},[o,r]),Zn(()=>{const l=d=>()=>{a(d)};if(!o)return;const c=l("loaded"),u=l("error");return o.addEventListener("load",c),o.addEventListener("error",u),e&&(o.referrerPolicy=e),typeof t=="string"&&(o.crossOrigin=t),()=>{o.removeEventListener("load",c),o.removeEventListener("error",u)}},[o,t,e]),s}var V3=WM,$3=HM;function W3(r){const[e,t]=_.useState(void 0);return Zn(()=>{if(r){t({width:r.offsetWidth,height:r.offsetHeight});const n=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let s,a;if("borderBoxSize"in o){const l=o.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=r.offsetWidth,a=r.offsetHeight;t({width:s,height:a})});return n.observe(r,{box:"border-box"}),()=>n.unobserve(r)}else t(void 0)},[r]),e}const q3=["top","right","bottom","left"],Ps=Math.min,Ln=Math.max,Wp=Math.round,ch=Math.floor,Xi=r=>({x:r,y:r}),G3={left:"right",right:"left",bottom:"top",top:"bottom"};function GS(r,e,t){return Ln(r,Ps(e,t))}function No(r,e){return typeof r=="function"?r(e):r}function Lo(r){return r.split("-")[0]}function Dc(r){return r.split("-")[1]}function ZE(r){return r==="x"?"y":"x"}function ew(r){return r==="y"?"height":"width"}function zi(r){const e=r[0];return e==="t"||e==="b"?"y":"x"}function tw(r){return ZE(zi(r))}function H3(r,e,t){t===void 0&&(t=!1);const n=Dc(r),i=tw(r),o=ew(i);let s=i==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(s=qp(s)),[s,qp(s)]}function z3(r){const e=qp(r);return[HS(r),e,HS(e)]}function HS(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}const RR=["left","right"],CR=["right","left"],Y3=["top","bottom"],J3=["bottom","top"];function X3(r,e,t){switch(r){case"top":case"bottom":return t?e?CR:RR:e?RR:CR;case"left":case"right":return e?Y3:J3;default:return[]}}function Q3(r,e,t,n){const i=Dc(r);let o=X3(Lo(r),t==="start",n);return i&&(o=o.map(s=>s+"-"+i),e&&(o=o.concat(o.map(HS)))),o}function qp(r){const e=Lo(r);return G3[e]+r.slice(e.length)}function Z3(r){return{top:0,right:0,bottom:0,left:0,...r}}function zM(r){return typeof r!="number"?Z3(r):{top:r,right:r,bottom:r,left:r}}function Gp(r){const{x:e,y:t,width:n,height:i}=r;return{width:n,height:i,top:t,left:e,right:e+n,bottom:t+i,x:e,y:t}}function kR(r,e,t){let{reference:n,floating:i}=r;const o=zi(e),s=tw(e),a=ew(s),l=Lo(e),c=o==="y",u=n.x+n.width/2-i.width/2,d=n.y+n.height/2-i.height/2,f=n[a]/2-i[a]/2;let p;switch(l){case"top":p={x:u,y:n.y-i.height};break;case"bottom":p={x:u,y:n.y+n.height};break;case"right":p={x:n.x+n.width,y:d};break;case"left":p={x:n.x-i.width,y:d};break;default:p={x:n.x,y:n.y}}switch(Dc(e)){case"start":p[s]-=f*(t&&c?-1:1);break;case"end":p[s]+=f*(t&&c?-1:1);break}return p}async function e4(r,e){var t;e===void 0&&(e={});const{x:n,y:i,platform:o,rects:s,elements:a,strategy:l}=r,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=No(e,r),h=zM(p),E=a[f?d==="floating"?"reference":"floating":d],y=Gp(await o.getClippingRect({element:(t=await(o.isElement==null?void 0:o.isElement(E)))==null||t?E:E.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),S=d==="floating"?{x:n,y:i,width:s.floating.width,height:s.floating.height}:s.reference,R=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),k=await(o.isElement==null?void 0:o.isElement(R))?await(o.getScale==null?void 0:o.getScale(R))||{x:1,y:1}:{x:1,y:1},x=Gp(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:S,offsetParent:R,strategy:l}):S);return{top:(y.top-x.top+h.top)/k.y,bottom:(x.bottom-y.bottom+h.bottom)/k.y,left:(y.left-x.left+h.left)/k.x,right:(x.right-y.right+h.right)/k.x}}const t4=50,r4=async(r,e,t)=>{const{placement:n="bottom",strategy:i="absolute",middleware:o=[],platform:s}=t,a=s.detectOverflow?s:{...s,detectOverflow:e4},l=await(s.isRTL==null?void 0:s.isRTL(e));let c=await s.getElementRects({reference:r,floating:e,strategy:i}),{x:u,y:d}=kR(c,n,l),f=n,p=0;const h={};for(let m=0;m<o.length;m++){const E=o[m];if(!E)continue;const{name:y,fn:S}=E,{x:R,y:k,data:x,reset:T}=await S({x:u,y:d,initialPlacement:n,placement:f,strategy:i,middlewareData:h,rects:c,platform:a,elements:{reference:r,floating:e}});u=R??u,d=k??d,h[y]={...h[y],...x},T&&p<t4&&(p++,typeof T=="object"&&(T.placement&&(f=T.placement),T.rects&&(c=T.rects===!0?await s.getElementRects({reference:r,floating:e,strategy:i}):T.rects),{x:u,y:d}=kR(c,f,l)),m=-1)}return{x:u,y:d,placement:f,strategy:i,middlewareData:h}},n4=r=>({name:"arrow",options:r,async fn(e){const{x:t,y:n,placement:i,rects:o,platform:s,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=No(r,e)||{};if(c==null)return{};const d=zM(u),f={x:t,y:n},p=tw(i),h=ew(p),m=await s.getDimensions(c),E=p==="y",y=E?"top":"left",S=E?"bottom":"right",R=E?"clientHeight":"clientWidth",k=o.reference[h]+o.reference[p]-f[p]-o.floating[h],x=f[p]-o.reference[p],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(c));let O=T?T[R]:0;(!O||!await(s.isElement==null?void 0:s.isElement(T)))&&(O=a.floating[R]||o.floating[h]);const C=k/2-x/2,N=O/2-m[h]/2-1,F=Ps(d[y],N),H=Ps(d[S],N),ie=F,$=O-m[h]-H,X=O/2-m[h]/2+C,oe=GS(ie,X,$),re=!l.arrow&&Dc(i)!=null&&X!==oe&&o.reference[h]/2-(X<ie?F:H)-m[h]/2<0,ae=re?X<ie?X-ie:X-$:0;return{[p]:f[p]+ae,data:{[p]:oe,centerOffset:X-oe-ae,...re&&{alignmentOffset:ae}},reset:re}}}),i4=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;const{placement:i,middlewareData:o,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:h="none",flipAlignment:m=!0,...E}=No(r,e);if((t=o.arrow)!=null&&t.alignmentOffset)return{};const y=Lo(i),S=zi(a),R=Lo(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),x=f||(R||!m?[qp(a)]:z3(a)),T=h!=="none";!f&&T&&x.push(...Q3(a,m,h,k));const O=[a,...x],C=await l.detectOverflow(e,E),N=[];let F=((n=o.flip)==null?void 0:n.overflows)||[];if(u&&N.push(C[y]),d){const X=H3(i,s,k);N.push(C[X[0]],C[X[1]])}if(F=[...F,{placement:i,overflows:N}],!N.every(X=>X<=0)){var H,ie;const X=(((H=o.flip)==null?void 0:H.index)||0)+1,oe=O[X];if(oe&&(!(d==="alignment"?S!==zi(oe):!1)||F.every(q=>zi(q.placement)===S?q.overflows[0]>0:!0)))return{data:{index:X,overflows:F},reset:{placement:oe}};let re=(ie=F.filter(ae=>ae.overflows[0]<=0).sort((ae,q)=>ae.overflows[1]-q.overflows[1])[0])==null?void 0:ie.placement;if(!re)switch(p){case"bestFit":{var $;const ae=($=F.filter(q=>{if(T){const z=zi(q.placement);return z===S||z==="y"}return!0}).map(q=>[q.placement,q.overflows.filter(z=>z>0).reduce((z,Q)=>z+Q,0)]).sort((q,z)=>q[1]-z[1])[0])==null?void 0:$[0];ae&&(re=ae);break}case"initialPlacement":re=a;break}if(i!==re)return{reset:{placement:re}}}return{}}}};function IR(r,e){return{top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function xR(r){return q3.some(e=>r[e]>=0)}const o4=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){const{rects:t,platform:n}=e,{strategy:i="referenceHidden",...o}=No(r,e);switch(i){case"referenceHidden":{const s=await n.detectOverflow(e,{...o,elementContext:"reference"}),a=IR(s,t.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:xR(a)}}}case"escaped":{const s=await n.detectOverflow(e,{...o,altBoundary:!0}),a=IR(s,t.floating);return{data:{escapedOffsets:a,escaped:xR(a)}}}default:return{}}}}},YM=new Set(["left","top"]);async function s4(r,e){const{placement:t,platform:n,elements:i}=r,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),s=Lo(t),a=Dc(t),l=zi(t)==="y",c=YM.has(s)?-1:1,u=o&&l?-1:1,d=No(e,r);let{mainAxis:f,crossAxis:p,alignmentAxis:h}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof h=="number"&&(p=a==="end"?h*-1:h),l?{x:p*u,y:f*c}:{x:f*c,y:p*u}}const a4=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;const{x:i,y:o,placement:s,middlewareData:a}=e,l=await s4(e,r);return s===((t=a.offset)==null?void 0:t.placement)&&(n=a.arrow)!=null&&n.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}},l4=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){const{x:t,y:n,placement:i,platform:o}=e,{mainAxis:s=!0,crossAxis:a=!1,limiter:l={fn:y=>{let{x:S,y:R}=y;return{x:S,y:R}}},...c}=No(r,e),u={x:t,y:n},d=await o.detectOverflow(e,c),f=zi(Lo(i)),p=ZE(f);let h=u[p],m=u[f];if(s){const y=p==="y"?"top":"left",S=p==="y"?"bottom":"right",R=h+d[y],k=h-d[S];h=GS(R,h,k)}if(a){const y=f==="y"?"top":"left",S=f==="y"?"bottom":"right",R=m+d[y],k=m-d[S];m=GS(R,m,k)}const E=l.fn({...e,[p]:h,[f]:m});return{...E,data:{x:E.x-t,y:E.y-n,enabled:{[p]:s,[f]:a}}}}}},c4=function(r){return r===void 0&&(r={}),{options:r,fn(e){const{x:t,y:n,placement:i,rects:o,middlewareData:s}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=No(r,e),u={x:t,y:n},d=zi(i),f=ZE(d);let p=u[f],h=u[d];const m=No(a,e),E=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const R=f==="y"?"height":"width",k=o.reference[f]-o.floating[R]+E.mainAxis,x=o.reference[f]+o.reference[R]-E.mainAxis;p<k?p=k:p>x&&(p=x)}if(c){var y,S;const R=f==="y"?"width":"height",k=YM.has(Lo(i)),x=o.reference[d]-o.floating[R]+(k&&((y=s.offset)==null?void 0:y[d])||0)+(k?0:E.crossAxis),T=o.reference[d]+o.reference[R]+(k?0:((S=s.offset)==null?void 0:S[d])||0)-(k?E.crossAxis:0);h<x?h=x:h>T&&(h=T)}return{[f]:p,[d]:h}}}},u4=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){var t,n;const{placement:i,rects:o,platform:s,elements:a}=e,{apply:l=()=>{},...c}=No(r,e),u=await s.detectOverflow(e,c),d=Lo(i),f=Dc(i),p=zi(i)==="y",{width:h,height:m}=o.floating;let E,y;d==="top"||d==="bottom"?(E=d,y=f===(await(s.isRTL==null?void 0:s.isRTL(a.floating))?"start":"end")?"left":"right"):(y=d,E=f==="end"?"top":"bottom");const S=m-u.top-u.bottom,R=h-u.left-u.right,k=Ps(m-u[E],S),x=Ps(h-u[y],R),T=!e.middlewareData.shift;let O=k,C=x;if((t=e.middlewareData.shift)!=null&&t.enabled.x&&(C=R),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(O=S),T&&!f){const F=Ln(u.left,0),H=Ln(u.right,0),ie=Ln(u.top,0),$=Ln(u.bottom,0);p?C=h-2*(F!==0||H!==0?F+H:Ln(u.left,u.right)):O=m-2*(ie!==0||$!==0?ie+$:Ln(u.top,u.bottom))}await l({...e,availableWidth:C,availableHeight:O});const N=await s.getDimensions(a.floating);return h!==N.width||m!==N.height?{reset:{rects:!0}}:{}}}};function Zv(){return typeof window<"u"}function Nc(r){return JM(r)?(r.nodeName||"").toLowerCase():"#document"}function Fn(r){var e;return(r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function no(r){var e;return(e=(JM(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function JM(r){return Zv()?r instanceof Node||r instanceof Fn(r).Node:!1}function Ri(r){return Zv()?r instanceof Element||r instanceof Fn(r).Element:!1}function jo(r){return Zv()?r instanceof HTMLElement||r instanceof Fn(r).HTMLElement:!1}function OR(r){return!Zv()||typeof ShadowRoot>"u"?!1:r instanceof ShadowRoot||r instanceof Fn(r).ShadowRoot}function uf(r){const{overflow:e,overflowX:t,overflowY:n,display:i}=Ci(r);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&i!=="inline"&&i!=="contents"}function d4(r){return/^(table|td|th)$/.test(Nc(r))}function em(r){try{if(r.matches(":popover-open"))return!0}catch{}try{return r.matches(":modal")}catch{return!1}}const f4=/transform|translate|scale|rotate|perspective|filter/,h4=/paint|layout|strict|content/,Xs=r=>!!r&&r!=="none";let Fg;function rw(r){const e=Ri(r)?Ci(r):r;return Xs(e.transform)||Xs(e.translate)||Xs(e.scale)||Xs(e.rotate)||Xs(e.perspective)||!nw()&&(Xs(e.backdropFilter)||Xs(e.filter))||f4.test(e.willChange||"")||h4.test(e.contain||"")}function p4(r){let e=Ms(r);for(;jo(e)&&!pc(e);){if(rw(e))return e;if(em(e))return null;e=Ms(e)}return null}function nw(){return Fg==null&&(Fg=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Fg}function pc(r){return/^(html|body|#document)$/.test(Nc(r))}function Ci(r){return Fn(r).getComputedStyle(r)}function tm(r){return Ri(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function Ms(r){if(Nc(r)==="html")return r;const e=r.assignedSlot||r.parentNode||OR(r)&&r.host||no(r);return OR(e)?e.host:e}function XM(r){const e=Ms(r);return pc(e)?r.ownerDocument?r.ownerDocument.body:r.body:jo(e)&&uf(e)?e:XM(e)}function Od(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const i=XM(r),o=i===((n=r.ownerDocument)==null?void 0:n.body),s=Fn(i);if(o){const a=zS(s);return e.concat(s,s.visualViewport||[],uf(i)?i:[],a&&t?Od(a):[])}else return e.concat(i,Od(i,[],t))}function zS(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function QM(r){const e=Ci(r);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=jo(r),o=i?r.offsetWidth:t,s=i?r.offsetHeight:n,a=Wp(t)!==o||Wp(n)!==s;return a&&(t=o,n=s),{width:t,height:n,$:a}}function iw(r){return Ri(r)?r:r.contextElement}function Yl(r){const e=iw(r);if(!jo(e))return Xi(1);const t=e.getBoundingClientRect(),{width:n,height:i,$:o}=QM(e);let s=(o?Wp(t.width):t.width)/n,a=(o?Wp(t.height):t.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}const v4=Xi(0);function ZM(r){const e=Fn(r);return!nw()||!e.visualViewport?v4:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function m4(r,e,t){return e===void 0&&(e=!1),!t||e&&t!==Fn(r)?!1:e}function ja(r,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const i=r.getBoundingClientRect(),o=iw(r);let s=Xi(1);e&&(n?Ri(n)&&(s=Yl(n)):s=Yl(r));const a=m4(o,t,n)?ZM(o):Xi(0);let l=(i.left+a.x)/s.x,c=(i.top+a.y)/s.y,u=i.width/s.x,d=i.height/s.y;if(o){const f=Fn(o),p=n&&Ri(n)?Fn(n):n;let h=f,m=zS(h);for(;m&&n&&p!==h;){const E=Yl(m),y=m.getBoundingClientRect(),S=Ci(m),R=y.left+(m.clientLeft+parseFloat(S.paddingLeft))*E.x,k=y.top+(m.clientTop+parseFloat(S.paddingTop))*E.y;l*=E.x,c*=E.y,u*=E.x,d*=E.y,l+=R,c+=k,h=Fn(m),m=zS(h)}}return Gp({width:u,height:d,x:l,y:c})}function rm(r,e){const t=tm(r).scrollLeft;return e?e.left+t:ja(no(r)).left+t}function eA(r,e){const t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-rm(r,t),i=t.top+e.scrollTop;return{x:n,y:i}}function g4(r){let{elements:e,rect:t,offsetParent:n,strategy:i}=r;const o=i==="fixed",s=no(n),a=e?em(e.floating):!1;if(n===s||a&&o)return t;let l={scrollLeft:0,scrollTop:0},c=Xi(1);const u=Xi(0),d=jo(n);if((d||!d&&!o)&&((Nc(n)!=="body"||uf(s))&&(l=tm(n)),d)){const p=ja(n);c=Yl(n),u.x=p.x+n.clientLeft,u.y=p.y+n.clientTop}const f=s&&!d&&!o?eA(s,l):Xi(0);return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+u.x+f.x,y:t.y*c.y-l.scrollTop*c.y+u.y+f.y}}function y4(r){return Array.from(r.getClientRects())}function S4(r){const e=no(r),t=tm(r),n=r.ownerDocument.body,i=Ln(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),o=Ln(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let s=-t.scrollLeft+rm(r);const a=-t.scrollTop;return Ci(n).direction==="rtl"&&(s+=Ln(e.clientWidth,n.clientWidth)-i),{width:i,height:o,x:s,y:a}}const PR=25;function b4(r,e){const t=Fn(r),n=no(r),i=t.visualViewport;let o=n.clientWidth,s=n.clientHeight,a=0,l=0;if(i){o=i.width,s=i.height;const u=nw();(!u||u&&e==="fixed")&&(a=i.offsetLeft,l=i.offsetTop)}const c=rm(n);if(c<=0){const u=n.ownerDocument,d=u.body,f=getComputedStyle(d),p=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,h=Math.abs(n.clientWidth-d.clientWidth-p);h<=PR&&(o-=h)}else c<=PR&&(o+=c);return{width:o,height:s,x:a,y:l}}function _4(r,e){const t=ja(r,!0,e==="fixed"),n=t.top+r.clientTop,i=t.left+r.clientLeft,o=jo(r)?Yl(r):Xi(1),s=r.clientWidth*o.x,a=r.clientHeight*o.y,l=i*o.x,c=n*o.y;return{width:s,height:a,x:l,y:c}}function MR(r,e,t){let n;if(e==="viewport")n=b4(r,t);else if(e==="document")n=S4(no(r));else if(Ri(e))n=_4(e,t);else{const i=ZM(r);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return Gp(n)}function tA(r,e){const t=Ms(r);return t===e||!Ri(t)||pc(t)?!1:Ci(t).position==="fixed"||tA(t,e)}function E4(r,e){const t=e.get(r);if(t)return t;let n=Od(r,[],!1).filter(a=>Ri(a)&&Nc(a)!=="body"),i=null;const o=Ci(r).position==="fixed";let s=o?Ms(r):r;for(;Ri(s)&&!pc(s);){const a=Ci(s),l=rw(s);!l&&a.position==="fixed"&&(i=null),(o?!l&&!i:!l&&a.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||uf(s)&&!l&&tA(r,s))?n=n.filter(u=>u!==s):i=a,s=Ms(s)}return e.set(r,n),n}function w4(r){let{element:e,boundary:t,rootBoundary:n,strategy:i}=r;const s=[...t==="clippingAncestors"?em(e)?[]:E4(e,this._c):[].concat(t),n],a=MR(e,s[0],i);let l=a.top,c=a.right,u=a.bottom,d=a.left;for(let f=1;f<s.length;f++){const p=MR(e,s[f],i);l=Ln(p.top,l),c=Ps(p.right,c),u=Ps(p.bottom,u),d=Ln(p.left,d)}return{width:c-d,height:u-l,x:d,y:l}}function T4(r){const{width:e,height:t}=QM(r);return{width:e,height:t}}function R4(r,e,t){const n=jo(e),i=no(e),o=t==="fixed",s=ja(r,!0,o,e);let a={scrollLeft:0,scrollTop:0};const l=Xi(0);function c(){l.x=rm(i)}if(n||!n&&!o)if((Nc(e)!=="body"||uf(i))&&(a=tm(e)),n){const p=ja(e,!0,o,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else i&&c();o&&!n&&i&&c();const u=i&&!n&&!o?eA(i,a):Xi(0),d=s.left+a.scrollLeft-l.x-u.x,f=s.top+a.scrollTop-l.y-u.y;return{x:d,y:f,width:s.width,height:s.height}}function Bg(r){return Ci(r).position==="static"}function AR(r,e){if(!jo(r)||Ci(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return no(r)===t&&(t=t.ownerDocument.body),t}function rA(r,e){const t=Fn(r);if(em(r))return t;if(!jo(r)){let i=Ms(r);for(;i&&!pc(i);){if(Ri(i)&&!Bg(i))return i;i=Ms(i)}return t}let n=AR(r,e);for(;n&&d4(n)&&Bg(n);)n=AR(n,e);return n&&pc(n)&&Bg(n)&&!rw(n)?t:n||p4(r)||t}const C4=async function(r){const e=this.getOffsetParent||rA,t=this.getDimensions,n=await t(r.floating);return{reference:R4(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function k4(r){return Ci(r).direction==="rtl"}const I4={convertOffsetParentRelativeRectToViewportRelativeRect:g4,getDocumentElement:no,getClippingRect:w4,getOffsetParent:rA,getElementRects:C4,getClientRects:y4,getDimensions:T4,getScale:Yl,isElement:Ri,isRTL:k4};function nA(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function x4(r,e){let t=null,n;const i=no(r);function o(){var a;clearTimeout(n),(a=t)==null||a.disconnect(),t=null}function s(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),o();const c=r.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=c;if(a||e(),!f||!p)return;const h=ch(d),m=ch(i.clientWidth-(u+f)),E=ch(i.clientHeight-(d+p)),y=ch(u),R={rootMargin:-h+"px "+-m+"px "+-E+"px "+-y+"px",threshold:Ln(0,Ps(1,l))||1};let k=!0;function x(T){const O=T[0].intersectionRatio;if(O!==l){if(!k)return s();O?s(!1,O):n=setTimeout(()=>{s(!1,1e-7)},1e3)}O===1&&!nA(c,r.getBoundingClientRect())&&s(),k=!1}try{t=new IntersectionObserver(x,{...R,root:i.ownerDocument})}catch{t=new IntersectionObserver(x,R)}t.observe(r)}return s(!0),o}function O4(r,e,t,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=n,c=iw(r),u=i||o?[...c?Od(c):[],...e?Od(e):[]]:[];u.forEach(y=>{i&&y.addEventListener("scroll",t,{passive:!0}),o&&y.addEventListener("resize",t)});const d=c&&a?x4(c,t):null;let f=-1,p=null;s&&(p=new ResizeObserver(y=>{let[S]=y;S&&S.target===c&&p&&e&&(p.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var R;(R=p)==null||R.observe(e)})),t()}),c&&!l&&p.observe(c),e&&p.observe(e));let h,m=l?ja(r):null;l&&E();function E(){const y=ja(r);m&&!nA(m,y)&&t(),m=y,h=requestAnimationFrame(E)}return t(),()=>{var y;u.forEach(S=>{i&&S.removeEventListener("scroll",t),o&&S.removeEventListener("resize",t)}),d==null||d(),(y=p)==null||y.disconnect(),p=null,l&&cancelAnimationFrame(h)}}const P4=a4,M4=l4,A4=i4,D4=u4,N4=o4,DR=n4,L4=c4,U4=(r,e,t)=>{const n=new Map,i={platform:I4,...t},o={...i.platform,_c:n};return r4(r,e,{...i,platform:o})};var j4=typeof document<"u",F4=function(){},Yh=j4?_.useLayoutEffect:F4;function Hp(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="function"&&r.toString()===e.toString())return!0;let t,n,i;if(r&&e&&typeof r=="object"){if(Array.isArray(r)){if(t=r.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!Hp(r[n],e[n]))return!1;return!0}if(i=Object.keys(r),t=i.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,i[n]))return!1;for(n=t;n--!==0;){const o=i[n];if(!(o==="_owner"&&r.$$typeof)&&!Hp(r[o],e[o]))return!1}return!0}return r!==r&&e!==e}function iA(r){return typeof window>"u"?1:(r.ownerDocument.defaultView||window).devicePixelRatio||1}function NR(r,e){const t=iA(r);return Math.round(e*t)/t}function Kg(r){const e=_.useRef(r);return Yh(()=>{e.current=r}),e}function B4(r){r===void 0&&(r={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:i,elements:{reference:o,floating:s}={},transform:a=!0,whileElementsMounted:l,open:c}=r,[u,d]=_.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[f,p]=_.useState(n);Hp(f,n)||p(n);const[h,m]=_.useState(null),[E,y]=_.useState(null),S=_.useCallback(q=>{q!==T.current&&(T.current=q,m(q))},[]),R=_.useCallback(q=>{q!==O.current&&(O.current=q,y(q))},[]),k=o||h,x=s||E,T=_.useRef(null),O=_.useRef(null),C=_.useRef(u),N=l!=null,F=Kg(l),H=Kg(i),ie=Kg(c),$=_.useCallback(()=>{if(!T.current||!O.current)return;const q={placement:e,strategy:t,middleware:f};H.current&&(q.platform=H.current),U4(T.current,O.current,q).then(z=>{const Q={...z,isPositioned:ie.current!==!1};X.current&&!Hp(C.current,Q)&&(C.current=Q,Wv.flushSync(()=>{d(Q)}))})},[f,e,t,H,ie]);Yh(()=>{c===!1&&C.current.isPositioned&&(C.current.isPositioned=!1,d(q=>({...q,isPositioned:!1})))},[c]);const X=_.useRef(!1);Yh(()=>(X.current=!0,()=>{X.current=!1}),[]),Yh(()=>{if(k&&(T.current=k),x&&(O.current=x),k&&x){if(F.current)return F.current(k,x,$);$()}},[k,x,$,F,N]);const oe=_.useMemo(()=>({reference:T,floating:O,setReference:S,setFloating:R}),[S,R]),re=_.useMemo(()=>({reference:k,floating:x}),[k,x]),ae=_.useMemo(()=>{const q={position:t,left:0,top:0};if(!re.floating)return q;const z=NR(re.floating,u.x),Q=NR(re.floating,u.y);return a?{...q,transform:"translate("+z+"px, "+Q+"px)",...iA(re.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:z,top:Q}},[t,a,re.floating,u.x,u.y]);return _.useMemo(()=>({...u,update:$,refs:oe,elements:re,floatingStyles:ae}),[u,$,oe,re,ae])}const K4=r=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:r,fn(t){const{element:n,padding:i}=typeof r=="function"?r(t):r;return n&&e(n)?n.current!=null?DR({element:n.current,padding:i}).fn(t):{}:n?DR({element:n,padding:i}).fn(t):{}}}},V4=(r,e)=>{const t=P4(r);return{name:t.name,fn:t.fn,options:[r,e]}},$4=(r,e)=>{const t=M4(r);return{name:t.name,fn:t.fn,options:[r,e]}},W4=(r,e)=>({fn:L4(r).fn,options:[r,e]}),q4=(r,e)=>{const t=A4(r);return{name:t.name,fn:t.fn,options:[r,e]}},G4=(r,e)=>{const t=D4(r);return{name:t.name,fn:t.fn,options:[r,e]}},H4=(r,e)=>{const t=N4(r);return{name:t.name,fn:t.fn,options:[r,e]}},z4=(r,e)=>{const t=K4(r);return{name:t.name,fn:t.fn,options:[r,e]}};var Y4="Arrow",oA=_.forwardRef((r,e)=>{const{children:t,width:n=10,height:i=5,...o}=r;return g.jsx(Je.svg,{...o,ref:e,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:r.asChild?t:g.jsx("polygon",{points:"0,0 30,0 15,10"})})});oA.displayName=Y4;var J4=oA,ow="Popper",[sA,Lc]=ro(ow),[X4,aA]=sA(ow),lA=r=>{const{__scopePopper:e,children:t}=r,[n,i]=_.useState(null);return g.jsx(X4,{scope:e,anchor:n,onAnchorChange:i,children:t})};lA.displayName=ow;var cA="PopperAnchor",uA=_.forwardRef((r,e)=>{const{__scopePopper:t,virtualRef:n,...i}=r,o=aA(cA,t),s=_.useRef(null),a=_t(e,s),l=_.useRef(null);return _.useEffect(()=>{const c=l.current;l.current=(n==null?void 0:n.current)||s.current,c!==l.current&&o.onAnchorChange(l.current)}),n?null:g.jsx(Je.div,{...i,ref:a})});uA.displayName=cA;var sw="PopperContent",[Q4,Z4]=sA(sw),dA=_.forwardRef((r,e)=>{var D,P,M,I,j,U;const{__scopePopper:t,side:n="bottom",sideOffset:i=0,align:o="center",alignOffset:s=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:h,...m}=r,E=aA(sw,t),[y,S]=_.useState(null),R=_t(e,K=>S(K)),[k,x]=_.useState(null),T=W3(k),O=(T==null?void 0:T.width)??0,C=(T==null?void 0:T.height)??0,N=n+(o!=="center"?"-"+o:""),F=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},H=Array.isArray(c)?c:[c],ie=H.length>0,$={padding:F,boundary:H.filter(tV),altBoundary:ie},{refs:X,floatingStyles:oe,placement:re,isPositioned:ae,middlewareData:q}=B4({strategy:"fixed",placement:N,whileElementsMounted:(...K)=>O4(...K,{animationFrame:p==="always"}),elements:{reference:E.anchor},middleware:[V4({mainAxis:i+C,alignmentAxis:s}),l&&$4({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?W4():void 0,...$}),l&&q4({...$}),G4({...$,apply:({elements:K,rects:G,availableWidth:ee,availableHeight:se})=>{const{width:Ce,height:Re}=G.reference,ge=K.floating.style;ge.setProperty("--radix-popper-available-width",`${ee}px`),ge.setProperty("--radix-popper-available-height",`${se}px`),ge.setProperty("--radix-popper-anchor-width",`${Ce}px`),ge.setProperty("--radix-popper-anchor-height",`${Re}px`)}}),k&&z4({element:k,padding:a}),rV({arrowWidth:O,arrowHeight:C}),f&&H4({strategy:"referenceHidden",...$})]}),[z,Q]=pA(re),Ie=Pr(h);Zn(()=>{ae&&(Ie==null||Ie())},[ae,Ie]);const Y=(D=q.arrow)==null?void 0:D.x,le=(P=q.arrow)==null?void 0:P.y,B=((M=q.arrow)==null?void 0:M.centerOffset)!==0,[W,A]=_.useState();return Zn(()=>{y&&A(window.getComputedStyle(y).zIndex)},[y]),g.jsx("div",{ref:X.setFloating,"data-radix-popper-content-wrapper":"",style:{...oe,transform:ae?oe.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:W,"--radix-popper-transform-origin":[(I=q.transformOrigin)==null?void 0:I.x,(j=q.transformOrigin)==null?void 0:j.y].join(" "),...((U=q.hide)==null?void 0:U.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:r.dir,children:g.jsx(Q4,{scope:t,placedSide:z,onArrowChange:x,arrowX:Y,arrowY:le,shouldHideArrow:B,children:g.jsx(Je.div,{"data-side":z,"data-align":Q,...m,ref:R,style:{...m.style,animation:ae?void 0:"none"}})})})});dA.displayName=sw;var fA="PopperArrow",eV={top:"bottom",right:"left",bottom:"top",left:"right"},hA=_.forwardRef(function(e,t){const{__scopePopper:n,...i}=e,o=Z4(fA,n),s=eV[o.placedSide];return g.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:g.jsx(J4,{...i,ref:t,style:{...i.style,display:"block"}})})});hA.displayName=fA;function tV(r){return r!==null}var rV=r=>({name:"transformOrigin",options:r,fn(e){var E,y,S;const{placement:t,rects:n,middlewareData:i}=e,s=((E=i.arrow)==null?void 0:E.centerOffset)!==0,a=s?0:r.arrowWidth,l=s?0:r.arrowHeight,[c,u]=pA(t),d={start:"0%",center:"50%",end:"100%"}[u],f=(((y=i.arrow)==null?void 0:y.x)??0)+a/2,p=(((S=i.arrow)==null?void 0:S.y)??0)+l/2;let h="",m="";return c==="bottom"?(h=s?d:`${f}px`,m=`${-l}px`):c==="top"?(h=s?d:`${f}px`,m=`${n.floating.height+l}px`):c==="right"?(h=`${-l}px`,m=s?d:`${p}px`):c==="left"&&(h=`${n.floating.width+l}px`,m=s?d:`${p}px`),{data:{x:h,y:m}}}});function pA(r){const[e,t="center"]=r.split("-");return[e,t]}var aw=lA,nm=uA,lw=dA,cw=hA,Vg="rovingFocusGroup.onEntryFocus",nV={bubbles:!1,cancelable:!0},df="RovingFocusGroup",[YS,vA,iV]=fM(df),[oV,mA]=ro(df,[iV]),[sV,aV]=oV(df),gA=_.forwardRef((r,e)=>g.jsx(YS.Provider,{scope:r.__scopeRovingFocusGroup,children:g.jsx(YS.Slot,{scope:r.__scopeRovingFocusGroup,children:g.jsx(lV,{...r,ref:e})})}));gA.displayName=df;var lV=_.forwardRef((r,e)=>{const{__scopeRovingFocusGroup:t,orientation:n,loop:i=!1,dir:o,currentTabStopId:s,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...d}=r,f=_.useRef(null),p=_t(e,f),h=KE(o),[m,E]=af({prop:s,defaultProp:a??null,onChange:l,caller:df}),[y,S]=_.useState(!1),R=Pr(c),k=vA(t),x=_.useRef(!1),[T,O]=_.useState(0);return _.useEffect(()=>{const C=f.current;if(C)return C.addEventListener(Vg,R),()=>C.removeEventListener(Vg,R)},[R]),g.jsx(sV,{scope:t,orientation:n,dir:h,loop:i,currentTabStopId:m,onItemFocus:_.useCallback(C=>E(C),[E]),onItemShiftTab:_.useCallback(()=>S(!0),[]),onFocusableItemAdd:_.useCallback(()=>O(C=>C+1),[]),onFocusableItemRemove:_.useCallback(()=>O(C=>C-1),[]),children:g.jsx(Je.div,{tabIndex:y||T===0?-1:0,"data-orientation":n,...d,ref:p,style:{outline:"none",...r.style},onMouseDown:Ae(r.onMouseDown,()=>{x.current=!0}),onFocus:Ae(r.onFocus,C=>{const N=!x.current;if(C.target===C.currentTarget&&N&&!y){const F=new CustomEvent(Vg,nV);if(C.currentTarget.dispatchEvent(F),!F.defaultPrevented){const H=k().filter(re=>re.focusable),ie=H.find(re=>re.active),$=H.find(re=>re.id===m),oe=[ie,$,...H].filter(Boolean).map(re=>re.ref.current);bA(oe,u)}}x.current=!1}),onBlur:Ae(r.onBlur,()=>S(!1))})})}),yA="RovingFocusGroupItem",SA=_.forwardRef((r,e)=>{const{__scopeRovingFocusGroup:t,focusable:n=!0,active:i=!1,tabStopId:o,children:s,...a}=r,l=Tn(),c=o||l,u=aV(yA,t),d=u.currentTabStopId===c,f=vA(t),{onFocusableItemAdd:p,onFocusableItemRemove:h,currentTabStopId:m}=u;return _.useEffect(()=>{if(n)return p(),()=>h()},[n,p,h]),g.jsx(YS.ItemSlot,{scope:t,id:c,focusable:n,active:i,children:g.jsx(Je.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...a,ref:e,onMouseDown:Ae(r.onMouseDown,E=>{n?u.onItemFocus(c):E.preventDefault()}),onFocus:Ae(r.onFocus,()=>u.onItemFocus(c)),onKeyDown:Ae(r.onKeyDown,E=>{if(E.key==="Tab"&&E.shiftKey){u.onItemShiftTab();return}if(E.target!==E.currentTarget)return;const y=dV(E,u.orientation,u.dir);if(y!==void 0){if(E.metaKey||E.ctrlKey||E.altKey||E.shiftKey)return;E.preventDefault();let R=f().filter(k=>k.focusable).map(k=>k.ref.current);if(y==="last")R.reverse();else if(y==="prev"||y==="next"){y==="prev"&&R.reverse();const k=R.indexOf(E.currentTarget);R=u.loop?fV(R,k+1):R.slice(k+1)}setTimeout(()=>bA(R))}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:m!=null}):s})})});SA.displayName=yA;var cV={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function uV(r,e){return e!=="rtl"?r:r==="ArrowLeft"?"ArrowRight":r==="ArrowRight"?"ArrowLeft":r}function dV(r,e,t){const n=uV(r.key,t);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return cV[n]}function bA(r,e=!1){const t=document.activeElement;for(const n of r)if(n===t||(n.focus({preventScroll:e}),document.activeElement!==t))return}function fV(r,e){return r.map((t,n)=>r[(e+n)%r.length])}var hV=gA,pV=SA,JS=["Enter"," "],vV=["ArrowDown","PageUp","Home"],_A=["ArrowUp","PageDown","End"],mV=[...vV,..._A],gV={ltr:[...JS,"ArrowRight"],rtl:[...JS,"ArrowLeft"]},yV={ltr:["ArrowLeft"],rtl:["ArrowRight"]},ff="Menu",[Pd,SV,bV]=fM(ff),[Xa,EA]=ro(ff,[bV,Lc,mA]),im=Lc(),wA=mA(),[_V,Qa]=Xa(ff),[EV,hf]=Xa(ff),TA=r=>{const{__scopeMenu:e,open:t=!1,children:n,dir:i,onOpenChange:o,modal:s=!0}=r,a=im(e),[l,c]=_.useState(null),u=_.useRef(!1),d=Pr(o),f=KE(i);return _.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),g.jsx(aw,{...a,children:g.jsx(_V,{scope:e,open:t,onOpenChange:d,content:l,onContentChange:c,children:g.jsx(EV,{scope:e,onClose:_.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:s,children:n})})})};TA.displayName=ff;var wV="MenuAnchor",uw=_.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r,i=im(t);return g.jsx(nm,{...i,...n,ref:e})});uw.displayName=wV;var dw="MenuPortal",[TV,RA]=Xa(dw,{forceMount:void 0}),CA=r=>{const{__scopeMenu:e,forceMount:t,children:n,container:i}=r,o=Qa(dw,e);return g.jsx(TV,{scope:e,forceMount:t,children:g.jsx(Gr,{present:t||o.open,children:g.jsx(cf,{asChild:!0,container:i,children:n})})})};CA.displayName=dw;var Yn="MenuContent",[RV,fw]=Xa(Yn),kA=_.forwardRef((r,e)=>{const t=RA(Yn,r.__scopeMenu),{forceMount:n=t.forceMount,...i}=r,o=Qa(Yn,r.__scopeMenu),s=hf(Yn,r.__scopeMenu);return g.jsx(Pd.Provider,{scope:r.__scopeMenu,children:g.jsx(Gr,{present:n||o.open,children:g.jsx(Pd.Slot,{scope:r.__scopeMenu,children:s.modal?g.jsx(CV,{...i,ref:e}):g.jsx(kV,{...i,ref:e})})})})}),CV=_.forwardRef((r,e)=>{const t=Qa(Yn,r.__scopeMenu),n=_.useRef(null),i=_t(e,n);return _.useEffect(()=>{const o=n.current;if(o)return $E(o)},[]),g.jsx(hw,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:t.open,disableOutsideScroll:!0,onFocusOutside:Ae(r.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>t.onOpenChange(!1)})}),kV=_.forwardRef((r,e)=>{const t=Qa(Yn,r.__scopeMenu);return g.jsx(hw,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>t.onOpenChange(!1)})}),IV=La("MenuContent.ScrollLock"),hw=_.forwardRef((r,e)=>{const{__scopeMenu:t,loop:n=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:h,...m}=r,E=Qa(Yn,t),y=hf(Yn,t),S=im(t),R=wA(t),k=SV(t),[x,T]=_.useState(null),O=_.useRef(null),C=_t(e,O,E.onContentChange),N=_.useRef(0),F=_.useRef(""),H=_.useRef(0),ie=_.useRef(null),$=_.useRef("right"),X=_.useRef(0),oe=h?Xv:_.Fragment,re=h?{as:IV,allowPinchZoom:!0}:void 0,ae=z=>{var D,P;const Q=F.current+z,Ie=k().filter(M=>!M.disabled),Y=document.activeElement,le=(D=Ie.find(M=>M.ref.current===Y))==null?void 0:D.textValue,B=Ie.map(M=>M.textValue),W=BV(B,Q,le),A=(P=Ie.find(M=>M.textValue===W))==null?void 0:P.ref.current;(function M(I){F.current=I,window.clearTimeout(N.current),I!==""&&(N.current=window.setTimeout(()=>M(""),1e3))})(Q),A&&setTimeout(()=>A.focus())};_.useEffect(()=>()=>window.clearTimeout(N.current),[]),VE();const q=_.useCallback(z=>{var Ie,Y;return $.current===((Ie=ie.current)==null?void 0:Ie.side)&&VV(z,(Y=ie.current)==null?void 0:Y.area)},[]);return g.jsx(RV,{scope:t,searchRef:F,onItemEnter:_.useCallback(z=>{q(z)&&z.preventDefault()},[q]),onItemLeave:_.useCallback(z=>{var Q;q(z)||((Q=O.current)==null||Q.focus(),T(null))},[q]),onTriggerLeave:_.useCallback(z=>{q(z)&&z.preventDefault()},[q]),pointerGraceTimerRef:H,onPointerGraceIntentChange:_.useCallback(z=>{ie.current=z},[]),children:g.jsx(oe,{...re,children:g.jsx(Yv,{asChild:!0,trapped:i,onMountAutoFocus:Ae(o,z=>{var Q;z.preventDefault(),(Q=O.current)==null||Q.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:g.jsx(lf,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:g.jsx(hV,{asChild:!0,...R,dir:y.dir,orientation:"vertical",loop:n,currentTabStopId:x,onCurrentTabStopIdChange:T,onEntryFocus:Ae(l,z=>{y.isUsingKeyboardRef.current||z.preventDefault()}),preventScrollOnEntryFocus:!0,children:g.jsx(lw,{role:"menu","aria-orientation":"vertical","data-state":$A(E.open),"data-radix-menu-content":"",dir:y.dir,...S,...m,ref:C,style:{outline:"none",...m.style},onKeyDown:Ae(m.onKeyDown,z=>{const Ie=z.target.closest("[data-radix-menu-content]")===z.currentTarget,Y=z.ctrlKey||z.altKey||z.metaKey,le=z.key.length===1;Ie&&(z.key==="Tab"&&z.preventDefault(),!Y&&le&&ae(z.key));const B=O.current;if(z.target!==B||!mV.includes(z.key))return;z.preventDefault();const A=k().filter(D=>!D.disabled).map(D=>D.ref.current);_A.includes(z.key)&&A.reverse(),jV(A)}),onBlur:Ae(r.onBlur,z=>{z.currentTarget.contains(z.target)||(window.clearTimeout(N.current),F.current="")}),onPointerMove:Ae(r.onPointerMove,Md(z=>{const Q=z.target,Ie=X.current!==z.clientX;if(z.currentTarget.contains(Q)&&Ie){const Y=z.clientX>X.current?"right":"left";$.current=Y,X.current=z.clientX}}))})})})})})})});kA.displayName=Yn;var xV="MenuGroup",pw=_.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r;return g.jsx(Je.div,{role:"group",...n,ref:e})});pw.displayName=xV;var OV="MenuLabel",IA=_.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r;return g.jsx(Je.div,{...n,ref:e})});IA.displayName=OV;var zp="MenuItem",LR="menu.itemSelect",om=_.forwardRef((r,e)=>{const{disabled:t=!1,onSelect:n,...i}=r,o=_.useRef(null),s=hf(zp,r.__scopeMenu),a=fw(zp,r.__scopeMenu),l=_t(e,o),c=_.useRef(!1),u=()=>{const d=o.current;if(!t&&d){const f=new CustomEvent(LR,{bubbles:!0,cancelable:!0});d.addEventListener(LR,p=>n==null?void 0:n(p),{once:!0}),uM(d,f),f.defaultPrevented?c.current=!1:s.onClose()}};return g.jsx(xA,{...i,ref:l,disabled:t,onClick:Ae(r.onClick,u),onPointerDown:d=>{var f;(f=r.onPointerDown)==null||f.call(r,d),c.current=!0},onPointerUp:Ae(r.onPointerUp,d=>{var f;c.current||(f=d.currentTarget)==null||f.click()}),onKeyDown:Ae(r.onKeyDown,d=>{const f=a.searchRef.current!=="";t||f&&d.key===" "||JS.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});om.displayName=zp;var xA=_.forwardRef((r,e)=>{const{__scopeMenu:t,disabled:n=!1,textValue:i,...o}=r,s=fw(zp,t),a=wA(t),l=_.useRef(null),c=_t(e,l),[u,d]=_.useState(!1),[f,p]=_.useState("");return _.useEffect(()=>{const h=l.current;h&&p((h.textContent??"").trim())},[o.children]),g.jsx(Pd.ItemSlot,{scope:t,disabled:n,textValue:i??f,children:g.jsx(pV,{asChild:!0,...a,focusable:!n,children:g.jsx(Je.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...o,ref:c,onPointerMove:Ae(r.onPointerMove,Md(h=>{n?s.onItemLeave(h):(s.onItemEnter(h),h.defaultPrevented||h.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ae(r.onPointerLeave,Md(h=>s.onItemLeave(h))),onFocus:Ae(r.onFocus,()=>d(!0)),onBlur:Ae(r.onBlur,()=>d(!1))})})})}),PV="MenuCheckboxItem",OA=_.forwardRef((r,e)=>{const{checked:t=!1,onCheckedChange:n,...i}=r;return g.jsx(NA,{scope:r.__scopeMenu,checked:t,children:g.jsx(om,{role:"menuitemcheckbox","aria-checked":Yp(t)?"mixed":t,...i,ref:e,"data-state":mw(t),onSelect:Ae(i.onSelect,()=>n==null?void 0:n(Yp(t)?!0:!t),{checkForDefaultPrevented:!1})})})});OA.displayName=PV;var PA="MenuRadioGroup",[MV,AV]=Xa(PA,{value:void 0,onValueChange:()=>{}}),MA=_.forwardRef((r,e)=>{const{value:t,onValueChange:n,...i}=r,o=Pr(n);return g.jsx(MV,{scope:r.__scopeMenu,value:t,onValueChange:o,children:g.jsx(pw,{...i,ref:e})})});MA.displayName=PA;var AA="MenuRadioItem",DA=_.forwardRef((r,e)=>{const{value:t,...n}=r,i=AV(AA,r.__scopeMenu),o=t===i.value;return g.jsx(NA,{scope:r.__scopeMenu,checked:o,children:g.jsx(om,{role:"menuitemradio","aria-checked":o,...n,ref:e,"data-state":mw(o),onSelect:Ae(n.onSelect,()=>{var s;return(s=i.onValueChange)==null?void 0:s.call(i,t)},{checkForDefaultPrevented:!1})})})});DA.displayName=AA;var vw="MenuItemIndicator",[NA,DV]=Xa(vw,{checked:!1}),LA=_.forwardRef((r,e)=>{const{__scopeMenu:t,forceMount:n,...i}=r,o=DV(vw,t);return g.jsx(Gr,{present:n||Yp(o.checked)||o.checked===!0,children:g.jsx(Je.span,{...i,ref:e,"data-state":mw(o.checked)})})});LA.displayName=vw;var NV="MenuSeparator",UA=_.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r;return g.jsx(Je.div,{role:"separator","aria-orientation":"horizontal",...n,ref:e})});UA.displayName=NV;var LV="MenuArrow",jA=_.forwardRef((r,e)=>{const{__scopeMenu:t,...n}=r,i=im(t);return g.jsx(cw,{...i,...n,ref:e})});jA.displayName=LV;var UV="MenuSub",[Ere,FA]=Xa(UV),Pu="MenuSubTrigger",BA=_.forwardRef((r,e)=>{const t=Qa(Pu,r.__scopeMenu),n=hf(Pu,r.__scopeMenu),i=FA(Pu,r.__scopeMenu),o=fw(Pu,r.__scopeMenu),s=_.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=o,c={__scopeMenu:r.__scopeMenu},u=_.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return _.useEffect(()=>u,[u]),_.useEffect(()=>{const d=a.current;return()=>{window.clearTimeout(d),l(null)}},[a,l]),g.jsx(uw,{asChild:!0,...c,children:g.jsx(xA,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":t.open,"aria-controls":i.contentId,"data-state":$A(t.open),...r,ref:Do(e,i.onTriggerChange),onClick:d=>{var f;(f=r.onClick)==null||f.call(r,d),!(r.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),t.open||t.onOpenChange(!0))},onPointerMove:Ae(r.onPointerMove,Md(d=>{o.onItemEnter(d),!d.defaultPrevented&&!r.disabled&&!t.open&&!s.current&&(o.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{t.onOpenChange(!0),u()},100))})),onPointerLeave:Ae(r.onPointerLeave,Md(d=>{var p,h;u();const f=(p=t.content)==null?void 0:p.getBoundingClientRect();if(f){const m=(h=t.content)==null?void 0:h.dataset.side,E=m==="right",y=E?-5:5,S=f[E?"left":"right"],R=f[E?"right":"left"];o.onPointerGraceIntentChange({area:[{x:d.clientX+y,y:d.clientY},{x:S,y:f.top},{x:R,y:f.top},{x:R,y:f.bottom},{x:S,y:f.bottom}],side:m}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(d),d.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Ae(r.onKeyDown,d=>{var p;const f=o.searchRef.current!=="";r.disabled||f&&d.key===" "||gV[n.dir].includes(d.key)&&(t.onOpenChange(!0),(p=t.content)==null||p.focus(),d.preventDefault())})})})});BA.displayName=Pu;var KA="MenuSubContent",VA=_.forwardRef((r,e)=>{const t=RA(Yn,r.__scopeMenu),{forceMount:n=t.forceMount,...i}=r,o=Qa(Yn,r.__scopeMenu),s=hf(Yn,r.__scopeMenu),a=FA(KA,r.__scopeMenu),l=_.useRef(null),c=_t(e,l);return g.jsx(Pd.Provider,{scope:r.__scopeMenu,children:g.jsx(Gr,{present:n||o.open,children:g.jsx(Pd.Slot,{scope:r.__scopeMenu,children:g.jsx(hw,{id:a.contentId,"aria-labelledby":a.triggerId,...i,ref:c,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var d;s.isUsingKeyboardRef.current&&((d=l.current)==null||d.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:Ae(r.onFocusOutside,u=>{u.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Ae(r.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:Ae(r.onKeyDown,u=>{var p;const d=u.currentTarget.contains(u.target),f=yV[s.dir].includes(u.key);d&&f&&(o.onOpenChange(!1),(p=a.trigger)==null||p.focus(),u.preventDefault())})})})})})});VA.displayName=KA;function $A(r){return r?"open":"closed"}function Yp(r){return r==="indeterminate"}function mw(r){return Yp(r)?"indeterminate":r?"checked":"unchecked"}function jV(r){const e=document.activeElement;for(const t of r)if(t===e||(t.focus(),document.activeElement!==e))return}function FV(r,e){return r.map((t,n)=>r[(e+n)%r.length])}function BV(r,e,t){const i=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,o=t?r.indexOf(t):-1;let s=FV(r,Math.max(o,0));i.length===1&&(s=s.filter(c=>c!==t));const l=s.find(c=>c.toLowerCase().startsWith(i.toLowerCase()));return l!==t?l:void 0}function KV(r,e){const{x:t,y:n}=r;let i=!1;for(let o=0,s=e.length-1;o<e.length;s=o++){const a=e[o],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>n!=f>n&&t<(d-c)*(n-u)/(f-u)+c&&(i=!i)}return i}function VV(r,e){if(!e)return!1;const t={x:r.clientX,y:r.clientY};return KV(t,e)}function Md(r){return e=>e.pointerType==="mouse"?r(e):void 0}var $V=TA,WV=uw,qV=CA,GV=kA,HV=pw,zV=IA,YV=om,JV=OA,XV=MA,QV=DA,ZV=LA,e$=UA,t$=jA,r$=BA,n$=VA,sm="DropdownMenu",[i$]=ro(sm,[EA]),an=EA(),[o$,WA]=i$(sm),qA=r=>{const{__scopeDropdownMenu:e,children:t,dir:n,open:i,defaultOpen:o,onOpenChange:s,modal:a=!0}=r,l=an(e),c=_.useRef(null),[u,d]=af({prop:i,defaultProp:o??!1,onChange:s,caller:sm});return g.jsx(o$,{scope:e,triggerId:Tn(),triggerRef:c,contentId:Tn(),open:u,onOpenChange:d,onOpenToggle:_.useCallback(()=>d(f=>!f),[d]),modal:a,children:g.jsx($V,{...l,open:u,onOpenChange:d,dir:n,modal:a,children:t})})};qA.displayName=sm;var GA="DropdownMenuTrigger",HA=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,disabled:n=!1,...i}=r,o=WA(GA,t),s=an(t);return g.jsx(WV,{asChild:!0,...s,children:g.jsx(Je.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...i,ref:Do(e,o.triggerRef),onPointerDown:Ae(r.onPointerDown,a=>{!n&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:Ae(r.onKeyDown,a=>{n||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});HA.displayName=GA;var s$="DropdownMenuPortal",zA=r=>{const{__scopeDropdownMenu:e,...t}=r,n=an(e);return g.jsx(qV,{...n,...t})};zA.displayName=s$;var YA="DropdownMenuContent",JA=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=WA(YA,t),o=an(t),s=_.useRef(!1);return g.jsx(GV,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...n,ref:e,onCloseAutoFocus:Ae(r.onCloseAutoFocus,a=>{var l;s.current||(l=i.triggerRef.current)==null||l.focus(),s.current=!1,a.preventDefault()}),onInteractOutside:Ae(r.onInteractOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;(!i.modal||u)&&(s.current=!0)}),style:{...r.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});JA.displayName=YA;var a$="DropdownMenuGroup",l$=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(HV,{...i,...n,ref:e})});l$.displayName=a$;var c$="DropdownMenuLabel",u$=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(zV,{...i,...n,ref:e})});u$.displayName=c$;var d$="DropdownMenuItem",XA=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(YV,{...i,...n,ref:e})});XA.displayName=d$;var f$="DropdownMenuCheckboxItem",h$=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(JV,{...i,...n,ref:e})});h$.displayName=f$;var p$="DropdownMenuRadioGroup",QA=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(XV,{...i,...n,ref:e})});QA.displayName=p$;var v$="DropdownMenuRadioItem",ZA=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(QV,{...i,...n,ref:e})});ZA.displayName=v$;var m$="DropdownMenuItemIndicator",e1=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(ZV,{...i,...n,ref:e})});e1.displayName=m$;var g$="DropdownMenuSeparator",t1=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(e$,{...i,...n,ref:e})});t1.displayName=g$;var y$="DropdownMenuArrow",S$=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(t$,{...i,...n,ref:e})});S$.displayName=y$;var b$="DropdownMenuSubTrigger",_$=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(r$,{...i,...n,ref:e})});_$.displayName=b$;var E$="DropdownMenuSubContent",w$=_.forwardRef((r,e)=>{const{__scopeDropdownMenu:t,...n}=r,i=an(t);return g.jsx(n$,{...i,...n,ref:e,style:{...r.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});w$.displayName=E$;var T$=qA,R$=HA,C$=zA,k$=JA,I$=XA,x$=QA,O$=ZA,P$=e1,M$=t1,A$="Label",r1=_.forwardRef((r,e)=>g.jsx(Je.label,{...r,ref:e,onMouseDown:t=>{var i;t.target.closest("button, input, select, textarea")||((i=r.onMouseDown)==null||i.call(r,t),!t.defaultPrevented&&t.detail>1&&t.preventDefault())}}));r1.displayName=A$;var D$=r1;function N$(r,[e,t]){return Math.min(t,Math.max(e,r))}var am="Popover",[n1]=ro(am,[Lc]),pf=Lc(),[L$,$s]=n1(am),i1=r=>{const{__scopePopover:e,children:t,open:n,defaultOpen:i,onOpenChange:o,modal:s=!1}=r,a=pf(e),l=_.useRef(null),[c,u]=_.useState(!1),[d,f]=af({prop:n,defaultProp:i??!1,onChange:o,caller:am});return g.jsx(aw,{...a,children:g.jsx(L$,{scope:e,contentId:Tn(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:_.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:c,onCustomAnchorAdd:_.useCallback(()=>u(!0),[]),onCustomAnchorRemove:_.useCallback(()=>u(!1),[]),modal:s,children:t})})};i1.displayName=am;var o1="PopoverAnchor",U$=_.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=$s(o1,t),o=pf(t),{onCustomAnchorAdd:s,onCustomAnchorRemove:a}=i;return _.useEffect(()=>(s(),()=>a()),[s,a]),g.jsx(nm,{...o,...n,ref:e})});U$.displayName=o1;var s1="PopoverTrigger",a1=_.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=$s(s1,t),o=pf(t),s=_t(e,i.triggerRef),a=g.jsx(Je.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":f1(i.open),...n,ref:s,onClick:Ae(r.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:g.jsx(nm,{asChild:!0,...o,children:a})});a1.displayName=s1;var gw="PopoverPortal",[j$,F$]=n1(gw,{forceMount:void 0}),l1=r=>{const{__scopePopover:e,forceMount:t,children:n,container:i}=r,o=$s(gw,e);return g.jsx(j$,{scope:e,forceMount:t,children:g.jsx(Gr,{present:t||o.open,children:g.jsx(cf,{asChild:!0,container:i,children:n})})})};l1.displayName=gw;var vc="PopoverContent",c1=_.forwardRef((r,e)=>{const t=F$(vc,r.__scopePopover),{forceMount:n=t.forceMount,...i}=r,o=$s(vc,r.__scopePopover);return g.jsx(Gr,{present:n||o.open,children:o.modal?g.jsx(K$,{...i,ref:e}):g.jsx(V$,{...i,ref:e})})});c1.displayName=vc;var B$=La("PopoverContent.RemoveScroll"),K$=_.forwardRef((r,e)=>{const t=$s(vc,r.__scopePopover),n=_.useRef(null),i=_t(e,n),o=_.useRef(!1);return _.useEffect(()=>{const s=n.current;if(s)return $E(s)},[]),g.jsx(Xv,{as:B$,allowPinchZoom:!0,children:g.jsx(u1,{...r,ref:i,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ae(r.onCloseAutoFocus,s=>{var a;s.preventDefault(),o.current||(a=t.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ae(r.onPointerDownOutside,s=>{const a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;o.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:Ae(r.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),V$=_.forwardRef((r,e)=>{const t=$s(vc,r.__scopePopover),n=_.useRef(!1),i=_.useRef(!1);return g.jsx(u1,{...r,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var s,a;(s=r.onCloseAutoFocus)==null||s.call(r,o),o.defaultPrevented||(n.current||(a=t.triggerRef.current)==null||a.focus(),o.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:o=>{var l,c;(l=r.onInteractOutside)==null||l.call(r,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=o.target;((c=t.triggerRef.current)==null?void 0:c.contains(s))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),u1=_.forwardRef((r,e)=>{const{__scopePopover:t,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=r,f=$s(vc,t),p=pf(t);return VE(),g.jsx(Yv,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:g.jsx(lf,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>f.onOpenChange(!1),children:g.jsx(lw,{"data-state":f1(f.open),role:"dialog",id:f.contentId,...p,...d,ref:e,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),d1="PopoverClose",$$=_.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=$s(d1,t);return g.jsx(Je.button,{type:"button",...n,ref:e,onClick:Ae(r.onClick,()=>i.onOpenChange(!1))})});$$.displayName=d1;var W$="PopoverArrow",q$=_.forwardRef((r,e)=>{const{__scopePopover:t,...n}=r,i=pf(t);return g.jsx(cw,{...i,...n,ref:e})});q$.displayName=W$;function f1(r){return r?"open":"closed"}var G$=i1,H$=a1,z$=l1,Y$=c1;function J$(r,e){return _.useReducer((t,n)=>e[t][n]??t,r)}var yw="ScrollArea",[h1]=ro(yw),[X$,ri]=h1(yw),p1=_.forwardRef((r,e)=>{const{__scopeScrollArea:t,type:n="hover",dir:i,scrollHideDelay:o=600,...s}=r,[a,l]=_.useState(null),[c,u]=_.useState(null),[d,f]=_.useState(null),[p,h]=_.useState(null),[m,E]=_.useState(null),[y,S]=_.useState(0),[R,k]=_.useState(0),[x,T]=_.useState(!1),[O,C]=_.useState(!1),N=_t(e,H=>l(H)),F=KE(i);return g.jsx(X$,{scope:t,type:n,dir:F,scrollHideDelay:o,scrollArea:a,viewport:c,onViewportChange:u,content:d,onContentChange:f,scrollbarX:p,onScrollbarXChange:h,scrollbarXEnabled:x,onScrollbarXEnabledChange:T,scrollbarY:m,onScrollbarYChange:E,scrollbarYEnabled:O,onScrollbarYEnabledChange:C,onCornerWidthChange:S,onCornerHeightChange:k,children:g.jsx(Je.div,{dir:F,...s,ref:N,style:{position:"relative","--radix-scroll-area-corner-width":y+"px","--radix-scroll-area-corner-height":R+"px",...r.style}})})});p1.displayName=yw;var v1="ScrollAreaViewport",m1=_.forwardRef((r,e)=>{const{__scopeScrollArea:t,children:n,nonce:i,...o}=r,s=ri(v1,t),a=_.useRef(null),l=_t(e,a,s.onViewportChange);return g.jsxs(g.Fragment,{children:[g.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),g.jsx(Je.div,{"data-radix-scroll-area-viewport":"",...o,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...r.style},children:g.jsx("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});m1.displayName=v1;var io="ScrollAreaScrollbar",g1=_.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=ri(io,r.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:s}=i,a=r.orientation==="horizontal";return _.useEffect(()=>(a?o(!0):s(!0),()=>{a?o(!1):s(!1)}),[a,o,s]),i.type==="hover"?g.jsx(Q$,{...n,ref:e,forceMount:t}):i.type==="scroll"?g.jsx(Z$,{...n,ref:e,forceMount:t}):i.type==="auto"?g.jsx(y1,{...n,ref:e,forceMount:t}):i.type==="always"?g.jsx(Sw,{...n,ref:e}):null});g1.displayName=io;var Q$=_.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=ri(io,r.__scopeScrollArea),[o,s]=_.useState(!1);return _.useEffect(()=>{const a=i.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),s(!0)},u=()=>{l=window.setTimeout(()=>s(!1),i.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",u),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",u)}}},[i.scrollArea,i.scrollHideDelay]),g.jsx(Gr,{present:t||o,children:g.jsx(y1,{"data-state":o?"visible":"hidden",...n,ref:e})})}),Z$=_.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=ri(io,r.__scopeScrollArea),o=r.orientation==="horizontal",s=cm(()=>l("SCROLL_END"),100),[a,l]=J$("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return _.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,i.scrollHideDelay,l]),_.useEffect(()=>{const c=i.viewport,u=o?"scrollLeft":"scrollTop";if(c){let d=c[u];const f=()=>{const p=c[u];d!==p&&(l("SCROLL"),s()),d=p};return c.addEventListener("scroll",f),()=>c.removeEventListener("scroll",f)}},[i.viewport,o,l,s]),g.jsx(Gr,{present:t||a!=="hidden",children:g.jsx(Sw,{"data-state":a==="hidden"?"hidden":"visible",...n,ref:e,onPointerEnter:Ae(r.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:Ae(r.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),y1=_.forwardRef((r,e)=>{const t=ri(io,r.__scopeScrollArea),{forceMount:n,...i}=r,[o,s]=_.useState(!1),a=r.orientation==="horizontal",l=cm(()=>{if(t.viewport){const c=t.viewport.offsetWidth<t.viewport.scrollWidth,u=t.viewport.offsetHeight<t.viewport.scrollHeight;s(a?c:u)}},10);return mc(t.viewport,l),mc(t.content,l),g.jsx(Gr,{present:n||o,children:g.jsx(Sw,{"data-state":o?"visible":"hidden",...i,ref:e})})}),Sw=_.forwardRef((r,e)=>{const{orientation:t="vertical",...n}=r,i=ri(io,r.__scopeScrollArea),o=_.useRef(null),s=_.useRef(0),[a,l]=_.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=w1(a.viewport,a.content),u={...n,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:f=>o.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function d(f,p){return oW(f,s.current,a,p)}return t==="horizontal"?g.jsx(eW,{...u,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const f=i.viewport.scrollLeft,p=UR(f,a,i.dir);o.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:f=>{i.viewport&&(i.viewport.scrollLeft=f)},onDragScroll:f=>{i.viewport&&(i.viewport.scrollLeft=d(f,i.dir))}}):t==="vertical"?g.jsx(tW,{...u,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const f=i.viewport.scrollTop,p=UR(f,a);o.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:f=>{i.viewport&&(i.viewport.scrollTop=f)},onDragScroll:f=>{i.viewport&&(i.viewport.scrollTop=d(f))}}):null}),eW=_.forwardRef((r,e)=>{const{sizes:t,onSizesChange:n,...i}=r,o=ri(io,r.__scopeScrollArea),[s,a]=_.useState(),l=_.useRef(null),c=_t(e,l,o.onScrollbarXChange);return _.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),g.jsx(b1,{"data-orientation":"horizontal",...i,ref:c,sizes:t,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":lm(t)+"px",...r.style},onThumbPointerDown:u=>r.onThumbPointerDown(u.x),onDragScroll:u=>r.onDragScroll(u.x),onWheelScroll:(u,d)=>{if(o.viewport){const f=o.viewport.scrollLeft+u.deltaX;r.onWheelScroll(f),R1(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&o.viewport&&s&&n({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Xp(s.paddingLeft),paddingEnd:Xp(s.paddingRight)}})}})}),tW=_.forwardRef((r,e)=>{const{sizes:t,onSizesChange:n,...i}=r,o=ri(io,r.__scopeScrollArea),[s,a]=_.useState(),l=_.useRef(null),c=_t(e,l,o.onScrollbarYChange);return _.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),g.jsx(b1,{"data-orientation":"vertical",...i,ref:c,sizes:t,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":lm(t)+"px",...r.style},onThumbPointerDown:u=>r.onThumbPointerDown(u.y),onDragScroll:u=>r.onDragScroll(u.y),onWheelScroll:(u,d)=>{if(o.viewport){const f=o.viewport.scrollTop+u.deltaY;r.onWheelScroll(f),R1(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&o.viewport&&s&&n({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Xp(s.paddingTop),paddingEnd:Xp(s.paddingBottom)}})}})}),[rW,S1]=h1(io),b1=_.forwardRef((r,e)=>{const{__scopeScrollArea:t,sizes:n,hasThumb:i,onThumbChange:o,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:u,onResize:d,...f}=r,p=ri(io,t),[h,m]=_.useState(null),E=_t(e,N=>m(N)),y=_.useRef(null),S=_.useRef(""),R=p.viewport,k=n.content-n.viewport,x=Pr(u),T=Pr(l),O=cm(d,10);function C(N){if(y.current){const F=N.clientX-y.current.left,H=N.clientY-y.current.top;c({x:F,y:H})}}return _.useEffect(()=>{const N=F=>{const H=F.target;(h==null?void 0:h.contains(H))&&x(F,k)};return document.addEventListener("wheel",N,{passive:!1}),()=>document.removeEventListener("wheel",N,{passive:!1})},[R,h,k,x]),_.useEffect(T,[n,T]),mc(h,O),mc(p.content,O),g.jsx(rW,{scope:t,scrollbar:h,hasThumb:i,onThumbChange:Pr(o),onThumbPointerUp:Pr(s),onThumbPositionChange:T,onThumbPointerDown:Pr(a),children:g.jsx(Je.div,{...f,ref:E,style:{position:"absolute",...f.style},onPointerDown:Ae(r.onPointerDown,N=>{N.button===0&&(N.target.setPointerCapture(N.pointerId),y.current=h.getBoundingClientRect(),S.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),C(N))}),onPointerMove:Ae(r.onPointerMove,C),onPointerUp:Ae(r.onPointerUp,N=>{const F=N.target;F.hasPointerCapture(N.pointerId)&&F.releasePointerCapture(N.pointerId),document.body.style.webkitUserSelect=S.current,p.viewport&&(p.viewport.style.scrollBehavior=""),y.current=null})})})}),Jp="ScrollAreaThumb",_1=_.forwardRef((r,e)=>{const{forceMount:t,...n}=r,i=S1(Jp,r.__scopeScrollArea);return g.jsx(Gr,{present:t||i.hasThumb,children:g.jsx(nW,{ref:e,...n})})}),nW=_.forwardRef((r,e)=>{const{__scopeScrollArea:t,style:n,...i}=r,o=ri(Jp,t),s=S1(Jp,t),{onThumbPositionChange:a}=s,l=_t(e,d=>s.onThumbChange(d)),c=_.useRef(void 0),u=cm(()=>{c.current&&(c.current(),c.current=void 0)},100);return _.useEffect(()=>{const d=o.viewport;if(d){const f=()=>{if(u(),!c.current){const p=sW(d,a);c.current=p,a()}};return a(),d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,u,a]),g.jsx(Je.div,{"data-state":s.hasThumb?"visible":"hidden",...i,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:Ae(r.onPointerDownCapture,d=>{const p=d.target.getBoundingClientRect(),h=d.clientX-p.left,m=d.clientY-p.top;s.onThumbPointerDown({x:h,y:m})}),onPointerUp:Ae(r.onPointerUp,s.onThumbPointerUp)})});_1.displayName=Jp;var bw="ScrollAreaCorner",E1=_.forwardRef((r,e)=>{const t=ri(bw,r.__scopeScrollArea),n=!!(t.scrollbarX&&t.scrollbarY);return t.type!=="scroll"&&n?g.jsx(iW,{...r,ref:e}):null});E1.displayName=bw;var iW=_.forwardRef((r,e)=>{const{__scopeScrollArea:t,...n}=r,i=ri(bw,t),[o,s]=_.useState(0),[a,l]=_.useState(0),c=!!(o&&a);return mc(i.scrollbarX,()=>{var d;const u=((d=i.scrollbarX)==null?void 0:d.offsetHeight)||0;i.onCornerHeightChange(u),l(u)}),mc(i.scrollbarY,()=>{var d;const u=((d=i.scrollbarY)==null?void 0:d.offsetWidth)||0;i.onCornerWidthChange(u),s(u)}),c?g.jsx(Je.div,{...n,ref:e,style:{width:o,height:a,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...r.style}}):null});function Xp(r){return r?parseInt(r,10):0}function w1(r,e){const t=r/e;return isNaN(t)?0:t}function lm(r){const e=w1(r.viewport,r.content),t=r.scrollbar.paddingStart+r.scrollbar.paddingEnd,n=(r.scrollbar.size-t)*e;return Math.max(n,18)}function oW(r,e,t,n="ltr"){const i=lm(t),o=i/2,s=e||o,a=i-s,l=t.scrollbar.paddingStart+s,c=t.scrollbar.size-t.scrollbar.paddingEnd-a,u=t.content-t.viewport,d=n==="ltr"?[0,u]:[u*-1,0];return T1([l,c],d)(r)}function UR(r,e,t="ltr"){const n=lm(e),i=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,o=e.scrollbar.size-i,s=e.content-e.viewport,a=o-n,l=t==="ltr"?[0,s]:[s*-1,0],c=N$(r,l);return T1([0,s],[0,a])(c)}function T1(r,e){return t=>{if(r[0]===r[1]||e[0]===e[1])return e[0];const n=(e[1]-e[0])/(r[1]-r[0]);return e[0]+n*(t-r[0])}}function R1(r,e){return r>0&&r<e}var sW=(r,e=()=>{})=>{let t={left:r.scrollLeft,top:r.scrollTop},n=0;return function i(){const o={left:r.scrollLeft,top:r.scrollTop},s=t.left!==o.left,a=t.top!==o.top;(s||a)&&e(),t=o,n=window.requestAnimationFrame(i)}(),()=>window.cancelAnimationFrame(n)};function cm(r,e){const t=Pr(r),n=_.useRef(0);return _.useEffect(()=>()=>window.clearTimeout(n.current),[]),_.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(t,e)},[t,e])}function mc(r,e){const t=Pr(e);Zn(()=>{let n=0;if(r){const i=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(t)});return i.observe(r),()=>{window.cancelAnimationFrame(n),i.unobserve(r)}}},[r,t])}var aW=p1,lW=m1,cW=E1,uW="Separator",jR="horizontal",dW=["horizontal","vertical"],C1=_.forwardRef((r,e)=>{const{decorative:t,orientation:n=jR,...i}=r,o=fW(n)?n:jR,a=t?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return g.jsx(Je.div,{"data-orientation":o,...a,...i,ref:e})});C1.displayName=uW;function fW(r){return dW.includes(r)}var hW=C1,[um]=ro("Tooltip",[Lc]),dm=Lc(),k1="TooltipProvider",pW=700,XS="tooltip.open",[vW,_w]=um(k1),I1=r=>{const{__scopeTooltip:e,delayDuration:t=pW,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:o}=r,s=_.useRef(!0),a=_.useRef(!1),l=_.useRef(0);return _.useEffect(()=>{const c=l.current;return()=>window.clearTimeout(c)},[]),g.jsx(vW,{scope:e,isOpenDelayedRef:s,delayDuration:t,onOpen:_.useCallback(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,n)},[n]),isPointerInTransitRef:a,onPointerInTransitChange:_.useCallback(c=>{a.current=c},[]),disableHoverableContent:i,children:o})};I1.displayName=k1;var Ad="Tooltip",[mW,vf]=um(Ad),x1=r=>{const{__scopeTooltip:e,children:t,open:n,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:a}=r,l=_w(Ad,r.__scopeTooltip),c=dm(e),[u,d]=_.useState(null),f=Tn(),p=_.useRef(0),h=s??l.disableHoverableContent,m=a??l.delayDuration,E=_.useRef(!1),[y,S]=af({prop:n,defaultProp:i??!1,onChange:O=>{O?(l.onOpen(),document.dispatchEvent(new CustomEvent(XS))):l.onClose(),o==null||o(O)},caller:Ad}),R=_.useMemo(()=>y?E.current?"delayed-open":"instant-open":"closed",[y]),k=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,E.current=!1,S(!0)},[S]),x=_.useCallback(()=>{window.clearTimeout(p.current),p.current=0,S(!1)},[S]),T=_.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{E.current=!0,S(!0),p.current=0},m)},[m,S]);return _.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),g.jsx(aw,{...c,children:g.jsx(mW,{scope:e,contentId:f,open:y,stateAttribute:R,trigger:u,onTriggerChange:d,onTriggerEnter:_.useCallback(()=>{l.isOpenDelayedRef.current?T():k()},[l.isOpenDelayedRef,T,k]),onTriggerLeave:_.useCallback(()=>{h?x():(window.clearTimeout(p.current),p.current=0)},[x,h]),onOpen:k,onClose:x,disableHoverableContent:h,children:t})})};x1.displayName=Ad;var QS="TooltipTrigger",O1=_.forwardRef((r,e)=>{const{__scopeTooltip:t,...n}=r,i=vf(QS,t),o=_w(QS,t),s=dm(t),a=_.useRef(null),l=_t(e,a,i.onTriggerChange),c=_.useRef(!1),u=_.useRef(!1),d=_.useCallback(()=>c.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),g.jsx(nm,{asChild:!0,...s,children:g.jsx(Je.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:l,onPointerMove:Ae(r.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),u.current=!0)}),onPointerLeave:Ae(r.onPointerLeave,()=>{i.onTriggerLeave(),u.current=!1}),onPointerDown:Ae(r.onPointerDown,()=>{i.open&&i.onClose(),c.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Ae(r.onFocus,()=>{c.current||i.onOpen()}),onBlur:Ae(r.onBlur,i.onClose),onClick:Ae(r.onClick,i.onClose)})})});O1.displayName=QS;var Ew="TooltipPortal",[gW,yW]=um(Ew,{forceMount:void 0}),P1=r=>{const{__scopeTooltip:e,forceMount:t,children:n,container:i}=r,o=vf(Ew,e);return g.jsx(gW,{scope:e,forceMount:t,children:g.jsx(Gr,{present:t||o.open,children:g.jsx(cf,{asChild:!0,container:i,children:n})})})};P1.displayName=Ew;var gc="TooltipContent",M1=_.forwardRef((r,e)=>{const t=yW(gc,r.__scopeTooltip),{forceMount:n=t.forceMount,side:i="top",...o}=r,s=vf(gc,r.__scopeTooltip);return g.jsx(Gr,{present:n||s.open,children:s.disableHoverableContent?g.jsx(A1,{side:i,...o,ref:e}):g.jsx(SW,{side:i,...o,ref:e})})}),SW=_.forwardRef((r,e)=>{const t=vf(gc,r.__scopeTooltip),n=_w(gc,r.__scopeTooltip),i=_.useRef(null),o=_t(e,i),[s,a]=_.useState(null),{trigger:l,onClose:c}=t,u=i.current,{onPointerInTransitChange:d}=n,f=_.useCallback(()=>{a(null),d(!1)},[d]),p=_.useCallback((h,m)=>{const E=h.currentTarget,y={x:h.clientX,y:h.clientY},S=wW(y,E.getBoundingClientRect()),R=TW(y,S),k=RW(m.getBoundingClientRect()),x=kW([...R,...k]);a(x),d(!0)},[d]);return _.useEffect(()=>()=>f(),[f]),_.useEffect(()=>{if(l&&u){const h=E=>p(E,u),m=E=>p(E,l);return l.addEventListener("pointerleave",h),u.addEventListener("pointerleave",m),()=>{l.removeEventListener("pointerleave",h),u.removeEventListener("pointerleave",m)}}},[l,u,p,f]),_.useEffect(()=>{if(s){const h=m=>{const E=m.target,y={x:m.clientX,y:m.clientY},S=(l==null?void 0:l.contains(E))||(u==null?void 0:u.contains(E)),R=!CW(y,s);S?f():R&&(f(),c())};return document.addEventListener("pointermove",h),()=>document.removeEventListener("pointermove",h)}},[l,u,s,c,f]),g.jsx(A1,{...r,ref:o})}),[bW,_W]=um(Ad,{isInside:!1}),EW=JK("TooltipContent"),A1=_.forwardRef((r,e)=>{const{__scopeTooltip:t,children:n,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:s,...a}=r,l=vf(gc,t),c=dm(t),{onClose:u}=l;return _.useEffect(()=>(document.addEventListener(XS,u),()=>document.removeEventListener(XS,u)),[u]),_.useEffect(()=>{if(l.trigger){const d=f=>{const p=f.target;p!=null&&p.contains(l.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]),g.jsx(lf,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:g.jsxs(lw,{"data-state":l.stateAttribute,...c,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[g.jsx(EW,{children:n}),g.jsx(bW,{scope:t,isInside:!0,children:g.jsx(n5,{id:l.contentId,role:"tooltip",children:i||n})})]})})});M1.displayName=gc;var D1="TooltipArrow",N1=_.forwardRef((r,e)=>{const{__scopeTooltip:t,...n}=r,i=dm(t);return _W(D1,t).isInside?null:g.jsx(cw,{...i,...n,ref:e})});N1.displayName=D1;function wW(r,e){const t=Math.abs(e.top-r.y),n=Math.abs(e.bottom-r.y),i=Math.abs(e.right-r.x),o=Math.abs(e.left-r.x);switch(Math.min(t,n,i,o)){case o:return"left";case i:return"right";case t:return"top";case n:return"bottom";default:throw new Error("unreachable")}}function TW(r,e,t=5){const n=[];switch(e){case"top":n.push({x:r.x-t,y:r.y+t},{x:r.x+t,y:r.y+t});break;case"bottom":n.push({x:r.x-t,y:r.y-t},{x:r.x+t,y:r.y-t});break;case"left":n.push({x:r.x+t,y:r.y-t},{x:r.x+t,y:r.y+t});break;case"right":n.push({x:r.x-t,y:r.y-t},{x:r.x-t,y:r.y+t});break}return n}function RW(r){const{top:e,right:t,bottom:n,left:i}=r;return[{x:i,y:e},{x:t,y:e},{x:t,y:n},{x:i,y:n}]}function CW(r,e){const{x:t,y:n}=r;let i=!1;for(let o=0,s=e.length-1;o<e.length;s=o++){const a=e[o],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>n!=f>n&&t<(d-c)*(n-u)/(f-u)+c&&(i=!i)}return i}function kW(r){const e=r.slice();return e.sort((t,n)=>t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0),IW(e)}function IW(r){if(r.length<=1)return r.slice();const e=[];for(let n=0;n<r.length;n++){const i=r[n];for(;e.length>=2;){const o=e[e.length-1],s=e[e.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))e.pop();else break}e.push(i)}e.pop();const t=[];for(let n=r.length-1;n>=0;n--){const i=r[n];for(;t.length>=2;){const o=t[t.length-1],s=t[t.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}var xW=I1,OW=x1,PW=O1,MW=P1,AW=M1,DW=N1;function L1(r){var e,t,n="";if(typeof r=="string"||typeof r=="number")n+=r;else if(typeof r=="object")if(Array.isArray(r)){var i=r.length;for(e=0;e<i;e++)r[e]&&(t=L1(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function U1(){for(var r,e,t=0,n="",i=arguments.length;t<i;t++)(r=arguments[t])&&(e=L1(r))&&(n&&(n+=" "),n+=e);return n}const NW=(r,e)=>{const t=new Array(r.length+e.length);for(let n=0;n<r.length;n++)t[n]=r[n];for(let n=0;n<e.length;n++)t[r.length+n]=e[n];return t},LW=(r,e)=>({classGroupId:r,validator:e}),j1=(r=new Map,e=null,t)=>({nextPart:r,validators:e,classGroupId:t}),Qp="-",FR=[],UW="arbitrary..",jW=r=>{const e=BW(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:s=>{if(s.startsWith("[")&&s.endsWith("]"))return FW(s);const a=s.split(Qp),l=a[0]===""&&a.length>1?1:0;return F1(a,l,e)},getConflictingClassGroupIds:(s,a)=>{if(a){const l=n[s],c=t[s];return l?c?NW(c,l):l:c||FR}return t[s]||FR}}},F1=(r,e,t)=>{if(r.length-e===0)return t.classGroupId;const i=r[e],o=t.nextPart.get(i);if(o){const c=F1(r,e+1,o);if(c)return c}const s=t.validators;if(s===null)return;const a=e===0?r.join(Qp):r.slice(e).join(Qp),l=s.length;for(let c=0;c<l;c++){const u=s[c];if(u.validator(a))return u.classGroupId}},FW=r=>r.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=r.slice(1,-1),t=e.indexOf(":"),n=e.slice(0,t);return n?UW+n:void 0})(),BW=r=>{const{theme:e,classGroups:t}=r;return KW(t,e)},KW=(r,e)=>{const t=j1();for(const n in r){const i=r[n];ww(i,t,n,e)}return t},ww=(r,e,t,n)=>{const i=r.length;for(let o=0;o<i;o++){const s=r[o];VW(s,e,t,n)}},VW=(r,e,t,n)=>{if(typeof r=="string"){$W(r,e,t);return}if(typeof r=="function"){WW(r,e,t,n);return}qW(r,e,t,n)},$W=(r,e,t)=>{const n=r===""?e:B1(e,r);n.classGroupId=t},WW=(r,e,t,n)=>{if(GW(r)){ww(r(n),e,t,n);return}e.validators===null&&(e.validators=[]),e.validators.push(LW(t,r))},qW=(r,e,t,n)=>{const i=Object.entries(r),o=i.length;for(let s=0;s<o;s++){const[a,l]=i[s];ww(l,B1(e,a),t,n)}},B1=(r,e)=>{let t=r;const n=e.split(Qp),i=n.length;for(let o=0;o<i;o++){const s=n[o];let a=t.nextPart.get(s);a||(a=j1(),t.nextPart.set(s,a)),t=a}return t},GW=r=>"isThemeGetter"in r&&r.isThemeGetter===!0,HW=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=Object.create(null),n=Object.create(null);const i=(o,s)=>{t[o]=s,e++,e>r&&(e=0,n=t,t=Object.create(null))};return{get(o){let s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set(o,s){o in t?t[o]=s:i(o,s)}}},ZS="!",BR=":",zW=[],KR=(r,e,t,n,i)=>({modifiers:r,hasImportantModifier:e,baseClassName:t,maybePostfixModifierPosition:n,isExternal:i}),YW=r=>{const{prefix:e,experimentalParseClassName:t}=r;let n=i=>{const o=[];let s=0,a=0,l=0,c;const u=i.length;for(let m=0;m<u;m++){const E=i[m];if(s===0&&a===0){if(E===BR){o.push(i.slice(l,m)),l=m+1;continue}if(E==="/"){c=m;continue}}E==="["?s++:E==="]"?s--:E==="("?a++:E===")"&&a--}const d=o.length===0?i:i.slice(l);let f=d,p=!1;d.endsWith(ZS)?(f=d.slice(0,-1),p=!0):d.startsWith(ZS)&&(f=d.slice(1),p=!0);const h=c&&c>l?c-l:void 0;return KR(o,p,f,h)};if(e){const i=e+BR,o=n;n=s=>s.startsWith(i)?o(s.slice(i.length)):KR(zW,!1,s,void 0,!0)}if(t){const i=n;n=o=>t({className:o,parseClassName:i})}return n},JW=r=>{const e=new Map;return r.orderSensitiveModifiers.forEach((t,n)=>{e.set(t,1e6+n)}),t=>{const n=[];let i=[];for(let o=0;o<t.length;o++){const s=t[o],a=s[0]==="[",l=e.has(s);a||l?(i.length>0&&(i.sort(),n.push(...i),i=[]),n.push(s)):i.push(s)}return i.length>0&&(i.sort(),n.push(...i)),n}},XW=r=>({cache:HW(r.cacheSize),parseClassName:YW(r),sortModifiers:JW(r),...jW(r)}),QW=/\s+/,ZW=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:i,sortModifiers:o}=e,s=[],a=r.trim().split(QW);let l="";for(let c=a.length-1;c>=0;c-=1){const u=a[c],{isExternal:d,modifiers:f,hasImportantModifier:p,baseClassName:h,maybePostfixModifierPosition:m}=t(u);if(d){l=u+(l.length>0?" "+l:l);continue}let E=!!m,y=n(E?h.substring(0,m):h);if(!y){if(!E){l=u+(l.length>0?" "+l:l);continue}if(y=n(h),!y){l=u+(l.length>0?" "+l:l);continue}E=!1}const S=f.length===0?"":f.length===1?f[0]:o(f).join(":"),R=p?S+ZS:S,k=R+y;if(s.indexOf(k)>-1)continue;s.push(k);const x=i(y,E);for(let T=0;T<x.length;++T){const O=x[T];s.push(R+O)}l=u+(l.length>0?" "+l:l)}return l},eq=(...r)=>{let e=0,t,n,i="";for(;e<r.length;)(t=r[e++])&&(n=K1(t))&&(i&&(i+=" "),i+=n);return i},K1=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=K1(r[n]))&&(t&&(t+=" "),t+=e);return t},tq=(r,...e)=>{let t,n,i,o;const s=l=>{const c=e.reduce((u,d)=>d(u),r());return t=XW(c),n=t.cache.get,i=t.cache.set,o=a,a(l)},a=l=>{const c=n(l);if(c)return c;const u=ZW(l,t);return i(l,u),u};return o=s,(...l)=>o(eq(...l))},rq=[],sr=r=>{const e=t=>t[r]||rq;return e.isThemeGetter=!0,e},V1=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,$1=/^\((?:(\w[\w-]*):)?(.+)\)$/i,nq=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,iq=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,oq=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,sq=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,aq=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,lq=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Go=r=>nq.test(r),Ze=r=>!!r&&!Number.isNaN(Number(r)),Ho=r=>!!r&&Number.isInteger(Number(r)),$g=r=>r.endsWith("%")&&Ze(r.slice(0,-1)),lo=r=>iq.test(r),W1=()=>!0,cq=r=>oq.test(r)&&!sq.test(r),Tw=()=>!1,uq=r=>aq.test(r),dq=r=>lq.test(r),fq=r=>!Oe(r)&&!Pe(r),hq=r=>Ws(r,H1,Tw),Oe=r=>V1.test(r),Qs=r=>Ws(r,z1,cq),VR=r=>Ws(r,_q,Ze),pq=r=>Ws(r,J1,W1),vq=r=>Ws(r,Y1,Tw),$R=r=>Ws(r,q1,Tw),mq=r=>Ws(r,G1,dq),uh=r=>Ws(r,X1,uq),Pe=r=>$1.test(r),su=r=>Za(r,z1),gq=r=>Za(r,Y1),WR=r=>Za(r,q1),yq=r=>Za(r,H1),Sq=r=>Za(r,G1),dh=r=>Za(r,X1,!0),bq=r=>Za(r,J1,!0),Ws=(r,e,t)=>{const n=V1.exec(r);return n?n[1]?e(n[1]):t(n[2]):!1},Za=(r,e,t=!1)=>{const n=$1.exec(r);return n?n[1]?e(n[1]):t:!1},q1=r=>r==="position"||r==="percentage",G1=r=>r==="image"||r==="url",H1=r=>r==="length"||r==="size"||r==="bg-size",z1=r=>r==="length",_q=r=>r==="number",Y1=r=>r==="family-name",J1=r=>r==="number"||r==="weight",X1=r=>r==="shadow",Eq=()=>{const r=sr("color"),e=sr("font"),t=sr("text"),n=sr("font-weight"),i=sr("tracking"),o=sr("leading"),s=sr("breakpoint"),a=sr("container"),l=sr("spacing"),c=sr("radius"),u=sr("shadow"),d=sr("inset-shadow"),f=sr("text-shadow"),p=sr("drop-shadow"),h=sr("blur"),m=sr("perspective"),E=sr("aspect"),y=sr("ease"),S=sr("animate"),R=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],x=()=>[...k(),Pe,Oe],T=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto","contain","none"],C=()=>[Pe,Oe,l],N=()=>[Go,"full","auto",...C()],F=()=>[Ho,"none","subgrid",Pe,Oe],H=()=>["auto",{span:["full",Ho,Pe,Oe]},Ho,Pe,Oe],ie=()=>[Ho,"auto",Pe,Oe],$=()=>["auto","min","max","fr",Pe,Oe],X=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],oe=()=>["start","end","center","stretch","center-safe","end-safe"],re=()=>["auto",...C()],ae=()=>[Go,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],q=()=>[Go,"screen","full","dvw","lvw","svw","min","max","fit",...C()],z=()=>[Go,"screen","full","lh","dvh","lvh","svh","min","max","fit",...C()],Q=()=>[r,Pe,Oe],Ie=()=>[...k(),WR,$R,{position:[Pe,Oe]}],Y=()=>["no-repeat",{repeat:["","x","y","space","round"]}],le=()=>["auto","cover","contain",yq,hq,{size:[Pe,Oe]}],B=()=>[$g,su,Qs],W=()=>["","none","full",c,Pe,Oe],A=()=>["",Ze,su,Qs],D=()=>["solid","dashed","dotted","double"],P=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],M=()=>[Ze,$g,WR,$R],I=()=>["","none",h,Pe,Oe],j=()=>["none",Ze,Pe,Oe],U=()=>["none",Ze,Pe,Oe],K=()=>[Ze,Pe,Oe],G=()=>[Go,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[lo],breakpoint:[lo],color:[W1],container:[lo],"drop-shadow":[lo],ease:["in","out","in-out"],font:[fq],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[lo],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[lo],shadow:[lo],spacing:["px",Ze],text:[lo],"text-shadow":[lo],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Go,Oe,Pe,E]}],container:["container"],columns:[{columns:[Ze,Oe,Pe,a]}],"break-after":[{"break-after":R()}],"break-before":[{"break-before":R()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:x()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:N()}],"inset-x":[{"inset-x":N()}],"inset-y":[{"inset-y":N()}],start:[{"inset-s":N(),start:N()}],end:[{"inset-e":N(),end:N()}],"inset-bs":[{"inset-bs":N()}],"inset-be":[{"inset-be":N()}],top:[{top:N()}],right:[{right:N()}],bottom:[{bottom:N()}],left:[{left:N()}],visibility:["visible","invisible","collapse"],z:[{z:[Ho,"auto",Pe,Oe]}],basis:[{basis:[Go,"full","auto",a,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ze,Go,"auto","initial","none",Oe]}],grow:[{grow:["",Ze,Pe,Oe]}],shrink:[{shrink:["",Ze,Pe,Oe]}],order:[{order:[Ho,"first","last","none",Pe,Oe]}],"grid-cols":[{"grid-cols":F()}],"col-start-end":[{col:H()}],"col-start":[{"col-start":ie()}],"col-end":[{"col-end":ie()}],"grid-rows":[{"grid-rows":F()}],"row-start-end":[{row:H()}],"row-start":[{"row-start":ie()}],"row-end":[{"row-end":ie()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":$()}],"auto-rows":[{"auto-rows":$()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...X(),"normal"]}],"justify-items":[{"justify-items":[...oe(),"normal"]}],"justify-self":[{"justify-self":["auto",...oe()]}],"align-content":[{content:["normal",...X()]}],"align-items":[{items:[...oe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...oe(),{baseline:["","last"]}]}],"place-content":[{"place-content":X()}],"place-items":[{"place-items":[...oe(),"baseline"]}],"place-self":[{"place-self":["auto",...oe()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pbs:[{pbs:C()}],pbe:[{pbe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:re()}],mx:[{mx:re()}],my:[{my:re()}],ms:[{ms:re()}],me:[{me:re()}],mbs:[{mbs:re()}],mbe:[{mbe:re()}],mt:[{mt:re()}],mr:[{mr:re()}],mb:[{mb:re()}],ml:[{ml:re()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:ae()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...z()]}],"min-block-size":[{"min-block":["auto",...z()]}],"max-block-size":[{"max-block":["none",...z()]}],w:[{w:[a,"screen",...ae()]}],"min-w":[{"min-w":[a,"screen","none",...ae()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...ae()]}],h:[{h:["screen","lh",...ae()]}],"min-h":[{"min-h":["screen","lh","none",...ae()]}],"max-h":[{"max-h":["screen","lh",...ae()]}],"font-size":[{text:["base",t,su,Qs]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,bq,pq]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",$g,Oe]}],"font-family":[{font:[gq,vq,e]}],"font-features":[{"font-features":[Oe]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Pe,Oe]}],"line-clamp":[{"line-clamp":[Ze,"none",Pe,VR]}],leading:[{leading:[o,...C()]}],"list-image":[{"list-image":["none",Pe,Oe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Pe,Oe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:Q()}],"text-color":[{text:Q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...D(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ze,"from-font","auto",Pe,Qs]}],"text-decoration-color":[{decoration:Q()}],"underline-offset":[{"underline-offset":[Ze,"auto",Pe,Oe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Pe,Oe]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Pe,Oe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Ie()}],"bg-repeat":[{bg:Y()}],"bg-size":[{bg:le()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ho,Pe,Oe],radial:["",Pe,Oe],conic:[Ho,Pe,Oe]},Sq,mq]}],"bg-color":[{bg:Q()}],"gradient-from-pos":[{from:B()}],"gradient-via-pos":[{via:B()}],"gradient-to-pos":[{to:B()}],"gradient-from":[{from:Q()}],"gradient-via":[{via:Q()}],"gradient-to":[{to:Q()}],rounded:[{rounded:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:A()}],"border-w-x":[{"border-x":A()}],"border-w-y":[{"border-y":A()}],"border-w-s":[{"border-s":A()}],"border-w-e":[{"border-e":A()}],"border-w-bs":[{"border-bs":A()}],"border-w-be":[{"border-be":A()}],"border-w-t":[{"border-t":A()}],"border-w-r":[{"border-r":A()}],"border-w-b":[{"border-b":A()}],"border-w-l":[{"border-l":A()}],"divide-x":[{"divide-x":A()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":A()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...D(),"hidden","none"]}],"divide-style":[{divide:[...D(),"hidden","none"]}],"border-color":[{border:Q()}],"border-color-x":[{"border-x":Q()}],"border-color-y":[{"border-y":Q()}],"border-color-s":[{"border-s":Q()}],"border-color-e":[{"border-e":Q()}],"border-color-bs":[{"border-bs":Q()}],"border-color-be":[{"border-be":Q()}],"border-color-t":[{"border-t":Q()}],"border-color-r":[{"border-r":Q()}],"border-color-b":[{"border-b":Q()}],"border-color-l":[{"border-l":Q()}],"divide-color":[{divide:Q()}],"outline-style":[{outline:[...D(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ze,Pe,Oe]}],"outline-w":[{outline:["",Ze,su,Qs]}],"outline-color":[{outline:Q()}],shadow:[{shadow:["","none",u,dh,uh]}],"shadow-color":[{shadow:Q()}],"inset-shadow":[{"inset-shadow":["none",d,dh,uh]}],"inset-shadow-color":[{"inset-shadow":Q()}],"ring-w":[{ring:A()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:Q()}],"ring-offset-w":[{"ring-offset":[Ze,Qs]}],"ring-offset-color":[{"ring-offset":Q()}],"inset-ring-w":[{"inset-ring":A()}],"inset-ring-color":[{"inset-ring":Q()}],"text-shadow":[{"text-shadow":["none",f,dh,uh]}],"text-shadow-color":[{"text-shadow":Q()}],opacity:[{opacity:[Ze,Pe,Oe]}],"mix-blend":[{"mix-blend":[...P(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":P()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ze]}],"mask-image-linear-from-pos":[{"mask-linear-from":M()}],"mask-image-linear-to-pos":[{"mask-linear-to":M()}],"mask-image-linear-from-color":[{"mask-linear-from":Q()}],"mask-image-linear-to-color":[{"mask-linear-to":Q()}],"mask-image-t-from-pos":[{"mask-t-from":M()}],"mask-image-t-to-pos":[{"mask-t-to":M()}],"mask-image-t-from-color":[{"mask-t-from":Q()}],"mask-image-t-to-color":[{"mask-t-to":Q()}],"mask-image-r-from-pos":[{"mask-r-from":M()}],"mask-image-r-to-pos":[{"mask-r-to":M()}],"mask-image-r-from-color":[{"mask-r-from":Q()}],"mask-image-r-to-color":[{"mask-r-to":Q()}],"mask-image-b-from-pos":[{"mask-b-from":M()}],"mask-image-b-to-pos":[{"mask-b-to":M()}],"mask-image-b-from-color":[{"mask-b-from":Q()}],"mask-image-b-to-color":[{"mask-b-to":Q()}],"mask-image-l-from-pos":[{"mask-l-from":M()}],"mask-image-l-to-pos":[{"mask-l-to":M()}],"mask-image-l-from-color":[{"mask-l-from":Q()}],"mask-image-l-to-color":[{"mask-l-to":Q()}],"mask-image-x-from-pos":[{"mask-x-from":M()}],"mask-image-x-to-pos":[{"mask-x-to":M()}],"mask-image-x-from-color":[{"mask-x-from":Q()}],"mask-image-x-to-color":[{"mask-x-to":Q()}],"mask-image-y-from-pos":[{"mask-y-from":M()}],"mask-image-y-to-pos":[{"mask-y-to":M()}],"mask-image-y-from-color":[{"mask-y-from":Q()}],"mask-image-y-to-color":[{"mask-y-to":Q()}],"mask-image-radial":[{"mask-radial":[Pe,Oe]}],"mask-image-radial-from-pos":[{"mask-radial-from":M()}],"mask-image-radial-to-pos":[{"mask-radial-to":M()}],"mask-image-radial-from-color":[{"mask-radial-from":Q()}],"mask-image-radial-to-color":[{"mask-radial-to":Q()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[Ze]}],"mask-image-conic-from-pos":[{"mask-conic-from":M()}],"mask-image-conic-to-pos":[{"mask-conic-to":M()}],"mask-image-conic-from-color":[{"mask-conic-from":Q()}],"mask-image-conic-to-color":[{"mask-conic-to":Q()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Ie()}],"mask-repeat":[{mask:Y()}],"mask-size":[{mask:le()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Pe,Oe]}],filter:[{filter:["","none",Pe,Oe]}],blur:[{blur:I()}],brightness:[{brightness:[Ze,Pe,Oe]}],contrast:[{contrast:[Ze,Pe,Oe]}],"drop-shadow":[{"drop-shadow":["","none",p,dh,uh]}],"drop-shadow-color":[{"drop-shadow":Q()}],grayscale:[{grayscale:["",Ze,Pe,Oe]}],"hue-rotate":[{"hue-rotate":[Ze,Pe,Oe]}],invert:[{invert:["",Ze,Pe,Oe]}],saturate:[{saturate:[Ze,Pe,Oe]}],sepia:[{sepia:["",Ze,Pe,Oe]}],"backdrop-filter":[{"backdrop-filter":["","none",Pe,Oe]}],"backdrop-blur":[{"backdrop-blur":I()}],"backdrop-brightness":[{"backdrop-brightness":[Ze,Pe,Oe]}],"backdrop-contrast":[{"backdrop-contrast":[Ze,Pe,Oe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ze,Pe,Oe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ze,Pe,Oe]}],"backdrop-invert":[{"backdrop-invert":["",Ze,Pe,Oe]}],"backdrop-opacity":[{"backdrop-opacity":[Ze,Pe,Oe]}],"backdrop-saturate":[{"backdrop-saturate":[Ze,Pe,Oe]}],"backdrop-sepia":[{"backdrop-sepia":["",Ze,Pe,Oe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Pe,Oe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ze,"initial",Pe,Oe]}],ease:[{ease:["linear","initial",y,Pe,Oe]}],delay:[{delay:[Ze,Pe,Oe]}],animate:[{animate:["none",S,Pe,Oe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[m,Pe,Oe]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:j()}],"rotate-x":[{"rotate-x":j()}],"rotate-y":[{"rotate-y":j()}],"rotate-z":[{"rotate-z":j()}],scale:[{scale:U()}],"scale-x":[{"scale-x":U()}],"scale-y":[{"scale-y":U()}],"scale-z":[{"scale-z":U()}],"scale-3d":["scale-3d"],skew:[{skew:K()}],"skew-x":[{"skew-x":K()}],"skew-y":[{"skew-y":K()}],transform:[{transform:[Pe,Oe,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:G()}],"translate-x":[{"translate-x":G()}],"translate-y":[{"translate-y":G()}],"translate-z":[{"translate-z":G()}],"translate-none":["translate-none"],accent:[{accent:Q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:Q()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Pe,Oe]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mbs":[{"scroll-mbs":C()}],"scroll-mbe":[{"scroll-mbe":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pbs":[{"scroll-pbs":C()}],"scroll-pbe":[{"scroll-pbe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Pe,Oe]}],fill:[{fill:["none",...Q()]}],"stroke-w":[{stroke:[Ze,su,Qs,VR]}],stroke:[{stroke:["none",...Q()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},wq=tq(Eq);function Le(...r){return wq(U1(r))}function eb({delayDuration:r=0,...e}){return g.jsx(xW,{"data-slot":"tooltip-provider",delayDuration:r,...e})}function qR({...r}){return g.jsx(OW,{"data-slot":"tooltip",...r})}function GR({...r}){return g.jsx(PW,{"data-slot":"tooltip-trigger",...r})}function HR({className:r,sideOffset:e=0,children:t,...n}){return g.jsx(MW,{children:g.jsxs(AW,{"data-slot":"tooltip-content",sideOffset:e,className:Le("z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",r),...n,children:[t,g.jsx(DW,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}function zR(r,e,t,n,i,o,s){try{var a=r[o](s),l=a.value}catch(c){return void t(c)}a.done?e(l):Promise.resolve(l).then(n,i)}function w(r){return function(){var e=this,t=arguments;return new Promise(function(n,i){var o=r.apply(e,t);function s(l){zR(o,n,i,s,a,"next",l)}function a(l){zR(o,n,i,s,a,"throw",l)}s(void 0)})}}function Dd(r){"@babel/helpers - typeof";return Dd=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Dd(r)}function Tq(r,e){if(Dd(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(Dd(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Rq(r){var e=Tq(r,"string");return Dd(e)=="symbol"?e:e+""}function v(r,e,t){return(e=Rq(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var Q1={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(wi,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],o={},s=null;function a(m,E){var y=m[E];if(typeof y.bind=="function")return y.bind(m);try{return Function.prototype.bind.call(y,m)}catch{return function(){return Function.prototype.apply.apply(y,[m,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(m){return m==="debug"&&(m="log"),typeof console===t?!1:m==="trace"&&n?l:console[m]!==void 0?a(console,m):console.log!==void 0?a(console,"log"):e}function u(){for(var m=this.getLevel(),E=0;E<i.length;E++){var y=i[E];this[y]=E<m?e:this.methodFactory(y,m,this.name)}if(this.log=this.debug,typeof console===t&&m<this.levels.SILENT)return"No console available for logging"}function d(m){return function(){typeof console!==t&&(u.call(this),this[m].apply(this,arguments))}}function f(m,E,y){return c(m)||d.apply(this,arguments)}function p(m,E){var y=this,S,R,k,x="loglevel";typeof m=="string"?x+=":"+m:typeof m=="symbol"&&(x=void 0);function T(H){var ie=(i[H]||"silent").toUpperCase();if(!(typeof window===t||!x)){try{window.localStorage[x]=ie;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+ie+";"}catch{}}}function O(){var H;if(!(typeof window===t||!x)){try{H=window.localStorage[x]}catch{}if(typeof H===t)try{var ie=window.document.cookie,$=encodeURIComponent(x),X=ie.indexOf($+"=");X!==-1&&(H=/^([^;]+)/.exec(ie.slice(X+$.length+1))[1])}catch{}return y.levels[H]===void 0&&(H=void 0),H}}function C(){if(!(typeof window===t||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function N(H){var ie=H;if(typeof ie=="string"&&y.levels[ie.toUpperCase()]!==void 0&&(ie=y.levels[ie.toUpperCase()]),typeof ie=="number"&&ie>=0&&ie<=y.levels.SILENT)return ie;throw new TypeError("log.setLevel() called with invalid level: "+H)}y.name=m,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=E||f,y.getLevel=function(){return k??R??S},y.setLevel=function(H,ie){return k=N(H),ie!==!1&&T(k),u.call(y)},y.setDefaultLevel=function(H){R=N(H),O()||y.setLevel(H,!1)},y.resetLevel=function(){k=null,C(),u.call(y)},y.enableAll=function(H){y.setLevel(y.levels.TRACE,H)},y.disableAll=function(H){y.setLevel(y.levels.SILENT,H)},y.rebuild=function(){if(s!==y&&(S=N(s.getLevel())),u.call(y),s===y)for(var H in o)o[H].rebuild()},S=N(s?s.getLevel():"WARN");var F=O();F!=null&&(k=N(F)),u.call(y)}s=new p,s.getLogger=function(E){if(typeof E!="symbol"&&typeof E!="string"||E==="")throw new TypeError("You must supply a name when creating a logger.");var y=o[E];return y||(y=o[E]=new p(E,s.methodFactory)),y};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return o},s.default=s,s})})(Q1);var Cq=Q1.exports;const Nd=qa(Cq);var Z1="matrix";Nd.methodFactory=function(r,e,t){return function(){for(var n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];this.prefix&&i.unshift(this.prefix);var s=r==="error"||r==="warn"||r==="trace"||r==="info"||r==="debug";return s?console[r](...i):console.log(...i)}};function eD(r){var e=r;e.getChild=e.withPrefix=function(t){var n=this.prefix||"";return kq(n+t)}}function kq(r){var e=Nd.getLogger("".concat(Z1,"-").concat(r));return e.prefix!==r&&(eD(e),e.prefix=r,e.setLevel(Nd.levels.DEBUG,!1)),e}var b=Nd.getLogger(Z1);b.setLevel(Nd.levels.DEBUG,!1);eD(b);class wre{constructor(e,t){this.parent=e,v(this,"name",void 0),this.name=t+":"}trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.trace(this.name,...t)}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.debug(this.name,...t)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.info(this.name,...t)}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.warn(this.name,...t)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.parent.error(this.name,...t)}}const Iq="l",xq="rn",Oq={0:"O",1:"l","֭":"֖","֮":"֘","֨":"֙","֤":"֚","᪴":"ۛ","⃛":"ۛ","ؙ":"̓","ࣳ":"̓","̓":"̓","̕":"̓","ُ":"̓","ٝ":"̔","֜":"́","֝":"́","ؘ":"́","݇":"́","́":"́","॔":"́","َ":"́","̀":"̀","॓":"̀","̌":"̆","꙼":"̆","٘":"̆","ٚ":"̆","ͮ":"̆","ۨ":"̆̇","̐":"̆̇","ँ":"̆̇","ঁ":"̆̇","ઁ":"̆̇","ଁ":"̆̇","ఀ":"̆̇","ಁ":"̆̇","ഁ":"̆̇","𑒿":"̆̇","᳐":"̂","̑":"̂","ٛ":"̂","߮":"̂","꛰":"̂","֯":"̊","۟":"̊","៓":"̊","゚":"̊","ْ":"̊","ஂ":"̊","ံ":"̊","ំ":"̊","𑌀":"̊","ํ":"̊","ໍ":"̊","ͦ":"̊","ⷪ":"̊","࣫":"̈","߳":"̈","ً":"̋","ࣰ":"̋","͂":"̃","ٓ":"̃","ׄ":"̇","۬":"̇","݀":"̇","࣪":"̇","݁":"̇","͘":"̇","ֹ":"̇","ֺ":"̇","ׂ":"̇","ׁ":"̇","߭":"̇","ं":"̇","ਂ":"̇","ં":"̇","்":"̇","̷":"̸","᪷":"̨","̢":"̨","ͅ":"̨","᳒":"̄","̅":"̄","ٙ":"̄","߫":"̄","꛱":"̄","᳚":"̎","ٗ":"̒","͗":"͐","ࣿ":"͐","ࣸ":"͐","ऀ":"͒","᳭":"̖","᳜":"̩","ٖ":"̩","᳕":"̫","͇":"̳","ࣹ":"͔","ࣺ":"͕","゛":"゙","゜":"゚","̶":"̵","〬":"̉","ׅ":"̣","࣭":"̣","᳝":"̣","ִ":"̣","ٜ":"̣","़":"̣","়":"̣","਼":"̣","઼":"̣","଼":"̣","𑇊":"̣","𑓃":"̣","𐨺":"̣","࣮":"̤","᳞":"̤","༷":"̥","〭":"̥","̧":"̦","̡":"̦","̹":"̦","᳙":"̭","᳘":"̮","॒":"̱","̠":"̱","ࣱ":"ٌ","ࣨ":"ٌ","ࣥ":"ٌ",ﱞ:"ﹲّ","ࣲ":"ٍ",ﱟ:"ﹴّ",ﳲ:"ﹷّ",ﱠ:"ﹶّ",ﳳ:"ﹹّ",ﱡ:"ﹸّ","ؚ":"ِ","̗":"ِ",ﳴ:"ﹻّ",ﱢ:"ﹺّ",ﱣ:"ﹼٰ","ٟ":"ٕ","̍":"ٰ","݂":"ܼ","ਃ":"ঃ","ః":"ঃ","ಃ":"ঃ","ഃ":"ঃ","ඃ":"ঃ","း":"ঃ","𑓁":"ঃ","់":"่","່":"่","້":"้","໊":"๊","໋":"๋","꙯":"⃩","\u2028":" ","\u2029":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" ","ߺ":"_","﹍":"_","﹎":"_","﹏":"_","‐":"-","‑":"-","‒":"-","–":"-","﹘":"-","۔":"-","⁃":"-","˗":"-","−":"-","➖":"-","Ⲻ":"-","⨩":"-̓","⸚":"-̈","﬩":"-̇","∸":"-̇","⨪":"-̣","꓾":"-.","~":"〜","؍":",","٫":",","‚":",","¸":",","ꓹ":",","⸲":"،","٬":"،",";":";","⸵":"؛","ः":":","ઃ":":",":":":","։":":","܃":":","܄":":","᛬":":","︰":":","᠃":":","᠉":":","⁚":":","׃":":","˸":":","꞉":":","∶":":",ː:":","ꓽ":":","⩴":"::=","⧴":":→","!":"!",ǃ:"!","ⵑ":"!","‼":"!!","⁉":"!?",ʔ:"?","Ɂ":"?","ॽ":"?",Ꭾ:"?","ꛫ":"?","⁈":"?!","⁇":"??","⸮":"؟","𝅭":".","․":".","܁":".","܂":".","꘎":".","𐩐":".","٠":".","۰":".","ꓸ":".","ꓻ":".,","‥":"..","ꓺ":"..","…":"...","꛴":"꛳꛳","・":"·","・":"·","᛫":"·","·":"·","⸱":"·","𐄁":"·","•":"·","‧":"·","∙":"·","⋅":"·","ꞏ":"·",ᐧ:"·","⋯":"···","ⵈ":"···",ᑄ:"·<","⋗":"·>",ᐷ:"·>",ᑀ:"·>",ᔯ:"·4",ᑾ:"·b",ᒀ:"·ḃ",ᑺ:"·d",ᒘ:"·J",ᒶ:"·L",ᑶ:"·P",ᑗ:"·U",ᐺ:"·V",ᐼ:"·Ʌ",ᒮ:"·Γ",ᐎ:"·Δ",ᑙ:"·Ո",ᐌ:"·ᐁ",ᐐ:"·ᐄ",ᐒ:"·ᐅ",ᐔ:"·ᐆ",ᐗ:"·ᐊ",ᐙ:"·ᐋ",ᐾ:"·ᐲ",ᑂ:"·ᐴ",ᑆ:"·ᐹ",ᑛ:"·ᑏ",ᑔ:"·ᑐ",ᑝ:"·ᑐ",ᑟ:"·ᑑ",ᑡ:"·ᑕ",ᑣ:"·ᑖ",ᑴ:"·ᑫ",ᑸ:"·ᑮ",ᑼ:"·ᑰ",ᒒ:"·ᒉ",ᒔ:"·ᒋ",ᒖ:"·ᒌ",ᒚ:"·ᒎ",ᒜ:"·ᒐ",ᒞ:"·ᒑ",ᒬ:"·ᒣ",ᒰ:"·ᒦ",ᒲ:"·ᒧ",ᒴ:"·ᒨ",ᒸ:"·ᒫ",ᓉ:"·ᓀ","ᣆ":"·ᓂ","ᣈ":"·ᓃ","ᣊ":"·ᓄ","ᣌ":"·ᓅ",ᓋ:"·ᓇ",ᓍ:"·ᓈ",ᓜ:"·ᓓ",ᓞ:"·ᓕ",ᓠ:"·ᓖ",ᓢ:"·ᓗ",ᓤ:"·ᓘ",ᓦ:"·ᓚ",ᓨ:"·ᓛ",ᓶ:"·ᓭ",ᓸ:"·ᓯ",ᓺ:"·ᓰ",ᓼ:"·ᓱ",ᓾ:"·ᓲ",ᔀ:"·ᓴ",ᔂ:"·ᓵ",ᔗ:"·ᔐ",ᔙ:"·ᔑ",ᔛ:"·ᔒ",ᔝ:"·ᔓ",ᔟ:"·ᔔ",ᔡ:"·ᔕ",ᔣ:"·ᔖ",ᔱ:"·ᔨ",ᔳ:"·ᔩ",ᔵ:"·ᔪ",ᔷ:"·ᔫ",ᔹ:"·ᔭ",ᔻ:"·ᔮ","ᣎ":"·ᕃ","ᣏ":"·ᕆ","ᣐ":"·ᕇ","ᣑ":"·ᕈ","ᣒ":"·ᕉ","ᣓ":"·ᕋ",ᕎ:"·ᕌ",ᕛ:"·ᕚ",ᕨ:"·ᕧ","ᢳ":"·ᢱ","ᢶ":"·ᢴ","ᢹ":"·ᢸ","ᣂ":"·ᣀ","꠰":"।","॥":"।।","᰼":"᰻᰻","။":"၊၊","᪩":"᪨᪨","᪫":"᪪᪨","᭟":"᭞᭞","𐩗":"𐩖𐩖","𑑌":"𑑋𑑋","𑙂":"𑙁𑙁","𑱂":"𑱁𑱁","᱿":"᱾᱾","՝":"'","'":"'","‘":"'","’":"'","‛":"'","′":"'","‵":"'","՚":"'","׳":"'","`":"'","`":"'","`":"'","´":"'","΄":"'","´":"'","᾽":"'","᾿":"'","῾":"'","ʹ":"'","ʹ":"'","ˈ":"'","ˊ":"'","ˋ":"'","˴":"'",ʻ:"'",ʽ:"'",ʼ:"'",ʾ:"'","ꞌ":"'",י:"'","ߴ":"'","ߵ":"'",ᑊ:"'",ᛌ:"'","𖽑":"'","𖽒":"'","᳓":"''",'"':"''",""":"''","“":"''","”":"''","‟":"''","″":"''","‶":"''","〃":"''","״":"''","˝":"''","ʺ":"''","˶":"''",ˮ:"''",ײ:"''","‴":"'''","‷":"'''","⁗":"''''",Ɓ:"'B",Ɗ:"'D",ʼn:"'n",Ƥ:"'P",Ƭ:"'T",Ƴ:"'Y","[":"(","❨":"(","❲":"(","〔":"(","﴾":"(","⸨":"((","㈠":"(ー)","⑵":"(2)","⒇":"(2O)","⑶":"(3)","⑷":"(4)","⑸":"(5)","⑹":"(6)","⑺":"(7)","⑻":"(8)","⑼":"(9)","⒜":"(a)","🄐":"(A)","⒝":"(b)","🄑":"(B)","⒞":"(c)","🄒":"(C)","⒟":"(d)","🄓":"(D)","⒠":"(e)","🄔":"(E)","⒡":"(f)","🄕":"(F)","⒢":"(g)","🄖":"(G)","⒣":"(h)","🄗":"(H)","⒤":"(i)","⒥":"(j)","🄙":"(J)","⒦":"(k)","🄚":"(K)","⑴":"(l)","🄘":"(l)","⒧":"(l)","🄛":"(L)","⑿":"(l2)","⒀":"(l3)","⒁":"(l4)","⒂":"(l5)","⒃":"(l6)","⒄":"(l7)","⒅":"(l8)","⒆":"(l9)","⑾":"(ll)","⑽":"(lO)","🄜":"(M)","⒩":"(n)","🄝":"(N)","⒪":"(o)","🄞":"(O)","⒫":"(p)","🄟":"(P)","⒬":"(q)","🄠":"(Q)","⒭":"(r)","🄡":"(R)","⒨":"(rn)","⒮":"(s)","🄢":"(S)","🄪":"(S)","⒯":"(t)","🄣":"(T)","⒰":"(u)","🄤":"(U)","⒱":"(v)","🄥":"(V)","⒲":"(w)","🄦":"(W)","⒳":"(x)","🄧":"(X)","⒴":"(y)","🄨":"(Y)","⒵":"(z)","🄩":"(Z)","㈀":"(ᄀ)","㈎":"(가)","㈁":"(ᄂ)","㈏":"(나)","㈂":"(ᄃ)","㈐":"(다)","㈃":"(ᄅ)","㈑":"(라)","㈄":"(ᄆ)","㈒":"(마)","㈅":"(ᄇ)","㈓":"(바)","㈆":"(ᄉ)","㈔":"(사)","㈇":"(ᄋ)","㈕":"(아)","㈝":"(오전)","㈞":"(오후)","㈈":"(ᄌ)","㈖":"(자)","㈜":"(주)","㈉":"(ᄎ)","㈗":"(차)","㈊":"(ᄏ)","㈘":"(카)","㈋":"(ᄐ)","㈙":"(타)","㈌":"(ᄑ)","㈚":"(파)","㈍":"(ᄒ)","㈛":"(하)","㈦":"(七)","㈢":"(三)","🉁":"(三)","㈨":"(九)","㈡":"(二)","🉂":"(二)","㈤":"(五)","㈹":"(代)","㈽":"(企)","㉁":"(休)","㈧":"(八)","㈥":"(六)","㈸":"(労)","🉇":"(勝)","㈩":"(十)","㈿":"(協)","㈴":"(名)","㈺":"(呼)","㈣":"(四)","㈯":"(土)","㈻":"(学)","🉃":"(安)","🉅":"(打)","🉈":"(敗)","㈰":"(日)","㈪":"(月)","㈲":"(有)","㈭":"(木)","🉀":"(本)","㈱":"(株)","㈬":"(水)","㈫":"(火)","🉄":"(点)","㈵":"(特)","🉆":"(盗)","㈼":"(監)","㈳":"(社)","㈷":"(祝)","㉀":"(祭)","㉂":"(自)","㉃":"(至)","㈶":"(財)","㈾":"(資)","㈮":"(金)","]":")","❩":")","❳":")","〕":")","﴿":")","⸩":"))","❴":"{","𝄔":"{","❵":"}","〚":"⟦","〛":"⟧","⟨":"❬","〈":"❬","〈":"❬","㇛":"❬",く:"❬","𡿨":"❬","⟩":"❭","〉":"❭","〉":"❭","^":"︿","⸿":"¶","⁎":"*","٭":"*","∗":"*","𐌟":"*","᜵":"/","⁁":"/","∕":"/","⁄":"/","╱":"/","⟋":"/","⧸":"/","𝈺":"/","㇓":"/",〳:"/","Ⳇ":"/",ノ:"/",丿:"/","⼃":"/","⧶":"/̄","⫽":"//","⫻":"///","\":"\\","﹨":"\\","∖":"\\","⟍":"\\","⧵":"\\","⧹":"\\","𝈏":"\\","𝈻":"\\","㇔":"\\",丶:"\\","⼂":"\\","⳹":"\\\\","⑊":"\\\\","⟈":"\\ᑕ","ꝸ":"&","૰":"॰","𑂻":"॰","𑇇":"॰","⚬":"॰","𑇛":"꣼","៙":"๏","៕":"๚","៚":"๛","༌":"་","༎":"།།","˄":"^","ˆ":"^","꙾":"ˇ","˘":"ˇ","‾":"ˉ","﹉":"ˉ","﹊":"ˉ","﹋":"ˉ","﹌":"ˉ","¯":"ˉ"," ̄":"ˉ","▔":"ˉ",ъ:"ˉb","ꙑ":"ˉbi","͵":"ˏ","˻":"˪","꜖":"˪","꜔":"˫","。":"˳","⸰":"°","˚":"°","∘":"°","○":"°","◦":"°","⍜":"°̲","⍤":"°̈","℃":"°C","℉":"°F","௵":"௳","༛":"༚༚","༟":"༚༝","࿎":"༝༚","༞":"༝༝","Ⓒ":"©","Ⓡ":"®","Ⓟ":"℗","𝈛":"⅄","⯬":"↞","⯭":"↟","⯮":"↠","⯯":"↡","↵":"↲","⥥":"⇃⇂","⥯":"⇃ᛚ","𝛛":"∂","𝜕":"∂","𝝏":"∂","𝞉":"∂","𝟃":"∂","𞣌":"∂","𞣍":"∂̵",ð:"∂̵","⌀":"∅","𝛁":"∇","𝛻":"∇","𝜵":"∇","𝝯":"∇","𝞩":"∇","𑢨":"∇","⍢":"∇̈","⍫":"∇̴","█":"∎","■":"∎","⨿":"∐","᛭":"+","➕":"+","𐊛":"+","⨣":"+̂","⨢":"+̊","⨤":"+̃","∔":"+̇","⨥":"+̣","⨦":"+̰","⨧":"+₂","➗":"÷","‹":"<","❮":"<","˂":"<","𝈶":"<",ᐸ:"<",ᚲ:"<","⋖":"<·","Ⲵ":"<·",ᑅ:"<·","≪":"<<","⋘":"<<<","᐀":"=","⹀":"=","゠":"=","꓿":"=","≚":"=̆","≙":"=̂","≗":"=̊","≐":"=̇","≑":"=̣̇","⩮":"=⃰","⩵":"==","⩶":"===","≞":"=ͫ","›":">","❯":">","˃":">","𝈷":">",ᐳ:">","𖼿":">",ᑁ:">·","⪥":"><","≫":">>","⨠":">>","⋙":">>>","⁓":"~","˜":"~","῀":"~","∼":"~","⍨":"~̈","⸞":"~̇","⩪":"~̇","⸟":"~̣","𞣈":"∠","⋀":"∧","∯":"∮∮","∰":"∮∮∮","⸫":"∴","⸪":"∵","⸬":"∷","𑇞":"≈","♎":"≏","🝞":"≏","≣":"≡","⨃":"⊍","⨄":"⊎","𝈸":"⊏","𝈹":"⊐","⨅":"⊓","⨆":"⊔","⨂":"⊗","⍟":"⊛","🝱":"⊠","🝕":"⊡","◁":"⊲","▷":"⊳","⍣":"⋆̈","︴":"⌇","◠":"⌒","⨽":"⌙","⌥":"⌤","⧇":"⌻","◎":"⌾","⦾":"⌾","⧅":"⍂","⦰":"⍉","⏃":"⍋","⏂":"⍎","⏁":"⍕","⏆":"⍭","☸":"⎈","︵":"⏜","︶":"⏝","︷":"⏞","︸":"⏟","︹":"⏠","︺":"⏡","▱":"⏥","⏼":"⏻","︱":"│","|":"│","┃":"│","┏":"┌","┣":"├","▐":"▌","▗":"▖","▝":"▘","☐":"□","■":"▪","▸":"▶","►":"▶","⳩":"☧","🜊":"☩","🌒":"☽","🌙":"☽","⏾":"☾","🌘":"☾","⧙":"⦚","🜺":"⧟","⨾":"⨟","𐆠":"⳨","♩":"𝅘𝅥","♪":"𝅘𝅥𝅮","⓪":"🄍","↺":"🄎","˙":"ॱ","ൎ":"ॱ","-":"ー","—":"ー","―":"ー","─":"ー","━":"ー","㇐":"ー","ꟷ":"ー",ᅳ:"ー",ㅡ:"ー",一:"ー","⼀":"ー",ᆖ:"ーー","ힹ":"ーᅡ","ힺ":"ーᅥ","ힻ":"ーᅥ丨","ힼ":"ーᅩ",ᆕ:"ーᅮ",ᅴ:"ー丨",ㅢ:"ー丨",ᆗ:"ー丨ᅮ","🄏":"$⃠","₤":"£","〒":"₸","〶":"₸","᭜":"᭐","꧆":"꧐","𑓑":"১","೧":"౧","ၥ":"၁","①":"➀","⑩":"➉","⏨":"₁₀","𝟐":"2","𝟚":"2","𝟤":"2","𝟮":"2","𝟸":"2","🯲":"2","Ꝛ":"2",Ƨ:"2",Ϩ:"2","Ꙅ":"2",ᒿ:"2","ꛯ":"2","ꧏ":"٢","۲":"٢","૨":"२","𑓒":"২","೨":"౨","②":"➁",ƻ:"2̵","🄃":"2,","⒉":"2.","㏵":"22日","㍮":"22点","㏶":"23日","㍯":"23点","㏷":"24日","㍰":"24点","㏸":"25日","㏹":"26日","㏺":"27日","㏻":"28日","㏼":"29日","㏴":"2l日","㍭":"2l点","⒛":"2O.","㏳":"2O日","㍬":"2O点","෩":"෨ා","෯":"෨ී","㏡":"2日","㋁":"2月","㍚":"2点","𝈆":"3","𝟑":"3","𝟛":"3","𝟥":"3","𝟯":"3","𝟹":"3","🯳":"3","Ɜ":"3",Ȝ:"3",Ʒ:"3","Ꝫ":"3","Ⳍ":"3",З:"3",Ӡ:"3","𖼻":"3","𑣊":"3","۳":"٣","𞣉":"٣","૩":"३","③":"➂",Ҙ:"3̦","🄄":"3,","⒊":"3.","㏾":"3l日","㏽":"3O日","㏢":"3日","㋂":"3月","㍛":"3点","𝟒":"4","𝟜":"4","𝟦":"4","𝟰":"4","𝟺":"4","🯴":"4",Ꮞ:"4","𑢯":"4","۴":"٤","૪":"४","④":"➃","🄅":"4,","⒋":"4.",ᔰ:"4·","㏣":"4日","㋃":"4月","㍜":"4点","𝟓":"5","𝟝":"5","𝟧":"5","𝟱":"5","𝟻":"5","🯵":"5",Ƽ:"5","𑢻":"5","⑤":"➄","🄆":"5,","⒌":"5.","㏤":"5日","㋄":"5月","㍝":"5点","𝟔":"6","𝟞":"6","𝟨":"6","𝟲":"6","𝟼":"6","🯶":"6","Ⳓ":"6",б:"6",Ꮾ:"6","𑣕":"6","۶":"٦","𑓖":"৬","⑥":"➅","🄇":"6,","⒍":"6.","㏥":"6日","㋅":"6月","㍞":"6点","𝈒":"7","𝟕":"7","𝟟":"7","𝟩":"7","𝟳":"7","𝟽":"7","🯷":"7","𐓒":"7","𑣆":"7","⑦":"➆","🄈":"7,","⒎":"7.","㏦":"7日","㋆":"7月","㍟":"7点","ଃ":"8","৪":"8","੪":"8","𞣋":"8","𝟖":"8","𝟠":"8","𝟪":"8","𝟴":"8","𝟾":"8","🯸":"8",ȣ:"8",Ȣ:"8","𐌚":"8","૮":"८","⑧":"➇","🄉":"8,","⒏":"8.","㏧":"8日","㋇":"8月","㍠":"8点","੧":"9","୨":"9","৭":"9","൭":"9","𝟗":"9","𝟡":"9","𝟫":"9","𝟵":"9","𝟿":"9","🯹":"9","Ꝯ":"9","Ⳋ":"9","𑣌":"9","𑢬":"9","𑣖":"9","१":"٩","𑣤":"٩","۹":"٩","೯":"౯","⑨":"➈","🄊":"9,","⒐":"9.","㏨":"9日","㋈":"9月","㍡":"9点","⍺":"a",a:"a","𝐚":"a","𝑎":"a","𝒂":"a","𝒶":"a","𝓪":"a","𝔞":"a","𝕒":"a","𝖆":"a","𝖺":"a","𝗮":"a","𝘢":"a","𝙖":"a","𝚊":"a",ɑ:"a",α:"a","𝛂":"a","𝛼":"a","𝜶":"a","𝝰":"a","𝞪":"a",а:"a","ⷶ":"ͣ",A:"A","𝐀":"A","𝐴":"A","𝑨":"A","𝒜":"A","𝓐":"A","𝔄":"A","𝔸":"A","𝕬":"A","𝖠":"A","𝗔":"A","𝘈":"A","𝘼":"A","𝙰":"A",Α:"A","𝚨":"A","𝛢":"A","𝜜":"A","𝝖":"A","𝞐":"A",А:"A",Ꭺ:"A",ᗅ:"A","ꓮ":"A","𖽀":"A","𐊠":"A","⍶":"a̲",ǎ:"ă",Ǎ:"Ă",ȧ:"å",Ȧ:"Å",ẚ:"ả","℀":"a/c","℁":"a/s","ꜳ":"aa","Ꜳ":"AA",æ:"ae",ӕ:"ae",Æ:"AE",Ӕ:"AE","ꜵ":"ao","Ꜵ":"AO","🜇":"AR","ꜷ":"au","Ꜷ":"AU","ꜹ":"av","ꜻ":"av","Ꜹ":"AV","Ꜻ":"AV","ꜽ":"ay","Ꜽ":"AY","ꭺ":"ᴀ","∀":"Ɐ","𝈗":"Ɐ",ᗄ:"Ɐ","ꓯ":"Ɐ","𐐟":"Ɒ","𝐛":"b","𝑏":"b","𝒃":"b","𝒷":"b","𝓫":"b","𝔟":"b","𝕓":"b","𝖇":"b","𝖻":"b","𝗯":"b","𝘣":"b","𝙗":"b","𝚋":"b",Ƅ:"b",Ь:"b",Ꮟ:"b",ᑲ:"b",ᖯ:"b",B:"B",ℬ:"B","𝐁":"B","𝐵":"B","𝑩":"B","𝓑":"B","𝔅":"B","𝔹":"B","𝕭":"B","𝖡":"B","𝗕":"B","𝘉":"B","𝘽":"B","𝙱":"B","Ꞵ":"B",Β:"B","𝚩":"B","𝛣":"B","𝜝":"B","𝝗":"B","𝞑":"B",В:"B",Ᏼ:"B",ᗷ:"B","ꓐ":"B","𐊂":"B","𐊡":"B","𐌁":"B",ɓ:"b̔",ᑳ:"ḃ",ƃ:"b̄",Ƃ:"b̄",Б:"b̄",ƀ:"b̵",ҍ:"b̵",Ҍ:"b̵",ѣ:"b̵",Ѣ:"b̵",ᑿ:"b·",ᒁ:"ḃ·",ᒈ:"b'",Ы:"bl",в:"ʙ","ᏼ":"ʙ",c:"c","ⅽ":"c","𝐜":"c","𝑐":"c","𝒄":"c","𝒸":"c","𝓬":"c","𝔠":"c","𝕔":"c","𝖈":"c","𝖼":"c","𝗰":"c","𝘤":"c","𝙘":"c","𝚌":"c","ᴄ":"c",ϲ:"c","ⲥ":"c",с:"c","ꮯ":"c","𐐽":"c","ⷭ":"ͨ","🝌":"C","𑣲":"C","𑣩":"C",C:"C","Ⅽ":"C",ℂ:"C",ℭ:"C","𝐂":"C","𝐶":"C","𝑪":"C","𝒞":"C","𝓒":"C","𝕮":"C","𝖢":"C","𝗖":"C","𝘊":"C","𝘾":"C","𝙲":"C","Ϲ":"C","Ⲥ":"C",С:"C",Ꮯ:"C","ꓚ":"C","𐊢":"C","𐌂":"C","𐐕":"C","𐔜":"C","¢":"c̸","ȼ":"c̸","₡":"C⃫","🅮":"C⃠",ç:"c̦",ҫ:"c̦",Ç:"C̦",Ҫ:"C̦",Ƈ:"C'","℅":"c/o","℆":"c/u","🅭":"㏄ ⃝","⋴":"ꞓ",ɛ:"ꞓ",ε:"ꞓ","ϵ":"ꞓ","𝛆":"ꞓ","𝛜":"ꞓ","𝜀":"ꞓ","𝜖":"ꞓ","𝜺":"ꞓ","𝝐":"ꞓ","𝝴":"ꞓ","𝞊":"ꞓ","𝞮":"ꞓ","𝟄":"ꞓ","ⲉ":"ꞓ",є:"ꞓ","ԑ":"ꞓ","ꮛ":"ꞓ","𑣎":"ꞓ","𐐩":"ꞓ","€":"Ꞓ","Ⲉ":"Ꞓ",Є:"Ꞓ","⍷":"ꞓ̲","ͽ":"ꜿ","Ͽ":"Ꜿ","ⅾ":"d","ⅆ":"d","𝐝":"d","𝑑":"d","𝒅":"d","𝒹":"d","𝓭":"d","𝔡":"d","𝕕":"d","𝖉":"d","𝖽":"d","𝗱":"d","𝘥":"d","𝙙":"d","𝚍":"d","ԁ":"d",Ꮷ:"d",ᑯ:"d","ꓒ":"d","Ⅾ":"D","ⅅ":"D","𝐃":"D","𝐷":"D","𝑫":"D","𝒟":"D","𝓓":"D","𝔇":"D","𝔻":"D","𝕯":"D","𝖣":"D","𝗗":"D","𝘋":"D","𝘿":"D","𝙳":"D",Ꭰ:"D",ᗞ:"D",ᗪ:"D","ꓓ":"D",ɗ:"d̔",ɖ:"d̨",ƌ:"d̄",đ:"d̵",Đ:"D̵",Ð:"D̵",Ɖ:"D̵","₫":"ḏ̵","ꝺ":"Ꝺ",ᑻ:"d·",ᒇ:"d'",ʤ:"dȝ",dz:"dz",ʣ:"dz",Dz:"Dz",DZ:"DZ",dž:"dž",Dž:"Dž",DŽ:"DŽ",ʥ:"dʑ","ꭰ":"ᴅ","⸹":"ẟ",δ:"ẟ","𝛅":"ẟ","𝛿":"ẟ","𝜹":"ẟ","𝝳":"ẟ","𝞭":"ẟ",ծ:"ẟ",ᕷ:"ẟ","℮":"e",e:"e",ℯ:"e","ⅇ":"e","𝐞":"e","𝑒":"e","𝒆":"e","𝓮":"e","𝔢":"e","𝕖":"e","𝖊":"e","𝖾":"e","𝗲":"e","𝘦":"e","𝙚":"e","𝚎":"e","ꬲ":"e",е:"e",ҽ:"e","ⷷ":"ͤ","⋿":"E",E:"E",ℰ:"E","𝐄":"E","𝐸":"E","𝑬":"E","𝓔":"E","𝔈":"E","𝔼":"E","𝕰":"E","𝖤":"E","𝗘":"E","𝘌":"E","𝙀":"E","𝙴":"E",Ε:"E","𝚬":"E","𝛦":"E","𝜠":"E","𝝚":"E","𝞔":"E",Е:"E","ⴹ":"E",Ꭼ:"E","ꓰ":"E","𑢦":"E","𑢮":"E","𐊆":"E",ě:"ĕ",Ě:"Ĕ","ɇ":"e̸","Ɇ":"E̸",ҿ:"ę","ꭼ":"ᴇ",ə:"ǝ",ә:"ǝ","∃":"Ǝ","ⴺ":"Ǝ","ꓱ":"Ǝ",ɚ:"ǝ˞","ᴔ":"ǝo","ꭁ":"ǝo̸","ꭂ":"ǝo̵",Ә:"Ə","𝈡":"Ɛ",ℇ:"Ɛ","Ԑ":"Ɛ",Ꮛ:"Ɛ","𖼭":"Ɛ","𐐁":"Ɛ","ᶟ":"ᵋ","ᴈ":"ɜ",з:"ɜ",ҙ:"ɜ̦","𐑂":"ɞ","ꞝ":"ʚ","𐐪":"ʚ","𝐟":"f","𝑓":"f","𝒇":"f","𝒻":"f","𝓯":"f","𝔣":"f","𝕗":"f","𝖋":"f","𝖿":"f","𝗳":"f","𝘧":"f","𝙛":"f","𝚏":"f","ꬵ":"f","ꞙ":"f",ſ:"f","ẝ":"f",ք:"f","𝈓":"F",ℱ:"F","𝐅":"F","𝐹":"F","𝑭":"F","𝓕":"F","𝔉":"F","𝔽":"F","𝕱":"F","𝖥":"F","𝗙":"F","𝘍":"F","𝙁":"F","𝙵":"F","Ꞙ":"F",Ϝ:"F","𝟊":"F",ᖴ:"F","ꓝ":"F","𑣂":"F","𑢢":"F","𐊇":"F","𐊥":"F","𐔥":"F",ƒ:"f̦",Ƒ:"F̦","ᵮ":"f̴","℻":"FAX",ff:"ff",ffi:"ffi",ffl:"ffl",fi:"fi",fl:"fl",ʩ:"fŋ",ᖵ:"Ⅎ","ꓞ":"Ⅎ","𝈰":"ꟻ",ᖷ:"ꟻ",g:"g",ℊ:"g","𝐠":"g","𝑔":"g","𝒈":"g","𝓰":"g","𝔤":"g","𝕘":"g","𝖌":"g","𝗀":"g","𝗴":"g","𝘨":"g","𝙜":"g","𝚐":"g",ɡ:"g","ᶃ":"g",ƍ:"g",ց:"g","𝐆":"G","𝐺":"G","𝑮":"G","𝒢":"G","𝓖":"G","𝔊":"G","𝔾":"G","𝕲":"G","𝖦":"G","𝗚":"G","𝘎":"G","𝙂":"G","𝙶":"G","Ԍ":"G",Ꮐ:"G",Ᏻ:"G","ꓖ":"G","ᶢ":"ᵍ",ɠ:"g̔",ǧ:"ğ",Ǧ:"Ğ",ǵ:"ģ",ǥ:"g̵",Ǥ:"G̵",Ɠ:"G'","ԍ":"ɢ","ꮐ":"ɢ","ᏻ":"ɢ",h:"h",ℎ:"h","𝐡":"h","𝒉":"h","𝒽":"h","𝓱":"h","𝔥":"h","𝕙":"h","𝖍":"h","𝗁":"h","𝗵":"h","𝘩":"h","𝙝":"h","𝚑":"h",һ:"h",հ:"h",Ꮒ:"h",H:"H",ℋ:"H",ℌ:"H",ℍ:"H","𝐇":"H","𝐻":"H","𝑯":"H","𝓗":"H","𝕳":"H","𝖧":"H","𝗛":"H","𝘏":"H","𝙃":"H","𝙷":"H",Η:"H","𝚮":"H","𝛨":"H","𝜢":"H","𝝜":"H","𝞖":"H","Ⲏ":"H",Н:"H",Ꮋ:"H",ᕼ:"H","ꓧ":"H","𐋏":"H","ᵸ":"ᴴ",ɦ:"h̔","ꚕ":"h̔",Ᏺ:"h̔","Ⱨ":"H̩",Ң:"H̩",ħ:"h̵",ℏ:"h̵",ћ:"h̵",Ħ:"H̵","Ӊ":"H̦",Ӈ:"H̦",н:"ʜ","ꮋ":"ʜ",ң:"ʜ̩","ӊ":"ʜ̦",ӈ:"ʜ̦","Ԋ":"Ƕ","ꮀ":"ⱶ","Ͱ":"Ⱶ",Ꭸ:"Ⱶ",Ꮀ:"Ⱶ","ꚱ":"Ⱶ","ꞕ":"ꜧ","˛":"i","⍳":"i",i:"i","ⅰ":"i",ℹ:"i","ⅈ":"i","𝐢":"i","𝑖":"i","𝒊":"i","𝒾":"i","𝓲":"i","𝔦":"i","𝕚":"i","𝖎":"i","𝗂":"i","𝗶":"i","𝘪":"i","𝙞":"i","𝚒":"i",ı:"i","𝚤":"i",ɪ:"i",ɩ:"i",ι:"i",ι:"i",ͺ:"i","𝛊":"i","𝜄":"i","𝜾":"i","𝝸":"i","𝞲":"i",і:"i","ꙇ":"i","ӏ":"i","ꭵ":"i",Ꭵ:"i","𑣃":"i","ⓛ":"Ⓘ","⍸":"i̲",ǐ:"ĭ",Ǐ:"Ĭ",ɨ:"i̵","ᵻ":"i̵","ᵼ":"i̵","ⅱ":"ii","ⅲ":"iii",ij:"ij","ⅳ":"iv","ⅸ":"ix",j:"j","ⅉ":"j","𝐣":"j","𝑗":"j","𝒋":"j","𝒿":"j","𝓳":"j","𝔧":"j","𝕛":"j","𝖏":"j","𝗃":"j","𝗷":"j","𝘫":"j","𝙟":"j","𝚓":"j",ϳ:"j",ј:"j",J:"J","𝐉":"J","𝐽":"J","𝑱":"J","𝒥":"J","𝓙":"J","𝔍":"J","𝕁":"J","𝕵":"J","𝖩":"J","𝗝":"J","𝘑":"J","𝙅":"J","𝙹":"J","Ʝ":"J","Ϳ":"J",Ј:"J",Ꭻ:"J",ᒍ:"J","ꓙ":"J","ɉ":"j̵","Ɉ":"J̵",ᒙ:"J·","𝚥":"ȷ",յ:"ȷ","ꭻ":"ᴊ","𝐤":"k","𝑘":"k","𝒌":"k","𝓀":"k","𝓴":"k","𝔨":"k","𝕜":"k","𝖐":"k","𝗄":"k","𝗸":"k","𝘬":"k","𝙠":"k","𝚔":"k",K:"K",K:"K","𝐊":"K","𝐾":"K","𝑲":"K","𝒦":"K","𝓚":"K","𝔎":"K","𝕂":"K","𝕶":"K","𝖪":"K","𝗞":"K","𝘒":"K","𝙆":"K","𝙺":"K",Κ:"K","𝚱":"K","𝛫":"K","𝜥":"K","𝝟":"K","𝞙":"K","Ⲕ":"K",К:"K",Ꮶ:"K",ᛕ:"K","ꓗ":"K","𐔘":"K",ƙ:"k̔","Ⱪ":"K̩",Қ:"K̩","₭":"K̵","Ꝁ":"K̵",Ҟ:"K̵",Ƙ:"K'","׀":"l","|":"l","∣":"l","⏽":"l","│":"l","١":"l","۱":"l","𐌠":"l","𞣇":"l","𝟏":"l","𝟙":"l","𝟣":"l","𝟭":"l","𝟷":"l","🯱":"l",I:Iq,I:"l","Ⅰ":"l",ℐ:"l",ℑ:"l","𝐈":"l","𝐼":"l","𝑰":"l","𝓘":"l","𝕀":"l","𝕴":"l","𝖨":"l","𝗜":"l","𝘐":"l","𝙄":"l","𝙸":"l",Ɩ:"l",l:"l","ⅼ":"l",ℓ:"l","𝐥":"l","𝑙":"l","𝒍":"l","𝓁":"l","𝓵":"l","𝔩":"l","𝕝":"l","𝖑":"l","𝗅":"l","𝗹":"l","𝘭":"l","𝙡":"l","𝚕":"l",ǀ:"l",Ι:"l","𝚰":"l","𝛪":"l","𝜤":"l","𝝞":"l","𝞘":"l","Ⲓ":"l",І:"l",Ӏ:"l",ו:"l",ן:"l",ا:"l","𞸀":"l","𞺀":"l",ﺎ:"l",ﺍ:"l","ߊ":"l","ⵏ":"l",ᛁ:"l","ꓲ":"l","𖼨":"l","𐊊":"l","𐌉":"l","𝈪":"L","Ⅼ":"L",ℒ:"L","𝐋":"L","𝐿":"L","𝑳":"L","𝓛":"L","𝔏":"L","𝕃":"L","𝕷":"L","𝖫":"L","𝗟":"L","𝘓":"L","𝙇":"L","𝙻":"L","Ⳑ":"L",Ꮮ:"L",ᒪ:"L","ꓡ":"L","𖼖":"L","𑢣":"L","𑢲":"L","𐐛":"L","𐔦":"L",ﴼ:"l̋",ﴽ:"l̋",ł:"l̸",Ł:"L̸",ɭ:"l̨",Ɨ:"l̵",ƚ:"l̵",ɫ:"l̴",إ:"lٕ",ﺈ:"lٕ",ﺇ:"lٕ",ٳ:"lٕ",ŀ:"l·",Ŀ:"l·",ᒷ:"l·","🄂":"l,","⒈":"l.",ױ:"l'","⒓":"l2.","㏫":"l2日","㋋":"l2月","㍤":"l2点","⒔":"l3.","㏬":"l3日","㍥":"l3点","⒕":"l4.","㏭":"l4日","㍦":"l4点","⒖":"l5.","㏮":"l5日","㍧":"l5点","⒗":"l6.","㏯":"l6日","㍨":"l6点","⒘":"l7.","㏰":"l7日","㍩":"l7点","⒙":"l8.","㏱":"l8日","㍪":"l8点","⒚":"l9.","㏲":"l9日","㍫":"l9点",lj:"lj",IJ:"lJ",Lj:"Lj",LJ:"LJ","‖":"ll","∥":"ll","Ⅱ":"ll",ǁ:"ll",װ:"ll","𐆙":"l̵l̵","⒒":"ll.","Ⅲ":"lll","𐆘":"l̵l̵S̵","㏪":"ll日","㋊":"ll月","㍣":"ll点",Ю:"lO","⒑":"lO.","㏩":"lO日","㋉":"lO月","㍢":"lO点",ʪ:"ls","₶":"lt","Ⅳ":"lV","Ⅸ":"lX",ɮ:"lȝ",ʫ:"lz",أ:"lٴ",ﺄ:"lٴ",ﺃ:"lٴ",ٲ:"lٴ",ٵ:"lٴ",ﷳ:"lكبر",ﷲ:"lللّٰo","㏠":"l日","㋀":"l月","㍙":"l点","ⳑ":"ʟ","ꮮ":"ʟ","𐑃":"ʟ",M:"M","Ⅿ":"M",ℳ:"M","𝐌":"M","𝑀":"M","𝑴":"M","𝓜":"M","𝔐":"M","𝕄":"M","𝕸":"M","𝖬":"M","𝗠":"M","𝘔":"M","𝙈":"M","𝙼":"M",Μ:"M","𝚳":"M","𝛭":"M","𝜧":"M","𝝡":"M","𝞛":"M","Ϻ":"M","Ⲙ":"M",М:"M",Ꮇ:"M",ᗰ:"M",ᛖ:"M","ꓟ":"M","𐊰":"M","𐌑":"M","Ӎ":"M̦","🝫":"MB","ⷨ":"ᷟ","𝐧":"n","𝑛":"n","𝒏":"n","𝓃":"n","𝓷":"n","𝔫":"n","𝕟":"n","𝖓":"n","𝗇":"n","𝗻":"n","𝘯":"n","𝙣":"n","𝚗":"n",ո:"n",ռ:"n",N:"N",ℕ:"N","𝐍":"N","𝑁":"N","𝑵":"N","𝒩":"N","𝓝":"N","𝔑":"N","𝕹":"N","𝖭":"N","𝗡":"N","𝘕":"N","𝙉":"N","𝙽":"N",Ν:"N","𝚴":"N","𝛮":"N","𝜨":"N","𝝢":"N","𝞜":"N","Ⲛ":"N","ꓠ":"N","𐔓":"N","𐆎":"N̊",ɳ:"n̨",ƞ:"n̩",η:"n̩","𝛈":"n̩","𝜂":"n̩","𝜼":"n̩","𝝶":"n̩","𝞰":"n̩",Ɲ:"N̦","ᵰ":"n̴",nj:"nj",Nj:"Nj",NJ:"NJ","№":"No","ͷ":"ᴎ",и:"ᴎ","𐑍":"ᴎ",ņ:"ɲ","ం":"o","ಂ":"o","ം":"o","ං":"o","०":"o","੦":"o","૦":"o","௦":"o","౦":"o","೦":"o","൦":"o","๐":"o","໐":"o","၀":"o","٥":"o","۵":"o",o:"o",ℴ:"o","𝐨":"o","𝑜":"o","𝒐":"o","𝓸":"o","𝔬":"o","𝕠":"o","𝖔":"o","𝗈":"o","𝗼":"o","𝘰":"o","𝙤":"o","𝚘":"o","ᴏ":"o","ᴑ":"o","ꬽ":"o",ο:"o","𝛐":"o","𝜊":"o","𝝄":"o","𝝾":"o","𝞸":"o",σ:"o","𝛔":"o","𝜎":"o","𝝈":"o","𝞂":"o","𝞼":"o","ⲟ":"o",о:"o","ჿ":"o",օ:"o",ס:"o",ه:"o","𞸤":"o","𞹤":"o","𞺄":"o",ﻫ:"o",ﻬ:"o",ﻪ:"o",ﻩ:"o",ھ:"o",ﮬ:"o",ﮭ:"o",ﮫ:"o",ﮪ:"o",ہ:"o",ﮨ:"o",ﮩ:"o",ﮧ:"o",ﮦ:"o",ە:"o",ഠ:"o",ဝ:"o","𐓪":"o","𑣈":"o","𑣗":"o","𐐬":"o","߀":"O","০":"O","୦":"O","〇":"O","𑓐":"O","𑣠":"O","𝟎":"O","𝟘":"O","𝟢":"O","𝟬":"O","𝟶":"O","🯰":"O",O:"O","𝐎":"O","𝑂":"O","𝑶":"O","𝒪":"O","𝓞":"O","𝔒":"O","𝕆":"O","𝕺":"O","𝖮":"O","𝗢":"O","𝘖":"O","𝙊":"O","𝙾":"O",Ο:"O","𝚶":"O","𝛰":"O","𝜪":"O","𝝤":"O","𝞞":"O","Ⲟ":"O",О:"O",Օ:"O","ⵔ":"O",ዐ:"O",ଠ:"O","𐓂":"O","ꓳ":"O","𑢵":"O","𐊒":"O","𐊫":"O","𐐄":"O","𐔖":"O","⁰":"º","ᵒ":"º",ǒ:"ŏ",Ǒ:"Ŏ","ۿ":"ô",Ő:"Ö",ø:"o̸","ꬾ":"o̸",Ø:"O̸","ⵁ":"O̸",Ǿ:"Ó̸",ɵ:"o̵","ꝋ":"o̵",ө:"o̵",ѳ:"o̵","ꮎ":"o̵","ꮻ":"o̵","⊖":"O̵","⊝":"O̵","⍬":"O̵","𝈚":"O̵","🜔":"O̵",Ɵ:"O̵","Ꝋ":"O̵",θ:"O̵",ϑ:"O̵","𝛉":"O̵","𝛝":"O̵","𝜃":"O̵","𝜗":"O̵","𝜽":"O̵","𝝑":"O̵","𝝷":"O̵","𝞋":"O̵","𝞱":"O̵","𝟅":"O̵",Θ:"O̵","ϴ":"O̵","𝚯":"O̵","𝚹":"O̵","𝛩":"O̵","𝛳":"O̵","𝜣":"O̵","𝜭":"O̵","𝝝":"O̵","𝝧":"O̵","𝞗":"O̵","𝞡":"O̵",Ө:"O̵",Ѳ:"O̵","ⴱ":"O̵",Ꮎ:"O̵",Ꮻ:"O̵","ꭴ":"ơ",ﳙ:"oٰ","🄁":"O,","🄀":"O.",ơ:"o'",Ơ:"O'",Ꭴ:"O'","%":"º/₀","٪":"º/₀","⁒":"º/₀","‰":"º/₀₀","؉":"º/₀₀","‱":"º/₀₀₀","؊":"º/₀₀₀",œ:"oe",Œ:"OE",ɶ:"oᴇ","∞":"oo","ꝏ":"oo","ꚙ":"oo","Ꝏ":"OO","Ꚙ":"OO",ﳗ:"oج",ﱑ:"oج",ﳘ:"oم",ﱒ:"oم",ﶓ:"oمج",ﶔ:"oمم",ﱓ:"oى",ﱔ:"oى","ൟ":"oരo",တ:"oာ","㍘":"O点","ↄ":"ɔ","ᴐ":"ɔ","ͻ":"ɔ","𐑋":"ɔ","Ↄ":"Ɔ","Ͻ":"Ɔ","ꓛ":"Ɔ","𐐣":"Ɔ","ꬿ":"ɔ̸","ꭢ":"ɔe","𐐿":"ɷ","⍴":"p",p:"p","𝐩":"p","𝑝":"p","𝒑":"p","𝓅":"p","𝓹":"p","𝔭":"p","𝕡":"p","𝖕":"p","𝗉":"p","𝗽":"p","𝘱":"p","𝙥":"p","𝚙":"p",ρ:"p",ϱ:"p","𝛒":"p","𝛠":"p","𝜌":"p","𝜚":"p","𝝆":"p","𝝔":"p","𝞀":"p","𝞎":"p","𝞺":"p","𝟈":"p","ⲣ":"p",р:"p",P:"P",ℙ:"P","𝐏":"P","𝑃":"P","𝑷":"P","𝒫":"P","𝓟":"P","𝔓":"P","𝕻":"P","𝖯":"P","𝗣":"P","𝘗":"P","𝙋":"P","𝙿":"P",Ρ:"P","𝚸":"P","𝛲":"P","𝜬":"P","𝝦":"P","𝞠":"P","Ⲣ":"P",Р:"P",Ꮲ:"P",ᑭ:"P","ꓑ":"P","𐊕":"P",ƥ:"p̔","ᵽ":"p̵",ᑷ:"p·",ᒆ:"P'","ᴩ":"ᴘ","ꮲ":"ᴘ",φ:"ɸ",ϕ:"ɸ","𝛗":"ɸ","𝛟":"ɸ","𝜑":"ɸ","𝜙":"ɸ","𝝋":"ɸ","𝝓":"ɸ","𝞅":"ɸ","𝞍":"ɸ","𝞿":"ɸ","𝟇":"ɸ","ⲫ":"ɸ",ф:"ɸ","𝐪":"q","𝑞":"q","𝒒":"q","𝓆":"q","𝓺":"q","𝔮":"q","𝕢":"q","𝖖":"q","𝗊":"q","𝗾":"q","𝘲":"q","𝙦":"q","𝚚":"q","ԛ":"q",գ:"q",զ:"q",ℚ:"Q","𝐐":"Q","𝑄":"Q","𝑸":"Q","𝒬":"Q","𝓠":"Q","𝔔":"Q","𝕼":"Q","𝖰":"Q","𝗤":"Q","𝘘":"Q","𝙌":"Q","𝚀":"Q","ⵕ":"Q",ʠ:"q̔","🜀":"QE","ᶐ":"ɋ","ᴋ":"ĸ",κ:"ĸ",ϰ:"ĸ","𝛋":"ĸ","𝛞":"ĸ","𝜅":"ĸ","𝜘":"ĸ","𝜿":"ĸ","𝝒":"ĸ","𝝹":"ĸ","𝞌":"ĸ","𝞳":"ĸ","𝟆":"ĸ","ⲕ":"ĸ",к:"ĸ","ꮶ":"ĸ",қ:"ĸ̩",ҟ:"ĸ̵","𝐫":"r","𝑟":"r","𝒓":"r","𝓇":"r","𝓻":"r","𝔯":"r","𝕣":"r","𝖗":"r","𝗋":"r","𝗿":"r","𝘳":"r","𝙧":"r","𝚛":"r","ꭇ":"r","ꭈ":"r","ᴦ":"r","ⲅ":"r",г:"r","ꮁ":"r","𝈖":"R",ℛ:"R",ℜ:"R",ℝ:"R","𝐑":"R","𝑅":"R","𝑹":"R","𝓡":"R","𝕽":"R","𝖱":"R","𝗥":"R","𝘙":"R","𝙍":"R","𝚁":"R",Ʀ:"R",Ꭱ:"R",Ꮢ:"R","𐒴":"R",ᖇ:"R","ꓣ":"R","𖼵":"R",ɽ:"r̨",ɼ:"r̩","ɍ":"r̵",ғ:"r̵","ᵲ":"r̴",ґ:"r'","𑣣":"rn",m:xq,"ⅿ":"rn","𝐦":"rn","𝑚":"rn","𝒎":"rn","𝓂":"rn","𝓶":"rn","𝔪":"rn","𝕞":"rn","𝖒":"rn","𝗆":"rn","𝗺":"rn","𝘮":"rn","𝙢":"rn","𝚖":"rn","𑜀":"rn","₥":"rn̸",ɱ:"rn̦","ᵯ":"rn̴","₨":"Rs","ꭱ":"ʀ","ꮢ":"ʀ",я:"ᴙ","ᵳ":"ɾ̴","℩":"ɿ",s:"s","𝐬":"s","𝑠":"s","𝒔":"s","𝓈":"s","𝓼":"s","𝔰":"s","𝕤":"s","𝖘":"s","𝗌":"s","𝘀":"s","𝘴":"s","𝙨":"s","𝚜":"s","ꜱ":"s",ƽ:"s",ѕ:"s","ꮪ":"s","𑣁":"s","𐑈":"s",S:"S","𝐒":"S","𝑆":"S","𝑺":"S","𝒮":"S","𝓢":"S","𝔖":"S","𝕊":"S","𝕾":"S","𝖲":"S","𝗦":"S","𝘚":"S","𝙎":"S","𝚂":"S",Ѕ:"S",Տ:"S",Ꮥ:"S",Ꮪ:"S","ꓢ":"S","𖼺":"S","𐊖":"S","𐐠":"S",ʂ:"s̨","ᵴ":"s̴","ꞵ":"ß",β:"ß",ϐ:"ß","𝛃":"ß","𝛽":"ß","𝜷":"ß","𝝱":"ß","𝞫":"ß",Ᏸ:"ß","🝜":"sss",st:"st","∫":"ʃ","ꭍ":"ʃ","∑":"Ʃ","⅀":"Ʃ",Σ:"Ʃ","𝚺":"Ʃ","𝛴":"Ʃ","𝜮":"Ʃ","𝝨":"Ʃ","𝞢":"Ʃ","ⵉ":"Ʃ","∬":"ʃʃ","∭":"ʃʃʃ","⨌":"ʃʃʃʃ","𝐭":"t","𝑡":"t","𝒕":"t","𝓉":"t","𝓽":"t","𝔱":"t","𝕥":"t","𝖙":"t","𝗍":"t","𝘁":"t","𝘵":"t","𝙩":"t","𝚝":"t","⊤":"T","⟙":"T","🝨":"T",T:"T","𝐓":"T","𝑇":"T","𝑻":"T","𝒯":"T","𝓣":"T","𝔗":"T","𝕋":"T","𝕿":"T","𝖳":"T","𝗧":"T","𝘛":"T","𝙏":"T","𝚃":"T",Τ:"T","𝚻":"T","𝛵":"T","𝜯":"T","𝝩":"T","𝞣":"T","Ⲧ":"T",Т:"T",Ꭲ:"T","ꓔ":"T","𖼊":"T","𑢼":"T","𐊗":"T","𐊱":"T","𐌕":"T",ƭ:"t̔","⍡":"T̈","Ⱦ":"T̸",Ț:"Ţ",Ʈ:"T̨",Ҭ:"T̩","₮":"T⃫",ŧ:"t̵",Ŧ:"T̵","ᵵ":"t̴",Ⴀ:"Ꞇ","Ꜩ":"T3",ʨ:"tɕ","℡":"TEL","ꝷ":"tf",ʦ:"ts",ʧ:"tʃ","ꜩ":"tȝ",τ:"ᴛ","𝛕":"ᴛ","𝜏":"ᴛ","𝝉":"ᴛ","𝞃":"ᴛ","𝞽":"ᴛ",т:"ᴛ","ꭲ":"ᴛ",ҭ:"ᴛ̩",ţ:"ƫ",ț:"ƫ",Ꮏ:"ƫ","𝐮":"u","𝑢":"u","𝒖":"u","𝓊":"u","𝓾":"u","𝔲":"u","𝕦":"u","𝖚":"u","𝗎":"u","𝘂":"u","𝘶":"u","𝙪":"u","𝚞":"u","ꞟ":"u","ᴜ":"u","ꭎ":"u","ꭒ":"u",ʋ:"u",υ:"u","𝛖":"u","𝜐":"u","𝝊":"u","𝞄":"u","𝞾":"u",ս:"u","𐓶":"u","𑣘":"u","∪":"U","⋃":"U","𝐔":"U","𝑈":"U","𝑼":"U","𝒰":"U","𝓤":"U","𝔘":"U","𝕌":"U","𝖀":"U","𝖴":"U","𝗨":"U","𝘜":"U","𝙐":"U","𝚄":"U",Ս:"U",ሀ:"U","𐓎":"U",ᑌ:"U","ꓴ":"U","𖽂":"U","𑢸":"U",ǔ:"ŭ",Ǔ:"Ŭ","ᵾ":"u̵","ꮜ":"u̵","Ʉ":"U̵",Ꮜ:"U̵",ᑘ:"U·",ᑧ:"U'","ᵫ":"ue","ꭣ":"uo",ṃ:"ꭑ",պ:"ɰ",ሣ:"ɰ","℧":"Ʊ",ᘮ:"Ʊ",ᘴ:"Ʊ","ᵿ":"ʊ̵","∨":"v","⋁":"v",v:"v","ⅴ":"v","𝐯":"v","𝑣":"v","𝒗":"v","𝓋":"v","𝓿":"v","𝔳":"v","𝕧":"v","𝖛":"v","𝗏":"v","𝘃":"v","𝘷":"v","𝙫":"v","𝚟":"v","ᴠ":"v",ν:"v","𝛎":"v","𝜈":"v","𝝂":"v","𝝼":"v","𝞶":"v",ѵ:"v",ט:"v","𑜆":"v","ꮩ":"v","𑣀":"v","𝈍":"V","٧":"V","۷":"V","Ⅴ":"V","𝐕":"V","𝑉":"V","𝑽":"V","𝒱":"V","𝓥":"V","𝔙":"V","𝕍":"V","𝖁":"V","𝖵":"V","𝗩":"V","𝘝":"V","𝙑":"V","𝚅":"V",Ѵ:"V","ⴸ":"V",Ꮩ:"V",ᐯ:"V","ꛟ":"V","ꓦ":"V","𖼈":"V","𑢠":"V","𐔝":"V","𐆗":"V̵",ᐻ:"V·","🝬":"VB","ⅵ":"vi","ⅶ":"vii","ⅷ":"viii","Ⅵ":"Vl","Ⅶ":"Vll","Ⅷ":"Vlll","🜈":"Vᷤ","ᴧ":"ʌ","𐓘":"ʌ","٨":"Ʌ","۸":"Ʌ",Λ:"Ʌ","𝚲":"Ʌ","𝛬":"Ʌ","𝜦":"Ʌ","𝝠":"Ʌ","𝞚":"Ʌ",Л:"Ʌ","ⴷ":"Ʌ","𐒰":"Ʌ",ᐱ:"Ʌ","ꛎ":"Ʌ","ꓥ":"Ʌ","𖼽":"Ʌ","𐊍":"Ʌ","Ӆ":"Ʌ̦",ᐽ:"Ʌ·",ɯ:"w","𝐰":"w","𝑤":"w","𝒘":"w","𝓌":"w","𝔀":"w","𝔴":"w","𝕨":"w","𝖜":"w","𝗐":"w","𝘄":"w","𝘸":"w","𝙬":"w","𝚠":"w","ᴡ":"w",ѡ:"w","ԝ":"w",ա:"w","𑜊":"w","𑜎":"w","𑜏":"w","ꮃ":"w","𑣯":"W","𑣦":"W","𝐖":"W","𝑊":"W","𝑾":"W","𝒲":"W","𝓦":"W","𝔚":"W","𝕎":"W","𝖂":"W","𝖶":"W","𝗪":"W","𝘞":"W","𝙒":"W","𝚆":"W","Ԝ":"W",Ꮃ:"W",Ꮤ:"W","ꓪ":"W",ѽ:"w҆҇","𑓅":"ẇ","₩":"W̵","ꝡ":"w̦","ᴍ":"ʍ",м:"ʍ","ꮇ":"ʍ","ӎ":"ʍ̦","᙮":"x","×":"x","⤫":"x","⤬":"x","⨯":"x",x:"x","ⅹ":"x","𝐱":"x","𝑥":"x","𝒙":"x","𝓍":"x","𝔁":"x","𝔵":"x","𝕩":"x","𝖝":"x","𝗑":"x","𝘅":"x","𝘹":"x","𝙭":"x","𝚡":"x",х:"x",ᕁ:"x",ᕽ:"x","ⷯ":"ͯ","᙭":"X","╳":"X","𐌢":"X","𑣬":"X",X:"X","Ⅹ":"X","𝐗":"X","𝑋":"X","𝑿":"X","𝒳":"X","𝓧":"X","𝔛":"X","𝕏":"X","𝖃":"X","𝖷":"X","𝗫":"X","𝘟":"X","𝙓":"X","𝚇":"X","Ꭓ":"X",Χ:"X","𝚾":"X","𝛸":"X","𝜲":"X","𝝬":"X","𝞦":"X","Ⲭ":"X",Х:"X","ⵝ":"X",ᚷ:"X","ꓫ":"X","𐊐":"X","𐊴":"X","𐌗":"X","𐔧":"X","⨰":"ẋ",Ҳ:"X̩","𐆖":"X̵","ⅺ":"xi","ⅻ":"xii","Ⅺ":"Xl","Ⅻ":"Xll",ɣ:"y","ᶌ":"y",y:"y","𝐲":"y","𝑦":"y","𝒚":"y","𝓎":"y","𝔂":"y","𝔶":"y","𝕪":"y","𝖞":"y","𝗒":"y","𝘆":"y","𝘺":"y","𝙮":"y","𝚢":"y",ʏ:"y","ỿ":"y","ꭚ":"y",γ:"y","ℽ":"y","𝛄":"y","𝛾":"y","𝜸":"y","𝝲":"y","𝞬":"y",у:"y",ү:"y",ყ:"y","𑣜":"y",Y:"Y","𝐘":"Y","𝑌":"Y","𝒀":"Y","𝒴":"Y","𝓨":"Y","𝔜":"Y","𝕐":"Y","𝖄":"Y","𝖸":"Y","𝗬":"Y","𝘠":"Y","𝙔":"Y","𝚈":"Y",Υ:"Y",ϒ:"Y","𝚼":"Y","𝛶":"Y","𝜰":"Y","𝝪":"Y","𝞤":"Y","Ⲩ":"Y",У:"Y",Ү:"Y",Ꭹ:"Y",Ꮍ:"Y","ꓬ":"Y","𖽃":"Y","𑢤":"Y","𐊲":"Y",ƴ:"y̔","ɏ":"y̵",ұ:"y̵","¥":"Y̵","Ɏ":"Y̵",Ұ:"Y̵",ʒ:"ȝ","ꝫ":"ȝ","ⳍ":"ȝ",ӡ:"ȝ",ჳ:"ȝ","𝐳":"z","𝑧":"z","𝒛":"z","𝓏":"z","𝔃":"z","𝔷":"z","𝕫":"z","𝖟":"z","𝗓":"z","𝘇":"z","𝘻":"z","𝙯":"z","𝚣":"z","ᴢ":"z","ꮓ":"z","𑣄":"z","𐋵":"Z","𑣥":"Z",Z:"Z",ℤ:"Z",ℨ:"Z","𝐙":"Z","𝑍":"Z","𝒁":"Z","𝒵":"Z","𝓩":"Z","𝖅":"Z","𝖹":"Z","𝗭":"Z","𝘡":"Z","𝙕":"Z","𝚉":"Z",Ζ:"Z","𝚭":"Z","𝛧":"Z","𝜡":"Z","𝝛":"Z","𝞕":"Z",Ꮓ:"Z","ꓜ":"Z","𑢩":"Z",ʐ:"z̨",ƶ:"z̵",Ƶ:"Z̵",ȥ:"z̦",Ȥ:"Z̦","ᵶ":"z̴",ƿ:"þ","ϸ":"þ","Ϸ":"Þ","𐓄":"Þ","⁹":"ꝰ","ᴤ":"ƨ",ϩ:"ƨ","ꙅ":"ƨ",ь:"ƅ","ꮟ":"ƅ",ы:"ƅi","ꭾ":"ɂ",ˤ:"ˁ","ꛍ":"ʡ","⊙":"ʘ","☉":"ʘ","⨀":"ʘ","Ꙩ":"ʘ","ⵙ":"ʘ","𐓃":"ʘ","ℾ":"Γ","𝚪":"Γ","𝛤":"Γ","𝜞":"Γ","𝝘":"Γ","𝞒":"Γ","Ⲅ":"Γ",Г:"Γ",Ꮁ:"Γ",ᒥ:"Γ","𖼇":"Γ",Ғ:"Γ̵",ᒯ:"Γ·",Ґ:"Γ'","∆":"Δ","△":"Δ","🜂":"Δ","𝚫":"Δ","𝛥":"Δ","𝜟":"Δ","𝝙":"Δ","𝞓":"Δ","Ⲇ":"Δ","ⵠ":"Δ",ᐃ:"Δ","𖼚":"Δ","𐊅":"Δ","𐊣":"Δ","⍙":"Δ̲",ᐏ:"Δ·",ᐬ:"Δᐠ","𝟋":"ϝ","𝛇":"ζ","𝜁":"ζ","𝜻":"ζ","𝝵":"ζ","𝞯":"ζ","ⳤ":"ϗ","𝛌":"λ","𝜆":"λ","𝝀":"λ","𝝺":"λ","𝞴":"λ","Ⲗ":"λ","𐓛":"λ",µ:"μ","𝛍":"μ","𝜇":"μ","𝝁":"μ","𝝻":"μ","𝞵":"μ","𝛏":"ξ","𝜉":"ξ","𝝃":"ξ","𝝽":"ξ","𝞷":"ξ","𝚵":"Ξ","𝛯":"Ξ","𝜩":"Ξ","𝝣":"Ξ","𝞝":"Ξ",ϖ:"π","ℼ":"π","𝛑":"π","𝛡":"π","𝜋":"π","𝜛":"π","𝝅":"π","𝝕":"π","𝝿":"π","𝞏":"π","𝞹":"π","𝟉":"π","ᴨ":"π",п:"π","∏":"Π","ℿ":"Π","𝚷":"Π","𝛱":"Π","𝜫":"Π","𝝥":"Π","𝞟":"Π","Ⲡ":"Π",П:"Π","ꛛ":"Π","𐊭":"Ϙ","𐌒":"Ϙ",ϛ:"ς","𝛓":"ς","𝜍":"ς","𝝇":"ς","𝞁":"ς","𝞻":"ς","𝚽":"Φ","𝛷":"Φ","𝜱":"Φ","𝝫":"Φ","𝞥":"Φ","Ⲫ":"Φ",Ф:"Φ",Փ:"Φ",ቀ:"Φ","ᛰ":"Φ","𐊳":"Φ","ꭓ":"χ","ꭕ":"χ","𝛘":"χ","𝜒":"χ","𝝌":"χ","𝞆":"χ","𝟀":"χ","ⲭ":"χ","𝛙":"ψ","𝜓":"ψ","𝝍":"ψ","𝞇":"ψ","𝟁":"ψ",ѱ:"ψ","𐓹":"ψ","𝚿":"Ψ","𝛹":"Ψ","𝜳":"Ψ","𝝭":"Ψ","𝞧":"Ψ","Ⲯ":"Ψ",Ѱ:"Ψ","𐓑":"Ψ",ᛘ:"Ψ","𐊵":"Ψ","⍵":"ω","ꞷ":"ω","𝛚":"ω","𝜔":"ω","𝝎":"ω","𝞈":"ω","𝟂":"ω","ⲱ":"ω","ꙍ":"ω",Ω:"Ω","𝛀":"Ω","𝛺":"Ω","𝜴":"Ω","𝝮":"Ω","𝞨":"Ω",ᘯ:"Ω",ᘵ:"Ω","𐊶":"Ω","⍹":"ω̲",ώ:"ῴ","☰":"Ⲷ","Ⳝ":"Ϭ",җ:"ж̩",Җ:"Ж̩","𝈋":"И","Ͷ":"И","ꚡ":"И","𐐥":"И",Й:"Ѝ","Ҋ":"Ѝ̦",ѝ:"й","ҋ":"й̦","𐒼":"Ӄ","ᴫ":"л","ӆ":"л̦","ꭠ":"љ","𐓫":"ꙩ","ᷮ":"ⷬ","𐓍":"Ћ","𝈂":"Ӿ","𝈢":"Ѡ",Ꮗ:"Ѡ",ᗯ:"Ѡ",Ѽ:"Ѡ҆҇","ᣭ":"Ѡ·","Ꞷ":"Ꙍ",ӌ:"ҷ",Ӌ:"Ҷ",Ҿ:"Ҽ̨","ⲽ":"ш","Ⲽ":"Ш","Ꙑ":"Ъl","℈":"Э","🜁":"Ꙙ","𖼜":"Ꙙ","ꦒ":"ⰿ",և:"եւ",ኔ:"ձ",ﬔ:"մե",ﬕ:"մի",ﬗ:"մխ",ﬓ:"մն","∩":"Ո","⋂":"Ո","𝉅":"Ո",በ:"Ո",ᑎ:"Ո","ꓵ":"Ո",ᑚ:"Ո·",ᑨ:"Ո'",ﬖ:"վն","₽":"Ք","˓":"ՙ",ʿ:"ՙ",ℵ:"א",ﬡ:"א",אָ:"אַ",אּ:"אַ",ﭏ:"אל",ℶ:"ב",ℷ:"ג",ℸ:"ד",ﬢ:"ד",ﬣ:"ה",יּ:"יִ",ﬤ:"כ",ﬥ:"ל",ﬦ:"ם",ﬠ:"ע",ﬧ:"ר",שׂ:"שׁ",שּ:"שׁ",שּׂ:"שּׁ",ﬨ:"ת",ﺀ:"ء","۽":"ء͈",ﺂ:"آ",ﺁ:"آ",ﭑ:"ٱ",ﭐ:"ٱ","𞸁":"ب","𞸡":"ب","𞹡":"ب","𞺁":"ب","𞺡":"ب",ﺑ:"ب",ﺒ:"ب",ﺐ:"ب",ﺏ:"ب","ݑ":"بۛ","ࢶ":"بۢ","ࢡ":"بٔ",ﲠ:"بo",ﳢ:"بo",ﲜ:"بج",ﰅ:"بج",ﲝ:"بح",ﰆ:"بح",ﷂ:"بحى",ﲞ:"بخ",ﰇ:"بخ",ﳒ:"بخ",ﱋ:"بخ",ﶞ:"بخى",ﱪ:"بر",ﱫ:"بز",ﲟ:"بم",ﳡ:"بم",ﱬ:"بم",ﰈ:"بم",ﱭ:"بن",ﱮ:"بى",ﰉ:"بى",ﱯ:"بى",ﰊ:"بى",ﭔ:"ٻ",ﭕ:"ٻ",ﭓ:"ٻ",ﭒ:"ٻ",ې:"ٻ",ﯦ:"ٻ",ﯧ:"ٻ",ﯥ:"ٻ",ﯤ:"ٻ",ﭜ:"ڀ",ﭝ:"ڀ",ﭛ:"ڀ",ﭚ:"ڀ","ࢩ":"ݔ","ݧ":"ݔ","⍥":"ة",ö:"ة",ﺔ:"ة",ﺓ:"ة",ۃ:"ة","𞸕":"ت","𞸵":"ت","𞹵":"ت","𞺕":"ت","𞺵":"ت",ﺗ:"ت",ﺘ:"ت",ﺖ:"ت",ﺕ:"ت",ﲥ:"تo",ﳤ:"تo",ﲡ:"تج",ﰋ:"تج",ﵐ:"تجم",ﶠ:"تجى",ﶟ:"تجى",ﲢ:"تح",ﰌ:"تح",ﵒ:"تحج",ﵑ:"تحج",ﵓ:"تحم",ﲣ:"تخ",ﰍ:"تخ",ﵔ:"تخم",ﶢ:"تخى",ﶡ:"تخى",ﱰ:"تر",ﱱ:"تز",ﲤ:"تم",ﳣ:"تم",ﱲ:"تم",ﰎ:"تم",ﵕ:"تمج",ﵖ:"تمح",ﵗ:"تمخ",ﶤ:"تمى",ﶣ:"تمى",ﱳ:"تن",ﱴ:"تى",ﰏ:"تى",ﱵ:"تى",ﰐ:"تى",ﭠ:"ٺ",ﭡ:"ٺ",ﭟ:"ٺ",ﭞ:"ٺ",ﭤ:"ٿ",ﭥ:"ٿ",ﭣ:"ٿ",ﭢ:"ٿ","𞸂":"ج","𞸢":"ج","𞹂":"ج","𞹢":"ج","𞺂":"ج","𞺢":"ج",ﺟ:"ج",ﺠ:"ج",ﺞ:"ج",ﺝ:"ج",ﲧ:"جح",ﰕ:"جح",ﶦ:"جحى",ﶾ:"جحى",ﷻ:"جل جلlلo",ﲨ:"جم",ﰖ:"جم",ﵙ:"جمح",ﵘ:"جمح",ﶧ:"جمى",ﶥ:"جمى",ﴝ:"جى",ﴁ:"جى",ﴞ:"جى",ﴂ:"جى",ﭸ:"ڃ",ﭹ:"ڃ",ﭷ:"ڃ",ﭶ:"ڃ",ﭴ:"ڄ",ﭵ:"ڄ",ﭳ:"ڄ",ﭲ:"ڄ",ﭼ:"چ",ﭽ:"چ",ﭻ:"چ",ﭺ:"چ",ﮀ:"ڇ",ﮁ:"ڇ",ﭿ:"ڇ",ﭾ:"ڇ","𞸇":"ح","𞸧":"ح","𞹇":"ح","𞹧":"ح","𞺇":"ح","𞺧":"ح",ﺣ:"ح",ﺤ:"ح",ﺢ:"ح",ﺡ:"ح",څ:"حۛ",ځ:"حٔ","ݲ":"حٔ",ﲩ:"حج",ﰗ:"حج",ﶿ:"حجى",ﲪ:"حم",ﰘ:"حم",ﵛ:"حمى",ﵚ:"حمى",ﴛ:"حى",ﳿ:"حى",ﴜ:"حى",ﴀ:"حى","𞸗":"خ","𞸷":"خ","𞹗":"خ","𞹷":"خ","𞺗":"خ","𞺷":"خ",ﺧ:"خ",ﺨ:"خ",ﺦ:"خ",ﺥ:"خ",ﲫ:"خج",ﰙ:"خج",ﰚ:"خح",ﲬ:"خم",ﰛ:"خم",ﴟ:"خى",ﴃ:"خى",ﴠ:"خى",ﴄ:"خى","𐋡":"د","𞸃":"د","𞺃":"د","𞺣":"د",ﺪ:"د",ﺩ:"د",ڈ:"دؕ",ﮉ:"دؕ",ﮈ:"دؕ",ڎ:"دۛ",ﮇ:"دۛ",ﮆ:"دۛ","ۮ":"د̂","ࢮ":"د̤̣","𞸘":"ذ","𞺘":"ذ","𞺸":"ذ",ﺬ:"ذ",ﺫ:"ذ",ﱛ:"ذٰ",ڋ:"ڊؕ",ﮅ:"ڌ",ﮄ:"ڌ",ﮃ:"ڍ",ﮂ:"ڍ","𞸓":"ر","𞺓":"ر","𞺳":"ر",ﺮ:"ر",ﺭ:"ر",ڑ:"رؕ",ﮍ:"رؕ",ﮌ:"رؕ",ژ:"رۛ",ﮋ:"رۛ",ﮊ:"رۛ",ڒ:"ر̆","ࢹ":"ر̆̇","ۯ":"ر̂","ݬ":"رٔ",ﱜ:"رٰ",ﷶ:"رسول","﷼":"رىlل","𞸆":"ز","𞺆":"ز","𞺦":"ز",ﺰ:"ز",ﺯ:"ز","ࢲ":"ز̂","ݱ":"ڗؕ","𞸎":"س","𞸮":"س","𞹎":"س","𞹮":"س","𞺎":"س","𞺮":"س",ﺳ:"س",ﺴ:"س",ﺲ:"س",ﺱ:"س",ش:"سۛ","𞸔":"سۛ","𞸴":"سۛ","𞹔":"سۛ","𞹴":"سۛ","𞺔":"سۛ","𞺴":"سۛ",ﺷ:"سۛ",ﺸ:"سۛ",ﺶ:"سۛ",ﺵ:"سۛ","ݾ":"س̂",ﴱ:"سo",ﳨ:"سo",ﴲ:"سۛo",ﳪ:"سۛo",ﲭ:"سج",ﴴ:"سج",ﰜ:"سج",ﴭ:"سۛج",ﴷ:"سۛج",ﴥ:"سۛج",ﴉ:"سۛج",ﵝ:"سجح",ﵞ:"سجى",ﵩ:"سۛجى",ﲮ:"سح",ﴵ:"سح",ﰝ:"سح",ﴮ:"سۛح",ﴸ:"سۛح",ﴦ:"سۛح",ﴊ:"سۛح",ﵜ:"سحج",ﵨ:"سۛحم",ﵧ:"سۛحم",ﶪ:"سۛحى",ﲯ:"سخ",ﴶ:"سخ",ﰞ:"سخ",ﴯ:"سۛخ",ﴹ:"سۛخ",ﴧ:"سۛخ",ﴋ:"سۛخ",ﶨ:"سخى",ﷆ:"سخى",ﴪ:"سر",ﴎ:"سر",ﴩ:"سۛر",ﴍ:"سۛر",ﲰ:"سم",ﳧ:"سم",ﰟ:"سم",ﴰ:"سۛم",ﳩ:"سۛم",ﴨ:"سۛم",ﴌ:"سۛم",ﵡ:"سمج",ﵠ:"سمح",ﵟ:"سمح",ﵫ:"سۛمخ",ﵪ:"سۛمخ",ﵣ:"سمم",ﵢ:"سمم",ﵭ:"سۛمم",ﵬ:"سۛمم",ﴗ:"سى",ﳻ:"سى",ﴘ:"سى",ﳼ:"سى",ﴙ:"سۛى",ﳽ:"سۛى",ﴚ:"سۛى",ﳾ:"سۛى","𐋲":"ص","𞸑":"ص","𞸱":"ص","𞹑":"ص","𞹱":"ص","𞺑":"ص","𞺱":"ص",ﺻ:"ص",ﺼ:"ص",ﺺ:"ص",ﺹ:"ص",ڞ:"صۛ","ࢯ":"ص̤̣",ﲱ:"صح",ﰠ:"صح",ﵥ:"صحح",ﵤ:"صحح",ﶩ:"صحى",ﲲ:"صخ",ﴫ:"صر",ﴏ:"صر",ﷵ:"صلعم",ﷹ:"صلى",ﷰ:"صلى",ﷺ:"صلى lللo علىo وسلم",ﲳ:"صم",ﰡ:"صم",ﷅ:"صمم",ﵦ:"صمم",ﴡ:"صى",ﴅ:"صى",ﴢ:"صى",ﴆ:"صى","𞸙":"ض","𞸹":"ض","𞹙":"ض","𞹹":"ض","𞺙":"ض","𞺹":"ض",ﺿ:"ض",ﻀ:"ض",ﺾ:"ض",ﺽ:"ض",ﲴ:"ضج",ﰢ:"ضج",ﲵ:"ضح",ﰣ:"ضح",ﵮ:"ضحى",ﶫ:"ضحى",ﲶ:"ضخ",ﰤ:"ضخ",ﵰ:"ضخم",ﵯ:"ضخم",ﴬ:"ضر",ﴐ:"ضر",ﲷ:"ضم",ﰥ:"ضم",ﴣ:"ضى",ﴇ:"ضى",ﴤ:"ضى",ﴈ:"ضى","𐋨":"ط","𞸈":"ط","𞹨":"ط","𞺈":"ط","𞺨":"ط",ﻃ:"ط",ﻄ:"ط",ﻂ:"ط",ﻁ:"ط",ڟ:"طۛ",ﲸ:"طح",ﰦ:"طح",ﴳ:"طم",ﴺ:"طم",ﰧ:"طم",ﵲ:"طمح",ﵱ:"طمح",ﵳ:"طمم",ﵴ:"طمى",ﴑ:"طى",ﳵ:"طى",ﴒ:"طى",ﳶ:"طى","𞸚":"ظ","𞹺":"ظ","𞺚":"ظ","𞺺":"ظ",ﻇ:"ظ",ﻈ:"ظ",ﻆ:"ظ",ﻅ:"ظ",ﲹ:"ظم",ﴻ:"ظم",ﰨ:"ظم","؏":"ع","𞸏":"ع","𞸯":"ع","𞹏":"ع","𞹯":"ع","𞺏":"ع","𞺯":"ع",ﻋ:"ع",ﻌ:"ع",ﻊ:"ع",ﻉ:"ع",ﲺ:"عج",ﰩ:"عج",ﷄ:"عجم",ﵵ:"عجم",ﷷ:"علىo",ﲻ:"عم",ﰪ:"عم",ﵷ:"عمم",ﵶ:"عمم",ﵸ:"عمى",ﶶ:"عمى",ﴓ:"عى",ﳷ:"عى",ﴔ:"عى",ﳸ:"عى","𞸛":"غ","𞸻":"غ","𞹛":"غ","𞹻":"غ","𞺛":"غ","𞺻":"غ",ﻏ:"غ",ﻐ:"غ",ﻎ:"غ",ﻍ:"غ",ﲼ:"غج",ﰫ:"غج",ﲽ:"غم",ﰬ:"غم",ﵹ:"غمم",ﵻ:"غمى",ﵺ:"غمى",ﴕ:"غى",ﳹ:"غى",ﴖ:"غى",ﳺ:"غى","𞸐":"ف","𞸰":"ف","𞹰":"ف","𞺐":"ف","𞺰":"ف",ﻓ:"ف",ﻔ:"ف",ﻒ:"ف",ﻑ:"ف",ڧ:"ف",ﲾ:"فج",ﰭ:"فج",ﲿ:"فح",ﰮ:"فح",ﳀ:"فخ",ﰯ:"فخ",ﵽ:"فخم",ﵼ:"فخم",ﳁ:"فم",ﰰ:"فم",ﷁ:"فمى",ﱼ:"فى",ﰱ:"فى",ﱽ:"فى",ﰲ:"فى","𞸞":"ڡ","𞹾":"ڡ","ࢻ":"ڡ","ٯ":"ڡ","𞸟":"ڡ","𞹟":"ڡ","ࢼ":"ڡ",ڤ:"ڡۛ",ﭬ:"ڡۛ",ﭭ:"ڡۛ",ﭫ:"ڡۛ",ﭪ:"ڡۛ",ڨ:"ڡۛ","ࢤ":"ڢۛ",ﭰ:"ڦ",ﭱ:"ڦ",ﭯ:"ڦ",ﭮ:"ڦ","𞸒":"ق","𞸲":"ق","𞹒":"ق","𞹲":"ق","𞺒":"ق","𞺲":"ق",ﻗ:"ق",ﻘ:"ق",ﻖ:"ق",ﻕ:"ق",ﳂ:"قح",ﰳ:"قح",ﷱ:"قلى",ﳃ:"قم",ﰴ:"قم",ﶴ:"قمح",ﵾ:"قمح",ﵿ:"قمم",ﶲ:"قمى",ﱾ:"قى",ﰵ:"قى",ﱿ:"قى",ﰶ:"قى","𞸊":"ك","𞸪":"ك","𞹪":"ك",ﻛ:"ك",ﻜ:"ك",ﻚ:"ك",ﻙ:"ك",ک:"ك",ﮐ:"ك",ﮑ:"ك",ﮏ:"ك",ﮎ:"ك",ڪ:"ك",ڭ:"كۛ",ﯕ:"كۛ",ﯖ:"كۛ",ﯔ:"كۛ",ﯓ:"كۛ","ݣ":"كۛ",ﲀ:"كl",ﰷ:"كl",ﳄ:"كج",ﰸ:"كج",ﳅ:"كح",ﰹ:"كح",ﳆ:"كخ",ﰺ:"كخ",ﳇ:"كل",ﳫ:"كل",ﲁ:"كل",ﰻ:"كل",ﳈ:"كم",ﳬ:"كم",ﲂ:"كم",ﰼ:"كم",ﷃ:"كمم",ﶻ:"كمم",ﶷ:"كمى",ﲃ:"كى",ﰽ:"كى",ﲄ:"كى",ﰾ:"كى","ݢ":"ڬ",ﮔ:"گ",ﮕ:"گ",ﮓ:"گ",ﮒ:"گ","ࢰ":"گ",ڴ:"گۛ",ﮜ:"ڱ",ﮝ:"ڱ",ﮛ:"ڱ",ﮚ:"ڱ",ﮘ:"ڳ",ﮙ:"ڳ",ﮗ:"ڳ",ﮖ:"ڳ","𞸋":"ل","𞸫":"ل","𞹋":"ل","𞺋":"ل","𞺫":"ل",ﻟ:"ل",ﻠ:"ل",ﻞ:"ل",ﻝ:"ل",ڷ:"لۛ",ڵ:"ل̆",ﻼ:"لl",ﻻ:"لl",ﻺ:"لlٕ",ﻹ:"لlٕ",ﻸ:"لlٴ",ﻷ:"لlٴ",ﳍ:"لo",ﻶ:"لآ",ﻵ:"لآ",ﳉ:"لج",ﰿ:"لج",ﶃ:"لجج",ﶄ:"لجج",ﶺ:"لجم",ﶼ:"لجم",ﶬ:"لجى",ﳊ:"لح",ﱀ:"لح",ﶵ:"لحم",ﶀ:"لحم",ﶂ:"لحى",ﶁ:"لحى",ﳋ:"لخ",ﱁ:"لخ",ﶆ:"لخم",ﶅ:"لخم",ﳌ:"لم",ﳭ:"لم",ﲅ:"لم",ﱂ:"لم",ﶈ:"لمح",ﶇ:"لمح",ﶭ:"لمى",ﲆ:"لى",ﱃ:"لى",ﲇ:"لى",ﱄ:"لى","𞸌":"م","𞸬":"م","𞹬":"م","𞺌":"م","𞺬":"م",ﻣ:"م",ﻤ:"م",ﻢ:"م",ﻡ:"م","ࢧ":"مۛ","۾":"م͈",ﲈ:"مl",ﳎ:"مج",ﱅ:"مج",ﶌ:"مجح",ﶒ:"مجخ",ﶍ:"مجم",ﷀ:"مجى",ﳏ:"مح",ﱆ:"مح",ﶉ:"محج",ﶊ:"محم",ﷴ:"محمد",ﶋ:"محى",ﳐ:"مخ",ﱇ:"مخ",ﶎ:"مخج",ﶏ:"مخم",ﶹ:"مخى",ﳑ:"مم",ﲉ:"مم",ﱈ:"مم",ﶱ:"ممى",ﱉ:"مى",ﱊ:"مى","𞸍":"ن","𞸭":"ن","𞹍":"ن","𞹭":"ن","𞺍":"ن","𞺭":"ن",ﻧ:"ن",ﻨ:"ن",ﻦ:"ن",ﻥ:"ن","ݨ":"نؕ","ݩ":"ن̆",ﳖ:"نo",ﳯ:"نo",ﶸ:"نجح",ﶽ:"نجح",ﶘ:"نجم",ﶗ:"نجم",ﶙ:"نجى",ﷇ:"نجى",ﳓ:"نح",ﱌ:"نح",ﶕ:"نحم",ﶖ:"نحى",ﶳ:"نحى",ﳔ:"نخ",ﱍ:"نخ",ﲊ:"نر",ﲋ:"نز",ﳕ:"نم",ﳮ:"نم",ﲌ:"نم",ﱎ:"نم",ﶛ:"نمى",ﶚ:"نمى",ﲍ:"نن",ﲎ:"نى",ﱏ:"نى",ﲏ:"نى",ﱐ:"نى",ۂ:"ۀ",ﮥ:"ۀ",ﮤ:"ۀ","𐋤":"و","𞸅":"و","𞺅":"و","𞺥":"و",ﻮ:"و",ﻭ:"و","ࢱ":"و",ۋ:"وۛ",ﯟ:"وۛ",ﯞ:"وۛ",ۇ:"و̓",ﯘ:"و̓",ﯗ:"و̓",ۆ:"و̆",ﯚ:"و̆",ﯙ:"و̆",ۉ:"و̂",ﯣ:"و̂",ﯢ:"و̂",ۈ:"وٰ",ﯜ:"وٰ",ﯛ:"وٰ",ؤ:"وٴ",ﺆ:"وٴ",ﺅ:"وٴ",ٶ:"وٴ",ٷ:"و̓ٴ",ﯝ:"و̓ٴ",ﷸ:"وسلم",ﯡ:"ۅ",ﯠ:"ۅ","ٮ":"ى","𞸜":"ى","𞹼":"ى",ں:"ى","𞸝":"ى","𞹝":"ى",ﮟ:"ى",ﮞ:"ى","ࢽ":"ى",ﯨ:"ى",ﯩ:"ى",ﻰ:"ى",ﻯ:"ى",ي:"ى","𞸉":"ى","𞸩":"ى","𞹉":"ى","𞹩":"ى","𞺉":"ى","𞺩":"ى",ﻳ:"ى",ﻴ:"ى",ﻲ:"ى",ﻱ:"ى",ی:"ى",ﯾ:"ى",ﯿ:"ى",ﯽ:"ى",ﯼ:"ى",ے:"ى",ﮯ:"ى",ﮮ:"ى",ٹ:"ىؕ",ﭨ:"ىؕ",ﭩ:"ىؕ",ﭧ:"ىؕ",ﭦ:"ىؕ",ڻ:"ىؕ",ﮢ:"ىؕ",ﮣ:"ىؕ",ﮡ:"ىؕ",ﮠ:"ىؕ",پ:"ىۛ",ﭘ:"ىۛ",ﭙ:"ىۛ",ﭗ:"ىۛ",ﭖ:"ىۛ",ث:"ىۛ","𞸖":"ىۛ","𞸶":"ىۛ","𞹶":"ىۛ","𞺖":"ىۛ","𞺶":"ىۛ",ﺛ:"ىۛ",ﺜ:"ىۛ",ﺚ:"ىۛ",ﺙ:"ىۛ",ڽ:"ىۛ",ۑ:"ىۛ","ؿ":"ىۛ","ࢷ":"ىۛۢ","ݖ":"ى̆",ێ:"ى̆","ࢺ":"ى̆̇","ؽ":"ى̂","ࢨ":"ىٔ",ﲐ:"ىٰ",ﱝ:"ىٰ",ﳞ:"ىo",ﳱ:"ىo",ﳦ:"ىۛo",ئ:"ىٴ",ﺋ:"ىٴ",ﺌ:"ىٴ",ﺊ:"ىٴ",ﺉ:"ىٴ",ٸ:"ىٴ",ﯫ:"ىٴl",ﯪ:"ىٴl",ﲛ:"ىٴo",ﳠ:"ىٴo",ﯭ:"ىٴo",ﯬ:"ىٴo",ﯸ:"ىٴٻ",ﯷ:"ىٴٻ",ﯶ:"ىٴٻ",ﲗ:"ىٴج",ﰀ:"ىٴج",ﲘ:"ىٴح",ﰁ:"ىٴح",ﲙ:"ىٴخ",ﱤ:"ىٴر",ﱥ:"ىٴز",ﲚ:"ىٴم",ﳟ:"ىٴم",ﱦ:"ىٴم",ﰂ:"ىٴم",ﱧ:"ىٴن",ﯯ:"ىٴو",ﯮ:"ىٴو",ﯱ:"ىٴو̓",ﯰ:"ىٴو̓",ﯳ:"ىٴو̆",ﯲ:"ىٴو̆",ﯵ:"ىٴوٰ",ﯴ:"ىٴوٰ",ﯻ:"ىٴى",ﯺ:"ىٴى",ﱨ:"ىٴى",ﯹ:"ىٴى",ﰃ:"ىٴى",ﱩ:"ىٴى",ﰄ:"ىٴى",ﳚ:"ىج",ﱕ:"ىج",ﰑ:"ىۛج",ﶯ:"ىجى",ﳛ:"ىح",ﱖ:"ىح",ﶮ:"ىحى",ﳜ:"ىخ",ﱗ:"ىخ",ﲑ:"ىر",ﱶ:"ىۛر",ﲒ:"ىز",ﱷ:"ىۛز",ﳝ:"ىم",ﳰ:"ىم",ﲓ:"ىم",ﱘ:"ىم",ﲦ:"ىۛم",ﳥ:"ىۛم",ﱸ:"ىۛم",ﰒ:"ىۛم",ﶝ:"ىمم",ﶜ:"ىمم",ﶰ:"ىمى",ﲔ:"ىن",ﱹ:"ىۛن",ﲕ:"ىى",ﱙ:"ىى",ﲖ:"ىى",ﱚ:"ىى",ﱺ:"ىۛى",ﰓ:"ىۛى",ﱻ:"ىۛى",ﰔ:"ىۛى",ﮱ:"ۓ",ﮰ:"ۓ","𐊸":"ⵀ","⁞":"ⵂ","⸽":"ⵂ","⦙":"ⵂ","︙":"ⵗ","⁝":"ⵗ","⋮":"ⵗ",Մ:"ሆ",Ռ:"ቡ",Ի:"ኮ",Պ:"ጣ",आ:"अा",ऒ:"अाॆ",ओ:"अाे",औ:"अाै","ऄ":"अॆ",ऑ:"अॉ",ऍ:"एॅ",ऎ:"एॆ",ऐ:"एे",ई:"र्इ",ઽ:"ऽ","𑇜":"ꣻ","𑇋":"ऺ","ુ":"ु","ૂ":"ू","ੋ":"ॆ","੍":"्","્":"्",আ:"অা",ৠ:"ঋৃ",ৡ:"ঋৃ","𑒒":"ঘ","𑒔":"চ","𑒖":"জ","𑒘":"ঞ","𑒙":"ট","𑒛":"ড","𑒪":"ণ","𑒞":"ত","𑒟":"থ","𑒠":"দ","𑒡":"ধ","𑒢":"ন","𑒣":"প","𑒩":"ব","𑒧":"ম","𑒨":"য","𑒫":"র","𑒝":"ল","𑒭":"ষ","𑒮":"স","𑓄":"ঽ","𑒰":"া","𑒱":"ি","𑒹":"ে","𑒼":"ো","𑒾":"ৌ","𑓂":"্","𑒽":"ৗ",ਉ:"ੳੁ",ਊ:"ੳੂ",ਆ:"ਅਾ",ਐ:"ਅੈ",ਔ:"ਅੌ",ਇ:"ੲਿ",ਈ:"ੲੀ",ਏ:"ੲੇ",આ:"અા",ઑ:"અાૅ",ઓ:"અાે",ઔ:"અાૈ",ઍ:"અૅ",એ:"અે",ઐ:"અૈ",ଆ:"ଅା","௮":"அ",ர:"ஈ","ா":"ஈ","௫":"ஈு","௨":"உ",ഉ:"உ",ஊ:"உள",ഊ:"உൗ","௭":"எ","௷":"எவ",ஜ:"ஐ",ജ:"ஐ","௧":"க","௪":"ச","௬":"சு","௲":"சூ","ഺ":"டி",ണ:"ண","௺":"நீ","௴":"மீ","௰":"ய",ഴ:"ழ","ௗ":"ள","ை":"ன",ശ:"ஶ","௸":"ஷ","ി":"ி","ീ":"ி","ொ":"ெஈ","ௌ":"ெள","ோ":"ேஈ",ಅ:"అ",ಆ:"ఆ",ಇ:"ఇ",ౠ:"ఋా",ౡ:"ఌా",ಒ:"ఒ",ఔ:"ఒౌ",ಔ:"ఒౌ",ఓ:"ఒౕ",ಓ:"ఒౕ",ಜ:"జ",ಞ:"ఞ",ఢ:"డ̣",ಣ:"ణ",థ:"ధּ",భ:"బ̣",ಯ:"య",ఠ:"రּ",ಱ:"ఱ",ಲ:"ల",ష:"వ̣",హ:"వా",మ:"వు","ూ":"ుా","ౄ":"ృా",ೡ:"ಌಾ",ഈ:"ഇൗ",ഐ:"എെ",ഓ:"ഒാ",ഔ:"ഒൗ",ൡ:"ഞ","൫":"ദ്ര","൹":"നു",ഌ:"നു",ങ:"നു","൯":"ന്","ൻ":"ന്","൬":"ന്ന","൚":"ന്മ",റ:"ര","൪":"ര്","ർ":"ര്","൮":"വ്ര","൶":"ഹ്മ","ൂ":"ു","ൃ":"ു","ൈ":"െെ","෪":"ජ","෫":"ද","𑐓":"𑐴𑑂𑐒","𑐙":"𑐴𑑂𑐘","𑐤":"𑐴𑑂𑐣","𑐪":"𑐴𑑂𑐩","𑐭":"𑐴𑑂𑐬","𑐯":"𑐴𑑂𑐮","𑗘":"𑖂","𑗙":"𑖂","𑗚":"𑖃","𑗛":"𑖄","𑗜":"𑖲","𑗝":"𑖳",ฃ:"ข",ด:"ค",ต:"ค",ม:"ฆ",ຈ:"จ",ซ:"ช",ฏ:"ฎ",ท:"ฑ",ບ:"บ",ປ:"ป",ຝ:"ฝ",ພ:"พ",ຟ:"ฟ",ฦ:"ภ",ຍ:"ย","។":"ฯ",ๅ:"า",ำ:"̊า","ិ":"ิ","ី":"ี","ឹ":"ึ","ឺ":"ื","ຸ":"ุ","ູ":"ู",แ:"เเ",ໜ:"ຫນ",ໝ:"ຫມ",ຳ:"̊າ","༂":"འུྂཿ","༃":"འུྂ༔",ཪ:"ར",ༀ:"ཨོཾ","ཷ":"ྲཱྀ","ཹ":"ླཱྀ","𑲲":"𑲪","ႁ":"ဂှ",က:"ဂာ","ၰ":"ဃှ","ၦ":"ပှ",ဟ:"ပာ","ၯ":"ပာှ","ၾ":"ၽှ",ဩ:"သြ",ဪ:"သြော်","႞":"ႃ̊",ឣ:"អ","᧐":"ᦞ","᧑":"ᦱ","᪀":"ᩅ","᪐":"ᩅ","꩓":"ꨁ","꩖":"ꨣ","᭒":"ᬍ","᭓":"ᬑ","᭘":"ᬨ","ꦣ":"ꦝ",ᢖ:"ᡜ",ᡕ:"ᠵ",ῶ:"Ꮿ",ᐍ:"ᐁ·",ᐫ:"ᐁᐠ",ᐑ:"ᐄ·",ᐓ:"ᐅ·",ᐭ:"ᐅᐠ",ᐕ:"ᐆ·",ᐘ:"ᐊ·",ᐮ:"ᐊᐠ",ᐚ:"ᐋ·","ᣝ":"ᐞᣟ",ᓑ:"ᐡ",ᕀ:"ᐩ",ᐿ:"ᐲ·",ᑃ:"ᐴ·","⍩":"ᐵ",ᑇ:"ᐹ·",ᑜ:"ᑏ·","⸧":"ᑐ","⊃":"ᑐ",ᑞ:"ᑐ·",ᑩ:"ᑐ'","⟉":"ᑐ/","⫗":"ᑐᑕ",ᑠ:"ᑑ·","⸦":"ᑕ","⊂":"ᑕ",ᑢ:"ᑕ·",ᑪ:"ᑕ'",ᑤ:"ᑖ·",ᑵ:"ᑫ·",ᒅ:"ᑫ'",ᑹ:"ᑮ·",ᑽ:"ᑰ·",ᘃ:"ᒉ",ᒓ:"ᒉ·",ᒕ:"ᒋ·",ᒗ:"ᒌ·",ᒛ:"ᒎ·",ᘂ:"ᒐ",ᒝ:"ᒐ·",ᒟ:"ᒑ·",ᒭ:"ᒣ·",ᒱ:"ᒦ·",ᒳ:"ᒧ·",ᒵ:"ᒨ·",ᒹ:"ᒫ·",ᓊ:"ᓀ·","ᣇ":"ᓂ·","ᣉ":"ᓃ·","ᣋ":"ᓄ·","ᣍ":"ᓅ·",ᓌ:"ᓇ·",ᓎ:"ᓈ·",ᘄ:"ᓓ",ᓝ:"ᓓ·",ᓟ:"ᓕ·",ᓡ:"ᓖ·",ᓣ:"ᓗ·",ᓥ:"ᓘ·",ᘇ:"ᓚ",ᓧ:"ᓚ·",ᓩ:"ᓛ·",ᓷ:"ᓭ·",ᓹ:"ᓯ·",ᓻ:"ᓰ·",ᓽ:"ᓱ·",ᓿ:"ᓲ·",ᔁ:"ᓴ·",ᔃ:"ᓵ·",ᔌ:"ᔋ<",ᔎ:"ᔋb",ᔍ:"ᔋᑕ",ᔏ:"ᔋᒐ",ᔘ:"ᔐ·",ᔚ:"ᔑ·",ᔜ:"ᔒ·",ᔞ:"ᔓ·",ᔠ:"ᔔ·",ᔢ:"ᔕ·",ᔤ:"ᔖ·",ᔲ:"ᔨ·",ᔴ:"ᔩ·",ᔶ:"ᔪ·",ᔸ:"ᔫ·",ᔺ:"ᔭ·",ᔼ:"ᔮ·",ᘢ:"ᕃ","ᣠ":"ᕃ·",ᘣ:"ᕆ",ᘤ:"ᕊ",ᕏ:"ᕌ·",ᖃ:"ᕐb",ᖄ:"ᕐḃ",ᖁ:"ᕐd",ᕿ:"ᕐP",ᙯ:"ᕐᑫ",ᕾ:"ᕐᑬ",ᖀ:"ᕐᑮ",ᖂ:"ᕐᑰ",ᖅ:"ᕐᒃ",ᕜ:"ᕚ·","ᣣ":"ᕞ·","ᣤ":"ᕦ·",ᕩ:"ᕧ·","ᣥ":"ᕫ·","ᣨ":"ᖆ·",ᖑ:"ᖕJ",ᙰ:"ᖕᒉ",ᖎ:"ᖕᒊ",ᖏ:"ᖕᒋ",ᖐ:"ᖕᒌ",ᖒ:"ᖕᒎ",ᖓ:"ᖕᒐ",ᖔ:"ᖕᒑ",ᙳ:"ᖖJ",ᙱ:"ᖖᒋ",ᙲ:"ᖖᒌ",ᙴ:"ᖖᒎ",ᙵ:"ᖖᒐ",ᙶ:"ᖖᒑ","ᣪ":"ᖗ·","ᙷ":"ᖧ·","ᙸ":"ᖨ·","ᙹ":"ᖩ·","ᙺ":"ᖪ·","ᙻ":"ᖫ·","ᙼ":"ᖬ·","ᙽ":"ᖭ·","⪫":"ᗒ","⪪":"ᗕ","ꓷ":"ᗡ","ᣰ":"ᗴ·","ᣲ":"ᘛ·","ᶻ":"ᙆ","ꓭ":"ᙠ","ᶺ":"ᣔ","ᴾ":"ᣖ","ᣜ":"ᣟᐞ",ˡ:"ᣳ",ʳ:"ᣴ",ˢ:"ᣵ","ᣛ":"ᣵ","ꚰ":"ᚹ",ᛡ:"ᚼ","⍿":"ᚽ",ᛂ:"ᚽ","𝈿":"ᛋ","↑":"ᛏ","↿":"ᛐ","⥮":"ᛐ⇂","⥣":"ᛐᛚ","ⵣ":"ᛯ","↾":"ᛚ","⨡":"ᛚ","⋄":"ᛜ","◇":"ᛜ","◊":"ᛜ","♢":"ᛜ","🝔":"ᛜ","𑢷":"ᛜ","𐊔":"ᛜ","⍚":"ᛜ̲","⋈":"ᛞ","⨝":"ᛞ","𐓐":"ᛦ","↕":"ᛨ","𐳼":"𐲂","𐳺":"𐲥",ㄱ:"ᄀ",ᆨ:"ᄀ",ᄁ:"ᄀᄀ",ㄲ:"ᄀᄀ",ᆩ:"ᄀᄀ","ᇺ":"ᄀᄂ","ᅚ":"ᄀᄃ",ᇃ:"ᄀᄅ","ᇻ":"ᄀᄇ",ᆪ:"ᄀᄉ",ㄳ:"ᄀᄉ",ᇄ:"ᄀᄉᄀ","ᇼ":"ᄀᄎ","ᇽ":"ᄀᄏ","ᇾ":"ᄀᄒ",ㄴ:"ᄂ",ᆫ:"ᄂ",ᄓ:"ᄂᄀ",ᇅ:"ᄂᄀ",ᄔ:"ᄂᄂ",ㅥ:"ᄂᄂ","ᇿ":"ᄂᄂ",ᄕ:"ᄂᄃ",ㅦ:"ᄂᄃ",ᇆ:"ᄂᄃ","ퟋ":"ᄂᄅ",ᄖ:"ᄂᄇ","ᅛ":"ᄂᄉ",ᇇ:"ᄂᄉ",ㅧ:"ᄂᄉ","ᅜ":"ᄂᄌ",ᆬ:"ᄂᄌ",ㄵ:"ᄂᄌ","ퟌ":"ᄂᄎ",ᇉ:"ᄂᄐ","ᅝ":"ᄂᄒ",ᆭ:"ᄂᄒ",ㄶ:"ᄂᄒ",ᇈ:"ᄂᅀ",ㅨ:"ᄂᅀ",ㄷ:"ᄃ",ᆮ:"ᄃ",ᄗ:"ᄃᄀ",ᇊ:"ᄃᄀ",ᄄ:"ᄃᄃ",ㄸ:"ᄃᄃ","ퟍ":"ᄃᄃ","ퟎ":"ᄃᄃᄇ","ᅞ":"ᄃᄅ",ᇋ:"ᄃᄅ","ꥠ":"ᄃᄆ","ꥡ":"ᄃᄇ","ퟏ":"ᄃᄇ","ꥢ":"ᄃᄉ","ퟐ":"ᄃᄉ","ퟑ":"ᄃᄉᄀ","ꥣ":"ᄃᄌ","ퟒ":"ᄃᄌ","ퟓ":"ᄃᄎ","ퟔ":"ᄃᄐ",ㄹ:"ᄅ",ᆯ:"ᄅ","ꥤ":"ᄅᄀ",ᆰ:"ᄅᄀ",ㄺ:"ᄅᄀ","ꥥ":"ᄅᄀᄀ","ퟕ":"ᄅᄀᄀ",ᇌ:"ᄅᄀᄉ",ㅩ:"ᄅᄀᄉ","ퟖ":"ᄅᄀᄒ",ᄘ:"ᄅᄂ",ᇍ:"ᄅᄂ","ꥦ":"ᄅᄃ",ᇎ:"ᄅᄃ",ㅪ:"ᄅᄃ","ꥧ":"ᄅᄃᄃ",ᇏ:"ᄅᄃᄒ",ᄙ:"ᄅᄅ",ᇐ:"ᄅᄅ","ퟗ":"ᄅᄅᄏ","ꥨ":"ᄅᄆ",ᆱ:"ᄅᄆ",ㄻ:"ᄅᄆ",ᇑ:"ᄅᄆᄀ",ᇒ:"ᄅᄆᄉ","ퟘ":"ᄅᄆᄒ","ꥩ":"ᄅᄇ",ᆲ:"ᄅᄇ",ㄼ:"ᄅᄇ","ퟙ":"ᄅᄇᄃ","ꥪ":"ᄅᄇᄇ",ᇓ:"ᄅᄇᄉ",ㅫ:"ᄅᄇᄉ","ꥫ":"ᄅᄇᄋ",ᇕ:"ᄅᄇᄋ","ퟚ":"ᄅᄇᄑ",ᇔ:"ᄅᄇᄒ","ꥬ":"ᄅᄉ",ᆳ:"ᄅᄉ",ㄽ:"ᄅᄉ",ᇖ:"ᄅᄉᄉ",ᄛ:"ᄅᄋ","ퟝ":"ᄅᄋ","ꥭ":"ᄅᄌ","ꥮ":"ᄅᄏ",ᇘ:"ᄅᄏ",ᆴ:"ᄅᄐ",ㄾ:"ᄅᄐ",ᆵ:"ᄅᄑ",ㄿ:"ᄅᄑ",ᄚ:"ᄅᄒ",ㅀ:"ᄅᄒ",ᄻ:"ᄅᄒ",ᆶ:"ᄅᄒ","ퟲ":"ᄅᄒ",ᇗ:"ᄅᅀ",ㅬ:"ᄅᅀ","ퟛ":"ᄅᅌ",ᇙ:"ᄅᅙ",ㅭ:"ᄅᅙ","ퟜ":"ᄅᅙᄒ",ㅁ:"ᄆ",ᆷ:"ᄆ","ꥯ":"ᄆᄀ",ᇚ:"ᄆᄀ","ퟞ":"ᄆᄂ","ퟟ":"ᄆᄂᄂ","ꥰ":"ᄆᄃ",ᇛ:"ᄆᄅ","ퟠ":"ᄆᄆ",ᄜ:"ᄆᄇ",ㅮ:"ᄆᄇ",ᇜ:"ᄆᄇ","ퟡ":"ᄆᄇᄉ","ꥱ":"ᄆᄉ",ᇝ:"ᄆᄉ",ㅯ:"ᄆᄉ",ᇞ:"ᄆᄉᄉ",ᄝ:"ᄆᄋ",ㅱ:"ᄆᄋ",ᇢ:"ᄆᄋ","ퟢ":"ᄆᄌ",ᇠ:"ᄆᄎ",ᇡ:"ᄆᄒ",ᇟ:"ᄆᅀ",ㅰ:"ᄆᅀ",ㅂ:"ᄇ",ᆸ:"ᄇ",ᄞ:"ᄇᄀ",ㅲ:"ᄇᄀ",ᄟ:"ᄇᄂ",ᄠ:"ᄇᄃ",ㅳ:"ᄇᄃ","ퟣ":"ᄇᄃ",ᇣ:"ᄇᄅ","ퟤ":"ᄇᄅᄑ","ퟥ":"ᄇᄆ",ᄈ:"ᄇᄇ",ㅃ:"ᄇᄇ","ퟦ":"ᄇᄇ",ᄬ:"ᄇᄇᄋ",ㅹ:"ᄇᄇᄋ",ᄡ:"ᄇᄉ",ㅄ:"ᄇᄉ",ᆹ:"ᄇᄉ",ᄢ:"ᄇᄉᄀ",ㅴ:"ᄇᄉᄀ",ᄣ:"ᄇᄉᄃ",ㅵ:"ᄇᄉᄃ","ퟧ":"ᄇᄉᄃ",ᄤ:"ᄇᄉᄇ",ᄥ:"ᄇᄉᄉ",ᄦ:"ᄇᄉᄌ","ꥲ":"ᄇᄉᄐ",ᄫ:"ᄇᄋ",ㅸ:"ᄇᄋ",ᇦ:"ᄇᄋ",ᄧ:"ᄇᄌ",ㅶ:"ᄇᄌ","ퟨ":"ᄇᄌ",ᄨ:"ᄇᄎ","ퟩ":"ᄇᄎ","ꥳ":"ᄇᄏ",ᄩ:"ᄇᄐ",ㅷ:"ᄇᄐ",ᄪ:"ᄇᄑ",ᇤ:"ᄇᄑ","ꥴ":"ᄇᄒ",ᇥ:"ᄇᄒ",ㅅ:"ᄉ",ᆺ:"ᄉ",ᄭ:"ᄉᄀ",ㅺ:"ᄉᄀ",ᇧ:"ᄉᄀ",ᄮ:"ᄉᄂ",ㅻ:"ᄉᄂ",ᄯ:"ᄉᄃ",ㅼ:"ᄉᄃ",ᇨ:"ᄉᄃ",ᄰ:"ᄉᄅ",ᇩ:"ᄉᄅ",ᄱ:"ᄉᄆ","ퟪ":"ᄉᄆ",ᄲ:"ᄉᄇ",ㅽ:"ᄉᄇ",ᇪ:"ᄉᄇ",ᄳ:"ᄉᄇᄀ","ퟫ":"ᄉᄇᄋ",ᄊ:"ᄉᄉ",ㅆ:"ᄉᄉ",ᆻ:"ᄉᄉ","ퟬ":"ᄉᄉᄀ","ퟭ":"ᄉᄉᄃ","ꥵ":"ᄉᄉᄇ",ᄴ:"ᄉᄉᄉ",ᄵ:"ᄉᄋ",ᄶ:"ᄉᄌ",ㅾ:"ᄉᄌ","ퟯ":"ᄉᄌ",ᄷ:"ᄉᄎ","ퟰ":"ᄉᄎ",ᄸ:"ᄉᄏ",ᄹ:"ᄉᄐ","ퟱ":"ᄉᄐ",ᄺ:"ᄉᄑ","ퟮ":"ᄉᅀ",ㅇ:"ᄋ",ᆼ:"ᄋ",ᅁ:"ᄋᄀ",ᇬ:"ᄋᄀ",ᇭ:"ᄋᄀᄀ",ᅂ:"ᄋᄃ","ꥶ":"ᄋᄅ",ᅃ:"ᄋᄆ",ᅄ:"ᄋᄇ",ᅅ:"ᄋᄉ",ᇱ:"ᄋᄉ",ㆂ:"ᄋᄉ",ᅇ:"ᄋᄋ",ㆀ:"ᄋᄋ",ᇮ:"ᄋᄋ",ᅈ:"ᄋᄌ",ᅉ:"ᄋᄎ",ᇯ:"ᄋᄏ",ᅊ:"ᄋᄐ",ᅋ:"ᄋᄑ","ꥷ":"ᄋᄒ",ᅆ:"ᄋᅀ",ᇲ:"ᄋᅀ",ㆃ:"ᄋᅀ",ㅈ:"ᄌ",ᆽ:"ᄌ","ퟷ":"ᄌᄇ","ퟸ":"ᄌᄇᄇ",ᅍ:"ᄌᄋ",ᄍ:"ᄌᄌ",ㅉ:"ᄌᄌ","ퟹ":"ᄌᄌ","ꥸ":"ᄌᄌᄒ",ㅊ:"ᄎ",ᆾ:"ᄎ",ᅒ:"ᄎᄏ",ᅓ:"ᄎᄒ",ㅋ:"ᄏ",ᆿ:"ᄏ",ㅌ:"ᄐ",ᇀ:"ᄐ","ꥹ":"ᄐᄐ",ㅍ:"ᄑ",ᇁ:"ᄑ",ᅖ:"ᄑᄇ",ᇳ:"ᄑᄇ","ퟺ":"ᄑᄉ",ᅗ:"ᄑᄋ",ㆄ:"ᄑᄋ",ᇴ:"ᄑᄋ","ퟻ":"ᄑᄐ","ꥺ":"ᄑᄒ",ㅎ:"ᄒ",ᇂ:"ᄒ",ᇵ:"ᄒᄂ",ᇶ:"ᄒᄅ",ᇷ:"ᄒᄆ",ᇸ:"ᄒᄇ","ꥻ":"ᄒᄉ",ᅘ:"ᄒᄒ",ㆅ:"ᄒᄒ",ᄽ:"ᄼᄼ",ᄿ:"ᄾᄾ",ㅿ:"ᅀ",ᇫ:"ᅀ","ퟳ":"ᅀᄇ","ퟴ":"ᅀᄇᄋ",ㆁ:"ᅌ",ᇰ:"ᅌ","ퟵ":"ᅌᄆ","ퟶ":"ᅌᄒ",ᅏ:"ᅎᅎ",ᅑ:"ᅐᅐ",ㆆ:"ᅙ",ᇹ:"ᅙ","ꥼ":"ᅙᅙ",ㅤ:"ᅠ",ㅏ:"ᅡ","ᆣ":"ᅡー",ᅶ:"ᅡᅩ",ᅷ:"ᅡᅮ",ᅢ:"ᅡ丨",ㅐ:"ᅡ丨",ㅑ:"ᅣ",ᅸ:"ᅣᅩ",ᅹ:"ᅣᅭ","ᆤ":"ᅣᅮ",ᅤ:"ᅣ丨",ㅒ:"ᅣ丨",ㅓ:"ᅥ",ᅼ:"ᅥー",ᅺ:"ᅥᅩ",ᅻ:"ᅥᅮ",ᅦ:"ᅥ丨",ㅔ:"ᅥ丨",ㅕ:"ᅧ","ᆥ":"ᅧᅣ",ᅽ:"ᅧᅩ",ᅾ:"ᅧᅮ",ᅨ:"ᅧ丨",ㅖ:"ᅧ丨",ㅗ:"ᅩ",ᅪ:"ᅩᅡ",ㅘ:"ᅩᅡ",ᅫ:"ᅩᅡ丨",ㅙ:"ᅩᅡ丨","ᆦ":"ᅩᅣ","ᆧ":"ᅩᅣ丨",ᅿ:"ᅩᅥ",ᆀ:"ᅩᅥ丨","ힰ":"ᅩᅧ",ᆁ:"ᅩᅧ丨",ᆂ:"ᅩᅩ","ힱ":"ᅩᅩ丨",ᆃ:"ᅩᅮ",ᅬ:"ᅩ丨",ㅚ:"ᅩ丨",ㅛ:"ᅭ","ힲ":"ᅭᅡ","ힳ":"ᅭᅡ丨",ᆄ:"ᅭᅣ",ㆇ:"ᅭᅣ",ᆆ:"ᅭᅣ",ᆅ:"ᅭᅣ丨",ㆈ:"ᅭᅣ丨","ힴ":"ᅭᅥ",ᆇ:"ᅭᅩ",ᆈ:"ᅭ丨",ㆉ:"ᅭ丨",ㅜ:"ᅮ",ᆉ:"ᅮᅡ",ᆊ:"ᅮᅡ丨",ᅯ:"ᅮᅥ",ㅝ:"ᅮᅥ",ᆋ:"ᅮᅥー",ᅰ:"ᅮᅥ丨",ㅞ:"ᅮᅥ丨","ힵ":"ᅮᅧ",ᆌ:"ᅮᅧ丨",ᆍ:"ᅮᅮ",ᅱ:"ᅮ丨",ㅟ:"ᅮ丨","ힶ":"ᅮ丨丨",ㅠ:"ᅲ",ᆎ:"ᅲᅡ","ힷ":"ᅲᅡ丨",ᆏ:"ᅲᅥ",ᆐ:"ᅲᅥ丨",ᆑ:"ᅲᅧ",ㆊ:"ᅲᅧ",ᆒ:"ᅲᅧ丨",ㆋ:"ᅲᅧ丨","ힸ":"ᅲᅩ",ᆓ:"ᅲᅮ",ᆔ:"ᅲ丨",ㆌ:"ᅲ丨",ㆍ:"ᆞ","ퟅ":"ᆞᅡ",ᆟ:"ᆞᅥ","ퟆ":"ᆞᅥ丨",ᆠ:"ᆞᅮ",ᆢ:"ᆞᆞ",ᆡ:"ᆞ丨",ㆎ:"ᆞ丨",ヘ:"へ","⍁":"〼","⧄":"〼","꒞":"ꁊ","꒬":"ꁐ","꒜":"ꃀ","꒨":"ꄲ","꒿":"ꉙ","꒾":"ꊱ","꒔":"ꋍ","꓀":"ꎫ","꓂":"ꎵ","꒺":"ꎿ","꒰":"ꏂ","꒧":"ꑘ","⊥":"ꓕ","⟂":"ꓕ","𝈜":"ꓕ","Ʇ":"ꓕ","Ꞟ":"ꓤ","⅁":"ꓨ","⅂":"ꓶ","𝈕":"ꓶ","𝈫":"ꓶ","𖼦":"ꓶ","𐐑":"ꓶ","⅃":"𖼀","𑫦":"𑫥𑫯","𑫨":"𑫥𑫥","𑫩":"𑫥𑫥𑫯","𑫪":"𑫥𑫥𑫰","𑫧":"𑫥𑫰","𑫴":"𑫳𑫯","𑫶":"𑫳𑫳","𑫷":"𑫳𑫳𑫯","𑫸":"𑫳𑫳𑫰","𑫵":"𑫳𑫰","𑫬":"𑫫𑫯","𑫭":"𑫫𑫫","𑫮":"𑫫𑫫𑫯","⊕":"𐊨","⨁":"𐊨","🜨":"𐊨","Ꚛ":"𐊨","▽":"𐊼","𝈔":"𐊼","🜄":"𐊼","⧖":"𐋀","ꞛ":"𐐺","Ꞛ":"𐐒","𐒠":"𐒆","𐏑":"𐎂","𐏓":"𐎓","𒀸":"𐎚","☥":"𐦞","𓋹":"𐦞","〹":"卄",不:"不","丽":"丽","並":"並","⎜":"丨","⎟":"丨","⎢":"丨","⎥":"丨","⎪":"丨","⎮":"丨","㇑":"丨",ᅵ:"丨",ㅣ:"丨","⼁":"丨",ᆜ:"丨ー",ᆘ:"丨ᅡ",ᆙ:"丨ᅣ","ힽ":"丨ᅣᅩ","ힾ":"丨ᅣ丨","ힿ":"丨ᅧ","ퟀ":"丨ᅧ丨",ᆚ:"丨ᅩ","ퟁ":"丨ᅩ丨","ퟂ":"丨ᅭ",ᆛ:"丨ᅮ","ퟃ":"丨ᅲ",ᆝ:"丨ᆞ","ퟄ":"丨丨",串:"串","丸":"丸",丹:"丹","乁":"乁","㇠":"乙","⼄":"乙","㇟":"乚","⺃":"乚","㇖":"乛","⺂":"乛","⻲":"亀",亂:"亂","㇚":"亅","⼅":"亅",了:"了",ニ:"二","⼆":"二","𠄢":"𠄢","⼇":"亠",亮:"亮","⼈":"人",イ:"亻","⺅":"亻",什:"什","仌":"仌",令:"令","你":"你",倂:"併","倂":"併","侀":"侀",來:"來",例:"例","侮":"侮","侮":"侮","侻":"侻",便:"便",值:"値",倫:"倫","偺":"偺","備":"備","像":"像",僚:"僚","僧":"僧","僧":"僧","㒞":"㒞","⼉":"儿",兀:"兀","⺎":"兀","充":"充","免":"免","免":"免","兔":"兔","兤":"兤","⼊":"入","內":"內","全":"全",兩:"兩",ハ:"八","⼋":"八",六:"六","具":"具","𠔜":"𠔜","𠔥":"𠔥","冀":"冀","㒹":"㒹","⼌":"冂","再":"再","𠕋":"𠕋","冒":"冒","冕":"冕","㒻":"㒻","最":"最","⼍":"冖","冗":"冗","冤":"冤","⼎":"冫","冬":"冬","况":"况","况":"况",冷:"冷",凉:"凉",凌:"凌",凜:"凜",凞:"凞","⼏":"几","𠘺":"𠘺","凵":"凵","⼐":"凵","⼑":"刀","⺉":"刂","刃":"刃",切:"切","切":"切",列:"列",利:"利","㓟":"㓟",刺:"刺","刻":"刻","剆":"剆","割":"割","剷":"剷",劉:"劉","𠠄":"𠠄",カ:"力",力:"力","⼒":"力",劣:"劣","㔕":"㔕","劳":"劳","勇":"勇","勇":"勇","勉":"勉","勉":"勉",勒:"勒",勞:"勞","勤":"勤","勤":"勤",勵:"勵","⼓":"勹","勺":"勺","勺":"勺","包":"包","匆":"匆","𠣞":"𠣞","⼔":"匕",北:"北","北":"北","⼕":"匚","⼖":"匸",匿:"匿","⼗":"十","〸":"十","〺":"卅","卉":"卉","࿖":"卍","࿕":"卐","卑":"卑","卑":"卑","博":"博",ト:"卜","⼘":"卜","⼙":"卩","⺋":"㔾","即":"即",卵:"卵","卽":"卽","卿":"卿","卿":"卿","卿":"卿","⼚":"厂","𠨬":"𠨬","⼛":"厶",參:"參","⼜":"又","及":"及","叟":"叟","𠭣":"𠭣",ロ:"口","⼝":"口",囗:"口","⼞":"口",句:"句","叫":"叫","叱":"叱","吆":"吆",吏:"吏",吝:"吝","吸":"吸",呂:"呂","呈":"呈","周":"周","咞":"咞","咢":"咢",咽:"咽",䎛:"㖈","哶":"哶","唐":"唐","啓":"啓",啟:"啓","啕":"啕","啣":"啣","善":"善","善":"善",喇:"喇","喙":"喙","喙":"喙","喝":"喝","喝":"喝","喫":"喫","喳":"喳",嗀:"嗀","嗂":"嗂","嗢":"嗢","嘆":"嘆","嘆":"嘆","噑":"噑","噴":"噴","器":"器",囹:"囹","圖":"圖","圗":"圗","⼟":"土",士:"土","⼠":"土","型":"型","城":"城",㦳:"㘽","埴":"埴","堍":"堍","報":"報","堲":"堲","塀":"塀",塚:"塚","塚":"塚",塞:"塞",填:"塡",壿:"墫","墬":"墬","墳":"墳",壘:"壘",壟:"壟","𡓤":"𡓤","壮":"壮","売":"売","壷":"壷","⼡":"夂","夆":"夆","⼢":"夊",タ:"夕","⼣":"夕","多":"多","夢":"夢","⼤":"大","奄":"奄",奈:"奈",契:"契","奔":"奔","奢":"奢",女:"女","⼥":"女","𡚨":"𡚨","𡛪":"𡛪","姘":"姘","姬":"姬","娛":"娛","娧":"娧","婢":"婢","婦":"婦",嬀:"媯","㛮":"㛮","㛼":"㛼","媵":"媵","嬈":"嬈","嬨":"嬨","嬾":"嬾","嬾":"嬾","⼦":"子","⼧":"宀",宅:"宅","𡧈":"𡧈","寃":"寃","寘":"寘",寧:"寧",寧:"寧","寧":"寧",寮:"寮","寳":"寳","𡬘":"𡬘","⼨":"寸","寿":"寿","将":"将","⼩":"小","尢":"尢","⺐":"尢","⼪":"尢","⺏":"尣","㞁":"㞁","⼫":"尸",尿:"尿","屠":"屠",屢:"屢","層":"層",履:"履","屮":"屮","屮":"屮","⼬":"屮","𡴋":"𡴋","⼭":"山","峀":"峀","岍":"岍","𡷤":"𡷤","𡷦":"𡷦",崙:"崙","嵃":"嵃",嵐:"嵐","嵫":"嵫","嵮":"嵮","嵼":"嵼","嶲":"嶲",嶺:"嶺","⼮":"巛","巢":"巢",エ:"工","⼯":"工","⼰":"己","⺒":"巳","㠯":"㠯","巽":"巽","⼱":"巾",帲:"帡","帨":"帨","帽":"帽","幩":"幩","㡢":"㡢","𢆃":"𢆃","⼲":"干",年:"年","𢆟":"𢆟","⺓":"幺","⼳":"幺","⼴":"广",度:"度","㡼":"㡼","庰":"庰","庳":"庳","庶":"庶",廊:"廊","廊":"廊",廉:"廉","廒":"廒",廓:"廓","廙":"廙",廬:"廬","⼵":"廴","廾":"廾","⼶":"廾","𢌱":"𢌱","𢌱":"𢌱",弄:"弄","⼷":"弋","⼸":"弓","弢":"弢","弢":"弢","⼹":"彐","⺔":"彑","当":"当","㣇":"㣇","⼺":"彡","形":"形","彩":"彩","彫":"彫","⼻":"彳",律:"律","㣣":"㣣","徚":"徚",復:"復","徭":"徭","⼼":"心","⺖":"忄","⺗":"㣺","忍":"忍","志":"志",念:"念","忹":"忹",怒:"怒",怜:"怜","恵":"恵","㤜":"㤜","㤺":"㤺","悁":"悁","悔":"悔","悔":"悔","惇":"惇","惘":"惘",惡:"惡","𢛔":"𢛔","愈":"愈","慨":"慨",慄:"慄","慈":"慈","慌":"慌","慌":"慌","慎":"慎","慎":"慎","慠":"慠","慺":"慺","憎":"憎","憎":"憎","憎":"憎",憐:"憐","憤":"憤","憯":"憯","憲":"憲","𢡄":"𢡄","𢡊":"𢡊","懞":"懞","懲":"懲","懲":"懲","懲":"懲",懶:"懶","懶":"懶",戀:"戀","⼽":"戈","成":"成","戛":"戛",戮:"戮","戴":"戴","⼾":"戶",戸:"戶","⼿":"手","⺘":"扌","扝":"扝","抱":"抱",拉:"拉",拏:"拏",拓:"拓","拔":"拔","拼":"拼",拾:"拾","𢬌":"𢬌","挽":"挽","捐":"捐","捨":"捨",捻:"捻","掃":"掃",掠:"掠","掩":"掩","揄":"揄","揤":"揤","摒":"摒","𢯱":"𢯱","搜":"搜","搢":"搢","揅":"揅","摩":"摩","摷":"摷","摾":"摾","㨮":"㨮",搉:"㩁",撚:"撚","撝":"撝",擄:"擄","㩬":"㩬","⽀":"支","⽁":"攴","⺙":"攵","敏":"敏","敏":"敏","敖":"敖","敬":"敬",數:"數","𣀊":"𣀊","⽂":"文","⻫":"斉","⽃":"斗",料:"料","⽄":"斤","⽅":"方",旅:"旅","⽆":"无","⺛":"旡","既":"既","旣":"旣","⽇":"日",易:"易",曶:"㫚","㫤":"㫤","晉":"晉",晩:"晚",晴:"晴","晴":"晴","暑":"暑","暑":"暑",暈:"暈","㬈":"㬈","暜":"暜",暴:"暴",曆:"曆","㬙":"㬙","𣊸":"𣊸","⽈":"曰",更:"更","書":"書","⽉":"月","𣍟":"𣍟",肦:"朌",胐:"朏",胊:"朐",脁:"朓",胶:"㬵",朗:"朗","朗":"朗","朗":"朗",脧:"朘","望":"望","望":"望",幐:"㬺",䐠:"㬻","𣎓":"𣎓",膧:"朣","𣎜":"𣎜","⽊":"木",李:"李","杓":"杓","杖":"杖","杞":"杞","𣏃":"𣏃",柿:"杮",杻:"杻","枅":"枅",林:"林","㭉":"㭉","𣏕":"𣏕",柳:"柳","柺":"柺",栗:"栗","栟":"栟","桒":"桒","𣑭":"𣑭",梁:"梁","梅":"梅","梅":"梅","梎":"梎",梨:"梨","椔":"椔","楂":"楂","㮝":"㮝","㮝":"㮝",槩:"㮣",樧:"榝","榣":"榣","槪":"槪",樂:"樂",樂:"樂",樂:"樂",樓:"樓","𣚣":"𣚣","檨":"檨",櫓:"櫓","櫛":"櫛",欄:"欄","㰘":"㰘","⽋":"欠","次":"次","𣢧":"𣢧","歔":"歔","㱎":"㱎","⽌":"止","⻭":"歯","歲":"歲",歷:"歷","歹":"歹","⽍":"歹","⺞":"歺","殟":"殟",殮:"殮","⽎":"殳",殺:"殺","殺":"殺","殺":"殺","殻":"殻","𣪍":"𣪍","⽏":"毋","⺟":"母","𣫺":"𣫺","⽐":"比","⽑":"毛","⽒":"氏","⺠":"民","⽓":"气","⽔":"水","⺡":"氵","⺢":"氺","汎":"汎","汧":"汧",沈:"沈","沿":"沿",泌:"泌","泍":"泍",泥:"泥","𣲼":"𣲼",洛:"洛",洞:"洞","洴":"洴","派":"派",流:"流","流":"流","流":"流","洖":"洖","浩":"浩",浪:"浪","海":"海","海":"海","浸":"浸","涅":"涅","𣴞":"𣴞",淋:"淋",淚:"淚",淪:"淪","淹":"淹","渚":"渚","港":"港","湮":"湮",潙:"溈","滋":"滋","滋":"滋",溜:"溜",溺:"溺","滇":"滇",滑:"滑","滛":"滛","㴳":"㴳",漏:"漏","漢":"漢","漢":"漢",漣:"漣","𣻑":"𣻑","潮":"潮","𣽞":"𣽞","𣾎":"𣾎","濆":"濆",濫:"濫",濾:"濾","瀛":"瀛","瀞":"瀞","瀞":"瀞","瀹":"瀹","灊":"灊","㶖":"㶖","⽕":"火","⺣":"灬","灰":"灰","灷":"灷","災":"災",炙:"炙","炭":"炭",烈:"烈",烙:"烙","煮":"煮","煮":"煮","𤉣":"𤉣","煅":"煅",煉:"煉","𤋮":"𤋮","熜":"熜",燎:"燎",燐:"燐","𤎫":"𤎫",爐:"爐",爛:"爛","爨":"爨","⽖":"爪","爫":"爫","⺤":"爫","爵":"爵","爵":"爵","⽗":"父","⽘":"爻","⺦":"丬","⽙":"爿","⽚":"片","牐":"牐","⽛":"牙","𤘈":"𤘈","⽜":"牛",牢:"牢","犀":"犀","犕":"犕","⽝":"犬","⺨":"犭","犯":"犯",狀:"狀","𤜵":"𤜵",狼:"狼",猪:"猪","猪":"猪","𤠔":"𤠔",獵:"獵","獺":"獺","⽞":"玄",率:"率",率:"率","⽟":"玉","王":"王","㺬":"㺬","玥":"玥",玲:"玲","㺸":"㺸","㺸":"㺸",珞:"珞",琉:"琉",理:"理","琢":"琢","瑇":"瑇","瑜":"瑜",瑩:"瑩","瑱":"瑱","瑱":"瑱","璅":"璅",璉:"璉",璘:"璘","瓊":"瓊","⽠":"瓜","⽡":"瓦","㼛":"㼛","甆":"甆","⽢":"甘","⽣":"生","甤":"甤","⽤":"用","⽥":"田","画":"画","甾":"甾","𤰶":"𤰶",留:"留",略:"略",異:"異","異":"異","𤲒":"𤲒","⽦":"疋","⽧":"疒",痢:"痢","瘐":"瘐","瘟":"瘟","瘝":"瘝",療:"療",癩:"癩","⽨":"癶","⽩":"白","𤾡":"𤾡","𤾸":"𤾸","⽪":"皮","⽫":"皿","𥁄":"𥁄","㿼":"㿼",益:"益","益":"益","盛":"盛",盧:"盧","䀈":"䀈","⽬":"目","直":"直","直":"直","𥃲":"𥃲","𥃳":"𥃳",省:"省","䀘":"䀘","𥄙":"𥄙","眞":"眞","真":"真","真":"真","𥄳":"𥄳","着":"着","睊":"睊","睊":"睊","鿃":"䀹","䀹":"䀹","䀹":"䀹",晣:"䀿","䁆":"䁆","瞋":"瞋","𥉉":"𥉉","瞧":"瞧","⽭":"矛","⽮":"矢","⽯":"石","䂖":"䂖","𥐝":"𥐝",硏:"研","硎":"硎",硫:"硫",碌:"碌","碌":"碌","碑":"碑",磊:"磊","磌":"磌","磌":"磌",磻:"磻","䃣":"䃣",礪:"礪","⽰":"示","⺭":"礻",礼:"礼","社":"社","祈":"祈","祉":"祉","𥘦":"𥘦","祐":"祐","祖":"祖","祖":"祖","祝":"祝",神:"神",祥:"祥","視":"視","視":"視",祿:"祿","𥚚":"𥚚","禍":"禍","禎":"禎",福:"福","福":"福","𥛅":"𥛅",禮:"禮","⽱":"禸","⽲":"禾",秊:"秊","䄯":"䄯","秫":"秫",稜:"稜","穊":"穊","穀":"穀","穀":"穀","穏":"穏","⽳":"穴","突":"突","𥥼":"𥥼","窱":"窱",立:"立","⽴":"立","⻯":"竜","𥪧":"𥪧","𥪧":"𥪧","竮":"竮","⽵":"竹",笠:"笠","節":"節","節":"節","䈂":"䈂","𥮫":"𥮫","篆":"篆","䈧":"䈧","築":"築","𥲀":"𥲀","𥳐":"𥳐",簾:"簾",籠:"籠","⽶":"米","类":"类",粒:"粒",精:"精","糒":"糒",糖:"糖","糨":"糨","䊠":"䊠","糣":"糣",糧:"糧","⽷":"糸","⺯":"糹","𥾆":"𥾆","紀":"紀",紐:"紐",索:"索",累:"累",絶:"絕","絣":"絣","絛":"絛",綠:"綠",綾:"綾","緇":"緇",練:"練","練":"練","練":"練","縂":"縂","䌁":"䌁","縉":"縉",縷:"縷","繁":"繁","繅":"繅","𦇚":"𦇚","䌴":"䌴","⽸":"缶","𦈨":"𦈨","缾":"缾","𦉇":"𦉇","⽹":"网","⺫":"罒","⺲":"罒","⺱":"罓","䍙":"䍙","署":"署","𦋙":"𦋙",罹:"罹","罺":"罺",羅:"羅","𦌾":"𦌾","⽺":"羊","羕":"羕",羚:"羚",羽:"羽","⽻":"羽","翺":"翺",老:"老","⽼":"老","⺹":"耂","者":"者","者":"者","者":"者","⽽":"而","𦓚":"𦓚","⽾":"耒","𦔣":"𦔣","⽿":"耳",聆:"聆","聠":"聠","𦖨":"𦖨",聯:"聯","聰":"聰",聾:"聾","⾀":"聿","⺺":"肀","⾁":"肉",肋:"肋","肭":"肭","育":"育","䏕":"䏕","䏙":"䏙",腁:"胼","脃":"脃","脾":"脾","䐋":"䐋","朡":"朡","𦞧":"𦞧","𦞵":"𦞵",朦:"䑃",臘:"臘","⾂":"臣",臨:"臨","⾃":"自","臭":"臭","⾄":"至","⾅":"臼","舁":"舁","舁":"舁","舄":"舄","⾆":"舌","舘":"舘","⾇":"舛","⾈":"舟","䑫":"䑫","⾉":"艮",良:"良","⾊":"色","⾋":"艸","艹":"艹","艹":"艹","⺾":"艹","⺿":"艹","⻀":"艹","芋":"芋","芑":"芑","芝":"芝","花":"花","芳":"芳","芽":"芽",若:"若","若":"若","苦":"苦","𦬼":"𦬼",茶:"茶","荒":"荒","荣":"荣","茝":"茝","茣":"茣","莽":"莽","荓":"荓",菉:"菉","菊":"菊","菌":"菌","菜":"菜","菧":"菧","華":"華",菱:"菱","著":"著","著":"著","𦰶":"𦰶","莭":"莭",落:"落",葉:"葉",蔿:"蒍","𦳕":"𦳕","𦵫":"𦵫",蓮:"蓮","蓱":"蓱","蓳":"蓳",蓼:"蓼","蔖":"蔖","䔫":"䔫","蕤":"蕤","𦼬":"𦼬",藍:"藍","䕝":"䕝","𦾱":"𦾱","䕡":"䕡",藺:"藺",蘆:"蘆","䕫":"䕫",蘒:"蘒",蘭:"蘭","𧃒":"𧃒",虁:"蘷",蘿:"蘿","⾌":"虍","⻁":"虎","虐":"虐",虜:"虜","虜":"虜","虧":"虧","虩":"虩","⾍":"虫","蚩":"蚩","蚈":"蚈","蛢":"蛢","蜎":"蜎","蜨":"蜨","蝫":"蝫","蟡":"蟡","蝹":"蝹","蝹":"蝹","螆":"螆","䗗":"䗗","𧏊":"𧏊",螺:"螺","蠁":"蠁","䗹":"䗹",蠟:"蠟","⾎":"血",行:"行","⾏":"行","衠":"衠","衣":"衣","⾐":"衣","⻂":"衤",裂:"裂","𧙧":"𧙧",裏:"裏","裗":"裗","裞":"裞",裡:"裡",裸:"裸","裺":"裺","䘵":"䘵","褐":"褐","襁":"襁",襤:"襤","⾑":"襾","⻄":"西","⻃":"覀","覆":"覆",見:"見","⾒":"見","𧢮":"𧢮","⻅":"见","⾓":"角","⾔":"言","𧥦":"𧥦",詽:"訮",訞:"䚶","䚾":"䚾","䛇":"䛇","誠":"誠",說:"說",說:"說","調":"調","請":"請",諒:"諒",論:"論","諭":"諭","諭":"諭",諸:"諸","諸":"諸",諾:"諾","諾":"諾","謁":"謁","謁":"謁","謹":"謹","謹":"謹",識:"識",讀:"讀",讏:"讆","變":"變","變":"變","⻈":"讠","⾕":"谷","⾖":"豆",豈:"豈","豕":"豕","⾗":"豕",豣:"豜","⾘":"豸","𧲨":"𧲨","⾙":"貝","貫":"貫","賁":"賁",賂:"賂",賈:"賈","賓":"賓","贈":"贈","贈":"贈","贛":"贛","⻉":"贝","⾚":"赤","⾛":"走","起":"起",趆:"赿","𧻓":"𧻓","𧼯":"𧼯","⾜":"足","跋":"跋","趼":"趼",跺:"跥",路:"路","跰":"跰",躛:"躗","⾝":"身",車:"車","⾞":"車","軔":"軔",輧:"軿",輦:"輦",輪:"輪","輸":"輸","輸":"輸",輻:"輻",轢:"轢","⻋":"车","⾟":"辛","辞":"辞",辰:"辰","⾠":"辰","⾡":"辵","辶":"辶","⻌":"辶","⻍":"辶","巡":"巡",連:"連",逸:"逸","逸":"逸","遲":"遲",遼:"遼","𨗒":"𨗒","𨗭":"𨗭",邏:"邏","⾢":"邑","邔":"邔",郎:"郎",郞:"郎","郞":"郎","郱":"郱",都:"都","𨜮":"𨜮","鄑":"鄑","鄛":"鄛","⾣":"酉",酪:"酪","醙":"醙",醴:"醴","⾤":"釆",里:"里","⾥":"里",量:"量",金:"金","⾦":"金",鈴:"鈴","鈸":"鈸","鉶":"鉶","鋗":"鋗","鋘":"鋘","鉼":"鉼",錄:"錄",鍊:"鍊",鎮:"鎭","鏹":"鏹","鐕":"鐕","𨯺":"𨯺","⻐":"钅","⻑":"長","⾧":"長","⻒":"镸","⻓":"长","⾨":"門","開":"開","䦕":"䦕",閭:"閭","閷":"閷","𨵷":"𨵷","⻔":"门","⾩":"阜","⻏":"阝","⻖":"阝",阮:"阮",陋:"陋",降:"降",陵:"陵",陸:"陸","陼":"陼",隆:"隆",隣:"隣","䧦":"䧦","⾪":"隶","隷":"隷",隸:"隷",隸:"隷","⾫":"隹","雃":"雃",離:"離","難":"難","難":"難","⾬":"雨",零:"零",雷:"雷","霣":"霣","𩅅":"𩅅",露:"露",靈:"靈","⾭":"靑","⻘":"青",靖:"靖","靖":"靖","𩇟":"𩇟","⾮":"非","⾯":"面","𩈚":"𩈚","⾰":"革","䩮":"䩮","䩶":"䩶","⾱":"韋","韛":"韛","韠":"韠","⻙":"韦","⾲":"韭","𩐊":"𩐊","⾳":"音","響":"響","響":"響","⾴":"頁","䪲":"䪲","頋":"頋","頋":"頋","頋":"頋",領:"領","頩":"頩","𩒖":"𩒖","頻":"頻","頻":"頻",類:"類","⻚":"页","⾵":"風","𩖶":"𩖶","⻛":"风","⾶":"飛","⻜":"飞","⻝":"食","⾷":"食","⻟":"飠","飢":"飢",飯:"飯",飼:"飼","䬳":"䬳",館:"館","餩":"餩","⻠":"饣","⾸":"首","⾹":"香","馧":"馧","⾺":"馬","駂":"駂",駱:"駱","駾":"駾",驪:"驪","⻢":"马","⾻":"骨","䯎":"䯎","⾼":"高","⾽":"髟","𩬰":"𩬰","鬒":"鬒","鬒":"鬒","⾾":"鬥","⾿":"鬯","⿀":"鬲","⿁":"鬼","⻤":"鬼","⿂":"魚",魯:"魯","鱀":"鱀",鱗:"鱗","⻥":"鱼","⿃":"鳥","鳽":"鳽","䳎":"䳎","鵧":"鵧","䳭":"䳭","𪃎":"𪃎",鶴:"鶴","𪄅":"𪄅","䳸":"䳸",鷺:"鷺","𪈎":"𪈎",鸞:"鸞",鹃:"鹂","⿄":"鹵",鹿:"鹿","⿅":"鹿","𪊑":"𪊑",麗:"麗",麟:"麟","⿆":"麥","⻨":"麦","麻":"麻","⿇":"麻","𪎒":"𪎒","⿈":"黃","⻩":"黄","⿉":"黍",黎:"黎","䵖":"䵖","⿊":"黑",黒:"黑","墨":"墨","黹":"黹","⿋":"黹","⿌":"黽","鼅":"鼅","黾":"黾","⿍":"鼎","鼏":"鼏","⿎":"鼓","鼖":"鼖","⿏":"鼠","鼻":"鼻","⿐":"鼻","齃":"齃","⿑":"齊","⻬":"齐","⿒":"齒","𪘀":"𪘀","⻮":"齿",龍:"龍","⿓":"龍","龎":"龎","⻰":"龙",龜:"龜",龜:"龜","龜":"龜","⿔":"龜","⻳":"龟","⿕":"龠"};var tD=Oq;function Pq(r){return r.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")}var Mq=RegExp(Object.keys(tD).map(Pq).join("|"),"g");function Aq(r){return tD[r]}function Dq(r){return r.replace(Mq,Aq)}var Nq=Dq;const Lq=qa(Nq);var fm={exports:{}},rD={};function ei(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var Uq=ei;ei.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};ei.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};ei.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};ei.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};ei.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};ei.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};ei.prototype.start=ei.prototype.try;ei.prototype.errors=function(){return this._errors};ei.prototype.attempts=function(){return this._attempts};ei.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(r[o]||0)+1;r[o]=s,s>=t&&(e=i,t=s)}return e};(function(r){var e=Uq;r.operation=function(t){var n=r.timeouts(t);return new e(n,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},r.timeouts=function(t){if(t instanceof Array)return[].concat(t);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in t)n[i]=t[i];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],s=0;s<n.retries;s++)o.push(this.createTimeout(s,n));return t&&t.forever&&!o.length&&o.push(this.createTimeout(s,n)),o.sort(function(a,l){return a-l}),o},r.createTimeout=function(t,n){var i=n.randomize?Math.random()+1:1,o=Math.round(i*Math.max(n.minTimeout,1)*Math.pow(n.factor,t));return o=Math.min(o,n.maxTimeout),o},r.wrap=function(t,n,i){if(n instanceof Array&&(i=n,n=null),!i){i=[];for(var o in t)typeof t[o]=="function"&&i.push(o)}for(var s=0;s<i.length;s++){var a=i[s],l=t[a];t[a]=(function(u){var d=r.operation(n),f=Array.prototype.slice.call(arguments,1),p=f.pop();f.push(function(h){d.retry(h)||(h&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){u.apply(t,f)})}).bind(t,l),t[a].options=n}}})(rD);var jq=rD;const Fq=jq,Bq=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class nD extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Kq=(r,e,t)=>{const n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r},Vq=r=>Bq.includes(r),iD=(r,e)=>new Promise((t,n)=>{e={onFailedAttempt:()=>{},retries:10,...e};const i=Fq.operation(e);i.attempt(async o=>{try{t(await r(o))}catch(s){if(!(s instanceof Error)){n(new TypeError(`Non-error was thrown: "${s}". You should only throw errors.`));return}if(s instanceof nD)i.stop(),n(s.originalError);else if(s instanceof TypeError&&!Vq(s.message))i.stop(),n(s);else{Kq(s,o,e);try{await e.onFailedAttempt(s)}catch(a){n(a);return}i.retry(s)||n(i.mainError())}}})});fm.exports=iD;fm.exports.default=iD;fm.exports.AbortError=nD;var $q=fm.exports;const oD=qa($q);let hm=class{constructor(e,t){if(this.stable=e,this.unstable=t,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}get name(){return this.stable?this.stable:this.unstable}get altName(){return this.stable?this.unstable:null}get names(){var e=[this.name],t=this.altName;return t&&e.push(t),e}matches(e){return this.name===e||this.altName===e}findIn(e){var t=void 0;return this.name&&(t=e==null?void 0:e[this.name]),!t&&this.altName&&(t=e==null?void 0:e[this.altName]),t}includedIn(e){var t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}};class pm extends hm{constructor(){super(...arguments),v(this,"preferUnstable",!1)}setPreferUnstable(e){this.preferUnstable=e}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}}let Bt=class extends hm{constructor(e,t){if(super(e,t),!this.unstable)throw new Error("Unstable value must be supplied")}get name(){return this.unstable}get altName(){return this.stable}};var ln={},vm={},mf={};Object.defineProperty(mf,"__esModule",{value:!0});mf.NamespacedMap=void 0;function Wq(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=qq(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
280
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function qq(r,e){if(r){if(typeof r=="string")return YR(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return YR(r,e)}}function YR(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function Gq(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function Hq(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function zq(r,e,t){return e&&Hq(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}function Yq(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var Jq=function(){function r(e){if(Gq(this,r),Yq(this,"internalMap",new Map),e){var t=Wq(e),n;try{for(t.s();!(n=t.n()).done;){var i=n.value;this.set(i[0],i[1])}}catch(o){t.e(o)}finally{t.f()}}}return zq(r,[{key:"get",value:function(t){return t.name&&this.internalMap.has(t.name)?this.internalMap.get(t.name):t.altName&&this.internalMap.has(t.altName)?this.internalMap.get(t.altName):null}},{key:"set",value:function(t,n){t.name&&this.internalMap.set(t.name,n),t.altName&&this.internalMap.set(t.altName,n)}},{key:"has",value:function(t){return!!this.get(t)}},{key:"delete",value:function(t){t.name&&this.internalMap.delete(t.name),t.altName&&this.internalMap.delete(t.altName)}},{key:"hasNamespaced",value:function(t){return this.internalMap.has(t)}},{key:"getNamespaced",value:function(t){return this.internalMap.get(t)}}]),r}();mf.NamespacedMap=Jq;var Fo={};function tb(r){"@babel/helpers - typeof";return tb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},tb(r)}Object.defineProperty(Fo,"__esModule",{value:!0});Fo.InvalidEventError=void 0;function Xq(r,e,t){return Object.defineProperty(r,"prototype",{writable:!1}),r}function Qq(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function Zq(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&Ld(r,e)}function eG(r){var e=sD();return function(){var n=Ud(r),i;if(e){var o=Ud(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return tG(this,i)}}function tG(r,e){if(e&&(tb(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return rG(r)}function rG(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function rb(r){var e=typeof Map=="function"?new Map:void 0;return rb=function(n){if(n===null||!nG(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(typeof e<"u"){if(e.has(n))return e.get(n);e.set(n,i)}function i(){return Jh(n,arguments,Ud(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Ld(i,n)},rb(r)}function Jh(r,e,t){return sD()?Jh=Reflect.construct:Jh=function(i,o,s){var a=[null];a.push.apply(a,o);var l=Function.bind.apply(i,a),c=new l;return s&&Ld(c,s.prototype),c},Jh.apply(null,arguments)}function sD(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function nG(r){return Function.toString.call(r).indexOf("[native code]")!==-1}function Ld(r,e){return Ld=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},Ld(r,e)}function Ud(r){return Ud=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Ud(r)}var iG=function(r){Zq(t,r);var e=eG(t);function t(n){return Qq(this,t),e.call(this,n)}return Xq(t)}(rb(Error));Fo.InvalidEventError=iG;var Uc={},oo={},qs={};Object.defineProperty(qs,"__esModule",{value:!0});qs.ExtensibleEvent=void 0;function oG(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function sG(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function aG(r,e,t){return e&&sG(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}var lG=function(){function r(e){oG(this,r),this.wireFormat=e}return aG(r,[{key:"wireContent",get:function(){return this.wireFormat.content}}]),r}();qs.ExtensibleEvent=lG;var gf={};Object.defineProperty(gf,"__esModule",{value:!0});gf.isOptionalAString=cG;gf.isProvided=aD;function cG(r){return aD(r)&&typeof r=="string"}function aD(r){return r!=null}var Xt={},ki={};function nb(r){"@babel/helpers - typeof";return nb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nb(r)}Object.defineProperty(ki,"__esModule",{value:!0});ki.UnstableValue=ki.NamespacedValue=void 0;function uG(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&ib(r,e)}function ib(r,e){return ib=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},ib(r,e)}function dG(r){var e=pG();return function(){var n=Zp(r),i;if(e){var o=Zp(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return fG(this,i)}}function fG(r,e){if(e&&(nb(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return hG(r)}function hG(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function pG(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Zp(r){return Zp=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Zp(r)}function lD(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function vG(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function cD(r,e,t){return e&&vG(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}var uD=function(){function r(e,t){if(lD(this,r),this.stable=e,this.unstable=t,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}return cD(r,[{key:"name",get:function(){return this.stable?this.stable:this.unstable}},{key:"altName",get:function(){return this.stable?this.unstable:null}},{key:"matches",value:function(t){return!!this.name&&this.name===t||!!this.altName&&this.altName===t}},{key:"findIn",value:function(t){var n;return this.name&&(n=t==null?void 0:t[this.name]),!n&&this.altName&&(n=t==null?void 0:t[this.altName]),n}},{key:"includedIn",value:function(t){var n=!1;return this.name&&(n=t.includes(this.name)),!n&&this.altName&&(n=t.includes(this.altName)),n}}]),r}();ki.NamespacedValue=uD;var mG=function(r){uG(t,r);var e=dG(t);function t(n,i){var o;if(lD(this,t),o=e.call(this,n,i),!o.unstable)throw new Error("Unstable value must be supplied");return o}return cD(t,[{key:"name",get:function(){return this.unstable}},{key:"altName",get:function(){return this.stable}}]),t}(uD);ki.UnstableValue=mG;Object.defineProperty(Xt,"__esModule",{value:!0});Xt.M_TEXT=Xt.M_NOTICE=Xt.M_MESSAGE=Xt.M_HTML=Xt.M_EMOTE=void 0;var yf=ki,gG=new yf.UnstableValue("m.message","org.matrix.msc1767.message");Xt.M_MESSAGE=gG;var yG=new yf.UnstableValue("m.text","org.matrix.msc1767.text");Xt.M_TEXT=yG;var SG=new yf.UnstableValue("m.html","org.matrix.msc1767.html");Xt.M_HTML=SG;var bG=new yf.UnstableValue("m.emote","org.matrix.msc1767.emote");Xt.M_EMOTE=bG;var _G=new yf.UnstableValue("m.notice","org.matrix.msc1767.notice");Xt.M_NOTICE=_G;var Bo={};Object.defineProperty(Bo,"__esModule",{value:!0});Bo.isEventTypeSame=EG;function EG(r,e){if(typeof r=="string")return typeof e=="string"?e===r:e.matches(r);if(typeof e=="string")return r.matches(e);var t=e,n=r;return t.matches(n.name)||t.matches(n.altName)}function ob(r){"@babel/helpers - typeof";return ob=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ob(r)}Object.defineProperty(oo,"__esModule",{value:!0});oo.MessageEvent=void 0;var wG=qs,au=gf,Wg=Fo,kn=Xt,TG=Bo;function JR(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function XR(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?JR(Object(t),!0).forEach(function(n){es(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):JR(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function RG(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function QR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function CG(r,e,t){return e&&QR(r.prototype,e),t&&QR(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function kG(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&sb(r,e)}function sb(r,e){return sb=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},sb(r,e)}function IG(r){var e=OG();return function(){var n=ev(r),i;if(e){var o=ev(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return xG(this,i)}}function xG(r,e){if(e&&(ob(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Xh(r)}function Xh(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function OG(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function ev(r){return ev=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},ev(r)}function es(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var PG=function(r){kG(t,r);var e=IG(t);function t(n){var i;RG(this,t),i=e.call(this,n),es(Xh(i),"text",void 0),es(Xh(i),"html",void 0),es(Xh(i),"renderings",void 0);var o=kn.M_MESSAGE.findIn(i.wireContent),s=kn.M_TEXT.findIn(i.wireContent),a=kn.M_HTML.findIn(i.wireContent);if((0,au.isProvided)(o)){if(!Array.isArray(o))throw new Wg.InvalidEventError("m.message contents must be an array");var l=o.find(function(u){return!(0,au.isProvided)(u.mimetype)||u.mimetype==="text/plain"}),c=o.find(function(u){return u.mimetype==="text/html"});if(!l)throw new Wg.InvalidEventError("m.message is missing a plain text representation");i.text=l.body,i.html=c==null?void 0:c.body,i.renderings=o}else if((0,au.isOptionalAString)(s))i.text=s,i.html=a,i.renderings=[{body:s,mimetype:"text/plain"}],i.html&&i.renderings.push({body:i.html,mimetype:"text/html"});else throw new Wg.InvalidEventError("Missing textual representation for event");return i}return CG(t,[{key:"isEmote",get:function(){return kn.M_EMOTE.matches(this.wireFormat.type)||(0,au.isProvided)(kn.M_EMOTE.findIn(this.wireFormat.content))}},{key:"isNotice",get:function(){return kn.M_NOTICE.matches(this.wireFormat.type)||(0,au.isProvided)(kn.M_NOTICE.findIn(this.wireFormat.content))}},{key:"isEquivalentTo",value:function(i){return(0,TG.isEventTypeSame)(i,kn.M_MESSAGE)}},{key:"serializeMMessageOnly",value:function(){var i=es({},kn.M_MESSAGE.name,this.renderings);if(this.renderings.length===1){var o=this.renderings[0].mimetype;(o===void 0||o==="text/plain")&&(i=es({},kn.M_TEXT.name,this.renderings[0].body))}return i}},{key:"serialize",value:function(){var i;return{type:"m.room.message",content:XR(XR({},this.serializeMMessageOnly()),{},{body:this.text,msgtype:"m.text",format:this.html?"org.matrix.custom.html":void 0,formatted_body:(i=this.html)!==null&&i!==void 0?i:void 0})}}}],[{key:"from",value:function(i,o){var s;return new t({type:kn.M_MESSAGE.name,content:(s={},es(s,kn.M_TEXT.name,i),es(s,kn.M_HTML.name,o),s)})}}]),t}(wG.ExtensibleEvent);oo.MessageEvent=PG;var jc={};function ab(r){"@babel/helpers - typeof";return ab=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ab(r)}Object.defineProperty(jc,"__esModule",{value:!0});jc.NoticeEvent=void 0;var MG=oo,fh=Xt,AG=Bo;function ZR(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function DG(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function eC(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function NG(r,e,t){return e&&eC(r.prototype,e),t&&eC(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function Qu(){return typeof Reflect<"u"&&Reflect.get?Qu=Reflect.get:Qu=function(e,t,n){var i=LG(e,t);if(i){var o=Object.getOwnPropertyDescriptor(i,t);return o.get?o.get.call(arguments.length<3?e:n):o.value}},Qu.apply(this,arguments)}function LG(r,e){for(;!Object.prototype.hasOwnProperty.call(r,e)&&(r=Fa(r),r!==null););return r}function UG(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&lb(r,e)}function lb(r,e){return lb=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},lb(r,e)}function jG(r){var e=KG();return function(){var n=Fa(r),i;if(e){var o=Fa(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return FG(this,i)}}function FG(r,e){if(e&&(ab(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return BG(r)}function BG(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function KG(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Fa(r){return Fa=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Fa(r)}var VG=function(r){UG(t,r);var e=jG(t);function t(n){return DG(this,t),e.call(this,n)}return NG(t,[{key:"isNotice",get:function(){return!0}},{key:"isEquivalentTo",value:function(i){return(0,AG.isEventTypeSame)(i,fh.M_NOTICE)||Qu(Fa(t.prototype),"isEquivalentTo",this).call(this,i)}},{key:"serialize",value:function(){var i=Qu(Fa(t.prototype),"serialize",this).call(this);return i.content.msgtype="m.notice",i}}],[{key:"from",value:function(i,o){var s;return new t({type:fh.M_NOTICE.name,content:(s={},ZR(s,fh.M_TEXT.name,i),ZR(s,fh.M_HTML.name,o),s)})}}]),t}(MG.MessageEvent);jc.NoticeEvent=VG;var Fc={};function cb(r){"@babel/helpers - typeof";return cb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},cb(r)}Object.defineProperty(Fc,"__esModule",{value:!0});Fc.EmoteEvent=void 0;var $G=oo,hh=Xt,WG=Bo;function tC(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function qG(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function rC(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function GG(r,e,t){return e&&rC(r.prototype,e),t&&rC(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function Zu(){return typeof Reflect<"u"&&Reflect.get?Zu=Reflect.get:Zu=function(e,t,n){var i=HG(e,t);if(i){var o=Object.getOwnPropertyDescriptor(i,t);return o.get?o.get.call(arguments.length<3?e:n):o.value}},Zu.apply(this,arguments)}function HG(r,e){for(;!Object.prototype.hasOwnProperty.call(r,e)&&(r=Ba(r),r!==null););return r}function zG(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&ub(r,e)}function ub(r,e){return ub=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},ub(r,e)}function YG(r){var e=QG();return function(){var n=Ba(r),i;if(e){var o=Ba(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return JG(this,i)}}function JG(r,e){if(e&&(cb(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return XG(r)}function XG(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function QG(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Ba(r){return Ba=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},Ba(r)}var ZG=function(r){zG(t,r);var e=YG(t);function t(n){return qG(this,t),e.call(this,n)}return GG(t,[{key:"isEmote",get:function(){return!0}},{key:"isEquivalentTo",value:function(i){return(0,WG.isEventTypeSame)(i,hh.M_EMOTE)||Zu(Ba(t.prototype),"isEquivalentTo",this).call(this,i)}},{key:"serialize",value:function(){var i=Zu(Ba(t.prototype),"serialize",this).call(this);return i.content.msgtype="m.emote",i}}],[{key:"from",value:function(i,o){var s;return new t({type:hh.M_EMOTE.name,content:(s={},tC(s,hh.M_TEXT.name,i),tC(s,hh.M_HTML.name,o),s)})}}]),t}($G.MessageEvent);Fc.EmoteEvent=ZG;Object.defineProperty(Uc,"__esModule",{value:!0});Uc.LEGACY_M_ROOM_MESSAGE=void 0;Uc.parseMRoomMessage=i6;var nC=oo,e6=jc,t6=Fc,r6=ki,zo=Xt;function iC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function $n(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?iC(Object(t),!0).forEach(function(n){ua(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):iC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function ua(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var n6=new r6.NamespacedValue("m.room.message");Uc.LEGACY_M_ROOM_MESSAGE=n6;function i6(r){var e,t,n;if(zo.M_MESSAGE.findIn(r.content)||zo.M_TEXT.findIn(r.content))return new nC.MessageEvent(r);var i=(e=r.content)===null||e===void 0?void 0:e.msgtype,o=(t=r.content)===null||t===void 0?void 0:t.body,s=((n=r.content)===null||n===void 0?void 0:n.format)==="org.matrix.custom.html"?r.content.formatted_body:null;if(i==="m.text"){var a;return new nC.MessageEvent($n($n({},r),{},{content:$n($n({},r.content),{},(a={},ua(a,zo.M_TEXT.name,o),ua(a,zo.M_HTML.name,s),a))}))}else if(i==="m.notice"){var l;return new e6.NoticeEvent($n($n({},r),{},{content:$n($n({},r.content),{},(l={},ua(l,zo.M_TEXT.name,o),ua(l,zo.M_HTML.name,s),l))}))}else if(i==="m.emote"){var c;return new t6.EmoteEvent($n($n({},r),{},{content:$n($n({},r.content),{},(c={},ua(c,zo.M_TEXT.name,o),ua(c,zo.M_HTML.name,s),c))}))}else return null}var mm={};Object.defineProperty(mm,"__esModule",{value:!0});mm.parseMMessage=l6;var o6=oo,oC=Xt,s6=Fc,a6=jc;function l6(r){return oC.M_EMOTE.matches(r.type)?new s6.EmoteEvent(r):oC.M_NOTICE.matches(r.type)?new a6.NoticeEvent(r):new o6.MessageEvent(r)}var Mr={};Object.defineProperty(Mr,"__esModule",{value:!0});Mr.M_POLL_START=Mr.M_POLL_RESPONSE=Mr.M_POLL_KIND_UNDISCLOSED=Mr.M_POLL_KIND_DISCLOSED=Mr.M_POLL_END=void 0;var Sf=ki,c6=new Sf.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed");Mr.M_POLL_KIND_DISCLOSED=c6;var u6=new Sf.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed");Mr.M_POLL_KIND_UNDISCLOSED=u6;var d6=new Sf.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");Mr.M_POLL_START=d6;var f6=new Sf.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response");Mr.M_POLL_RESPONSE=f6;var h6=new Sf.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end");Mr.M_POLL_END=h6;var gm={},Ka={};function db(r){"@babel/helpers - typeof";return db=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},db(r)}Object.defineProperty(Ka,"__esModule",{value:!0});Ka.PollStartEvent=Ka.PollAnswerSubevent=void 0;var co=Mr,dD=oo,Mu=Xt,Qh=Fo,p6=ki,v6=Bo,m6=qs;function g6(r){return _6(r)||b6(r)||S6(r)||y6()}function y6(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
281
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function S6(r,e){if(r){if(typeof r=="string")return fb(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return fb(r,e)}}function b6(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function _6(r){if(Array.isArray(r))return fb(r)}function fb(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function sC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function E6(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?sC(Object(t),!0).forEach(function(n){vn(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):sC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function fD(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function aC(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function hD(r,e,t){return e&&aC(r.prototype,e),t&&aC(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function pD(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&hb(r,e)}function hb(r,e){return hb=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},hb(r,e)}function vD(r){var e=T6();return function(){var n=tv(r),i;if(e){var o=tv(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return w6(this,i)}}function w6(r,e){if(e&&(db(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ga(r)}function ga(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function T6(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function tv(r){return tv=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},tv(r)}function vn(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var mD=function(r){pD(t,r);var e=vD(t);function t(n){var i;fD(this,t),i=e.call(this,n),vn(ga(i),"id",void 0);var o=n.content.id;if(!o||typeof o!="string")throw new Qh.InvalidEventError("Answer ID must be a non-empty string");return i.id=o,i}return hD(t,[{key:"serialize",value:function(){return{type:"org.matrix.sdk.poll.answer",content:E6({id:this.id},this.serializeMMessageOnly())}}}],[{key:"from",value:function(i,o){return new t({type:"org.matrix.sdk.poll.answer",content:vn({id:i},Mu.M_TEXT.name,o)})}}]),t}(dD.MessageEvent);Ka.PollAnswerSubevent=mD;var R6=function(r){pD(t,r);var e=vD(t);function t(n){var i;fD(this,t),i=e.call(this,n),vn(ga(i),"question",void 0),vn(ga(i),"kind",void 0),vn(ga(i),"rawKind",void 0),vn(ga(i),"maxSelections",void 0),vn(ga(i),"answers",void 0);var o=co.M_POLL_START.findIn(i.wireContent);if(!o.question)throw new Qh.InvalidEventError("A question is required");if(i.question=new dD.MessageEvent({type:"org.matrix.sdk.poll.question",content:o.question}),i.rawKind=o.kind,co.M_POLL_KIND_DISCLOSED.matches(i.rawKind)?i.kind=co.M_POLL_KIND_DISCLOSED:i.kind=co.M_POLL_KIND_UNDISCLOSED,i.maxSelections=Number.isFinite(o.max_selections)&&o.max_selections>0?o.max_selections:1,!Array.isArray(o.answers))throw new Qh.InvalidEventError("Poll answers must be an array");var s=o.answers.slice(0,20).map(function(a){return new mD({type:"org.matrix.sdk.poll.answer",content:a})});if(s.length<=0)throw new Qh.InvalidEventError("No answers available");return i.answers=s,i}return hD(t,[{key:"isEquivalentTo",value:function(i){return(0,v6.isEventTypeSame)(i,co.M_POLL_START)}},{key:"serialize",value:function(){var i;return{type:co.M_POLL_START.name,content:(i={},vn(i,co.M_POLL_START.name,{question:this.question.serialize().content,kind:this.rawKind,max_selections:this.maxSelections,answers:this.answers.map(function(o){return o.serialize().content})}),vn(i,Mu.M_TEXT.name,"".concat(this.question.text,`
282
- `).concat(this.answers.map(function(o,s){return"".concat(s+1,". ").concat(o.text)}).join(`
283
- `))),i)}}}],[{key:"from",value:function(i,o,s){var a,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;return new t({type:co.M_POLL_START.name,content:(a={},vn(a,Mu.M_TEXT.name,i),vn(a,co.M_POLL_START.name,{question:vn({},Mu.M_TEXT.name,i),kind:s instanceof p6.NamespacedValue?s.name:s,max_selections:l,answers:o.map(function(c){return vn({id:C6()},Mu.M_TEXT.name,c)})}),a)})}}]),t}(m6.ExtensibleEvent);Ka.PollStartEvent=R6;var lC="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function C6(){return g6(Array(16)).map(function(){return lC.charAt(Math.floor(Math.random()*lC.length))}).join("")}var bf={},Bc={};Object.defineProperty(Bc,"__esModule",{value:!0});Bc.REFERENCE_RELATION=void 0;var k6=ki,I6=new k6.NamespacedValue("m.reference");Bc.REFERENCE_RELATION=I6;function pb(r){"@babel/helpers - typeof";return pb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},pb(r)}Object.defineProperty(bf,"__esModule",{value:!0});bf.PollResponseEvent=void 0;var x6=qs,ll=Mr,O6=Fo,qg=Bc,P6=Bo;function M6(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function cC(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function A6(r,e,t){return e&&cC(r.prototype,e),t&&cC(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function D6(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&vb(r,e)}function vb(r,e){return vb=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},vb(r,e)}function N6(r){var e=U6();return function(){var n=rv(r),i;if(e){var o=rv(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return L6(this,i)}}function L6(r,e){if(e&&(pb(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Zh(r)}function Zh(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function U6(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function rv(r){return rv=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},rv(r)}function lu(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var j6=function(r){D6(t,r);var e=N6(t);function t(n){var i;M6(this,t),i=e.call(this,n),lu(Zh(i),"internalAnswerIds",void 0),lu(Zh(i),"internalSpoiled",void 0),lu(Zh(i),"pollEventId",void 0);var o=i.wireContent["m.relates_to"];if(!qg.REFERENCE_RELATION.matches(o==null?void 0:o.rel_type)||typeof(o==null?void 0:o.event_id)!="string")throw new O6.InvalidEventError("Relationship must be a reference to an event");return i.pollEventId=o.event_id,i.validateAgainst(null),i}return A6(t,[{key:"answerIds",get:function(){return this.internalAnswerIds}},{key:"spoiled",get:function(){return this.internalSpoiled}},{key:"validateAgainst",value:function(i){var o=ll.M_POLL_RESPONSE.findIn(this.wireContent);if(!Array.isArray(o==null?void 0:o.answers)){this.internalSpoiled=!0,this.internalAnswerIds=[];return}var s=o.answers;if(s.some(function(a){return typeof a!="string"})||s.length===0){this.internalSpoiled=!0,this.internalAnswerIds=[];return}if(i){if(s.some(function(a){return!i.answers.some(function(l){return l.id===a})})){this.internalSpoiled=!0,this.internalAnswerIds=[];return}s=s.slice(0,i.maxSelections)}this.internalAnswerIds=s,this.internalSpoiled=!1}},{key:"isEquivalentTo",value:function(i){return(0,P6.isEventTypeSame)(i,ll.M_POLL_RESPONSE)}},{key:"serialize",value:function(){return{type:ll.M_POLL_RESPONSE.name,content:lu({"m.relates_to":{rel_type:qg.REFERENCE_RELATION.name,event_id:this.pollEventId}},ll.M_POLL_RESPONSE.name,{answers:this.spoiled?void 0:this.answerIds})}}}],[{key:"from",value:function(i,o){return new t({type:ll.M_POLL_RESPONSE.name,content:lu({"m.relates_to":{rel_type:qg.REFERENCE_RELATION.name,event_id:o}},ll.M_POLL_RESPONSE.name,{answers:i})})}}]),t}(x6.ExtensibleEvent);bf.PollResponseEvent=j6;var _f={};function mb(r){"@babel/helpers - typeof";return mb=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},mb(r)}Object.defineProperty(_f,"__esModule",{value:!0});_f.PollEndEvent=void 0;var cu=Mr,F6=Fo,Gg=Bc,B6=oo,K6=Xt,V6=Bo,$6=qs;function uC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function W6(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?uC(Object(t),!0).forEach(function(n){bl(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):uC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function q6(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function dC(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function G6(r,e,t){return e&&dC(r.prototype,e),t&&dC(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function H6(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&gb(r,e)}function gb(r,e){return gb=Object.setPrototypeOf||function(n,i){return n.__proto__=i,n},gb(r,e)}function z6(r){var e=J6();return function(){var n=nv(r),i;if(e){var o=nv(this).constructor;i=Reflect.construct(n,arguments,o)}else i=n.apply(this,arguments);return Y6(this,i)}}function Y6(r,e){if(e&&(mb(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return yb(r)}function yb(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function J6(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function nv(r){return nv=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},nv(r)}function bl(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var X6=function(r){H6(t,r);var e=z6(t);function t(n){var i;q6(this,t),i=e.call(this,n),bl(yb(i),"pollEventId",void 0),bl(yb(i),"closingMessage",void 0);var o=i.wireContent["m.relates_to"];if(!Gg.REFERENCE_RELATION.matches(o==null?void 0:o.rel_type)||typeof(o==null?void 0:o.event_id)!="string")throw new F6.InvalidEventError("Relationship must be a reference to an event");return i.pollEventId=o.event_id,i.closingMessage=new B6.MessageEvent(i.wireFormat),i}return G6(t,[{key:"isEquivalentTo",value:function(i){return(0,V6.isEventTypeSame)(i,cu.M_POLL_END)}},{key:"serialize",value:function(){return{type:cu.M_POLL_END.name,content:W6(bl({"m.relates_to":{rel_type:Gg.REFERENCE_RELATION.name,event_id:this.pollEventId}},cu.M_POLL_END.name,{}),this.closingMessage.serialize().content)}}}],[{key:"from",value:function(i,o){var s;return new t({type:cu.M_POLL_END.name,content:(s={"m.relates_to":{rel_type:Gg.REFERENCE_RELATION.name,event_id:i}},bl(s,cu.M_POLL_END.name,{}),bl(s,K6.M_TEXT.name,o),s)})}}]),t}($6.ExtensibleEvent);_f.PollEndEvent=X6;Object.defineProperty(gm,"__esModule",{value:!0});gm.parseMPoll=tH;var Hg=Mr,Q6=Ka,Z6=bf,eH=_f;function tH(r){return Hg.M_POLL_START.matches(r.type)?new Q6.PollStartEvent(r):Hg.M_POLL_RESPONSE.matches(r.type)?new Z6.PollResponseEvent(r):Hg.M_POLL_END.matches(r.type)?new eH.PollEndEvent(r):null}Object.defineProperty(vm,"__esModule",{value:!0});vm.ExtensibleEvents=void 0;var rH=mf,nH=Fo,fC=Uc,zg=mm,ph=Xt,Yg=Mr,Jg=gm;function iH(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=oH(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
284
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function oH(r,e){if(r){if(typeof r=="string")return hC(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return hC(r,e)}}function hC(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function sH(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function pC(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,n.key,n)}}function aH(r,e,t){return e&&pC(r.prototype,e),t&&pC(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function Sb(r,e,t){return e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}var bb=function(){function r(){sH(this,r),Sb(this,"interpreters",new rH.NamespacedMap([[fC.LEGACY_M_ROOM_MESSAGE,fC.parseMRoomMessage],[ph.M_MESSAGE,zg.parseMMessage],[ph.M_EMOTE,zg.parseMMessage],[ph.M_NOTICE,zg.parseMMessage],[Yg.M_POLL_START,Jg.parseMPoll],[Yg.M_POLL_RESPONSE,Jg.parseMPoll],[Yg.M_POLL_END,Jg.parseMPoll]])),Sb(this,"_unknownInterpretOrder",[ph.M_MESSAGE])}return aH(r,[{key:"unknownInterpretOrder",get:function(){var t;return(t=this._unknownInterpretOrder)!==null&&t!==void 0?t:[]},set:function(t){this._unknownInterpretOrder=t}},{key:"registerInterpreter",value:function(t,n){this.interpreters.set(t,n)}},{key:"parse",value:function(t){try{if(this.interpreters.hasNamespaced(t.type))return this.interpreters.getNamespaced(t.type)(t);var n=iH(this.unknownInterpretOrder),i;try{for(n.s();!(i=n.n()).done;){var o=i.value;if(this.interpreters.has(o)){var s=this.interpreters.get(o)(t);if(s)return s}}}catch(a){n.e(a)}finally{n.f()}return null}catch(a){if(a instanceof nH.InvalidEventError)return null;throw a}}}],[{key:"defaultInstance",get:function(){return r._defaultInstance}},{key:"unknownInterpretOrder",get:function(){return r.defaultInstance.unknownInterpretOrder},set:function(t){r.defaultInstance.unknownInterpretOrder=t}},{key:"registerInterpreter",value:function(t,n){r.defaultInstance.registerInterpreter(t,n)}},{key:"parse",value:function(t){return r.defaultInstance.parse(t)}}]),r}();vm.ExtensibleEvents=bb;Sb(bb,"_defaultInstance",new bb);var gD={};Object.defineProperty(gD,"__esModule",{value:!0});var Kc={};Object.defineProperty(Kc,"__esModule",{value:!0});Kc.LegacyMsgType=void 0;Kc.isEventLike=lH;var Xg=Xt,Jl;Kc.LegacyMsgType=Jl;(function(r){r.Text="m.text",r.Notice="m.notice",r.Emote="m.emote"})(Jl||(Kc.LegacyMsgType=Jl={}));function lH(r,e){var t=r.content;return e===Jl.Text?Xg.M_MESSAGE.matches(r.type)||r.type==="m.room.message"&&(t==null?void 0:t.msgtype)==="m.text":e===Jl.Emote?Xg.M_EMOTE.matches(r.type)||r.type==="m.room.message"&&(t==null?void 0:t.msgtype)==="m.emote":e===Jl.Notice?Xg.M_NOTICE.matches(r.type)||r.type==="m.room.message"&&(t==null?void 0:t.msgtype)==="m.notice":!1}(function(r){Object.defineProperty(r,"__esModule",{value:!0});var e=vm;Object.keys(e).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===e[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return e[T]}})});var t=gD;Object.keys(t).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===t[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return t[T]}})});var n=Fo;Object.keys(n).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===n[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return n[T]}})});var i=ki;Object.keys(i).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===i[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return i[T]}})});var o=mf;Object.keys(o).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===o[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return o[T]}})});var s=gf;Object.keys(s).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===s[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return s[T]}})});var a=Kc;Object.keys(a).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===a[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return a[T]}})});var l=Bo;Object.keys(l).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===l[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return l[T]}})});var c=Uc;Object.keys(c).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===c[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return c[T]}})});var u=mm;Object.keys(u).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===u[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return u[T]}})});var d=gm;Object.keys(d).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===d[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return d[T]}})});var f=Bc;Object.keys(f).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===f[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return f[T]}})});var p=qs;Object.keys(p).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===p[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return p[T]}})});var h=Xt;Object.keys(h).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===h[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return h[T]}})});var m=oo;Object.keys(m).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===m[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return m[T]}})});var E=Fc;Object.keys(E).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===E[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return E[T]}})});var y=jc;Object.keys(y).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===y[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return y[T]}})});var S=Mr;Object.keys(S).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===S[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return S[T]}})});var R=Ka;Object.keys(R).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===R[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return R[T]}})});var k=bf;Object.keys(k).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===k[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return k[T]}})});var x=_f;Object.keys(x).forEach(function(T){T==="default"||T==="__esModule"||T in r&&r[T]===x[T]||Object.defineProperty(r,T,{enumerable:!0,get:function(){return x[T]}})})})(ln);function Rw(r){return r!=null}var cH=new ln.UnstableValue("m.message","org.matrix.msc1767.message"),Cw=new ln.UnstableValue("m.text","org.matrix.msc1767.text"),uH=new ln.UnstableValue("m.html","org.matrix.msc1767.html"),yD=new ln.NamespacedValue("m.reference");function dH(r,e){if(typeof r=="string")return typeof e=="string"?e===r:e.matches(r);if(typeof e=="string")return r.matches(e);var t=e,n=r;return t.matches(n.name)||Rw(n.altName)&&t.matches(n.altName)}var yc=function(r){return r.Self="m.self",r.Pin="m.pin",r}({}),Ef=new Bt("m.asset","org.matrix.msc3488.asset"),Gs=new Bt("m.ts","org.matrix.msc3488.ts"),wf=new Bt("m.location","org.matrix.msc3488.location"),Xr=function(r){return r.Read="m.read",r.FullyRead="m.fully_read",r.ReadPrivate="m.read.private",r}({}),Tf="main";function vC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function mC(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?vC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):vC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Qg=new Map;function Zg(r){return r instanceof String&&(r=r.toString()),Qg.has(r)||Qg.set(r,r),Qg.get(r)}function _b(r,e){var t=e??new URLSearchParams,n=function(a){o!=null&&(Array.isArray(o)?o.forEach(l=>{t.append(a,String(l))}):t.append(a,String(o)))};for(var[i,o]of Object.entries(r))n(i);return t}function gC(r,e,t){var n=mC(mC({},t),{},{[e]:t[r]});return delete n[r],n}function Se(r,e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];n!=null&&(r=r.replace(t,encodeURIComponent(n)))}return r}function iv(r,e,t){var n;if(t){for(n=r.length-1;n>=0;n--)if(e(r[n],n,r))return r.splice(n,1),!0}else for(n=0;n<r.length;n++)if(e(r[n],n,r))return r.splice(n,1),!0;return!1}function SD(r,e){for(var t of e)if(!r.hasOwnProperty(t))throw new Error("Missing required key: "+t)}function ym(r){return JSON.parse(JSON.stringify(r))}function Va(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="number"&&isNaN(r)&&isNaN(e))return!0;if(r===null||e===null)return r===e;if(!(r instanceof Object)||r.constructor!==e.constructor||r.prototype!==e.prototype)return!1;if(r instanceof RegExp||r instanceof Date)return r.toString()===e.toString();if(Array.isArray(r)){if(r.length!==e.length)return!1;for(var t=0;t<r.length;t++)if(!Va(r[t],e[t]))return!1}else{for(var n in e)if(e.hasOwnProperty(n)!==r.hasOwnProperty(n))return!1;for(var i in r)if(e.hasOwnProperty(i)!==r.hasOwnProperty(i)||!Va(r[i],e[i]))return!1}return!0}function Eb(r){if(typeof r!="object"||r==null||Array.isArray(r))return r;var e=[];for(var[t,n]of Object.entries(r))e.push([t,Eb(n)]);return e.sort((i,o)=>ep(i[0],o[0])),e}function yC(r){return typeof r=="number"&&isFinite(r)}function ka(r){return typeof r=="string"?Lq(r.normalize("NFD").replace(hH,"")):""}function wb(r){return typeof r=="string"?r.replace(/[\u202d-\u202e]/g,""):""}function fH(r){return ka(r.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()}var hH=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g;function bD(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _D(r){return bD(r).replace(/\\\*/g,".*").replace(/\?/g,".")}function ey(r){return r!=null&&r.endsWith("/")?r.slice(0,-1):r}function As(r,e){return new Promise(t=>{setTimeout(t,r,e)})}function Cre(r,e,t){return Tb.apply(this,arguments)}function Tb(){return Tb=w(function*(r,e,t){var n=Date.now();try{return yield t()}finally{var i=Date.now();r.debug("[Perf]: ".concat(e," took ").concat(i-n,"ms"))}}),Tb.apply(this,arguments)}function pH(){return new Promise(r=>setTimeout(r))}function ED(r){return r==null}function Hs(){var r,e,t=new Promise((n,i)=>{r=n,e=i});return{resolve:r,reject:e,promise:t}}function Fl(r,e){return Rb.apply(this,arguments)}function Rb(){return Rb=w(function*(r,e){for(var t of r)yield e(yield t)}),Rb.apply(this,arguments)}function da(r){return Promise.resolve(r())}function vH(r,e){return Cb.apply(this,arguments)}function Cb(){return Cb=w(function*(r,e){for(var t=[],n=0;n<r.length;n+=e)t.push(...yield Promise.all(r.slice(n,n+e).map(i=>i())));return t}),Cb.apply(this,arguments)}function mH(r){return oD(e=>r(e),{forever:!0,factor:2,minTimeout:3e3,maxTimeout:15e3})}var Ds=(()=>{for(var r="",e=32;e<=126;e++)r+=String.fromCharCode(e);return r})();function SC(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ds;return r.padEnd(e,t[0])}function jd(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds,t=BigInt(e.length);if(r<=t){var n;return(n=e[Number(r)-1])!==null&&n!==void 0?n:""}var i=r/t,o=Number(r%t)-1;return o<0&&(i-=BigInt(Math.abs(o)),o=Number(t)-1),jd(i,e)+e[o]}function ov(r){for(var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds,t=BigInt(e.length),n=BigInt(0),i=r.length-1,o=BigInt(0);i>=0;i--,o++){var s=r.charCodeAt(i)-e.charCodeAt(0);n+=BigInt(1+s)*t**o}return n}function gH(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ds,n=Math.max(r.length,e.length),i=ov(SC(r,n,t),t),o=ov(SC(e,n,t),t),s=(i+o)/BigInt(2);return s===i||s==o?jd(s,t)+t[0]:jd(s,t)}function uu(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds;return jd(ov(r,e)+BigInt(1),e)}function bC(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ds;return jd(ov(r,e)-BigInt(1),e)}function ep(r,e){return r<e?-1:r>e?1:0}function wD(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;for(var[n,i]of Object.entries(e)){if(r[n]instanceof Object&&i){wD(r[n],i);continue}if(i!=null||!t){Qi(r,n,i);continue}}return r}function _C(r){var e;return(e=Gs.findIn(r.getContent()))!==null&&e!==void 0?e:-1}function yH(r,e){return _C(e)-_C(r)}function kw(r){return[Xr.Read,Xr.ReadPrivate].includes(r)}function EC(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:(s,a)=>s===a;if(r.size!==e.size)return!1;for(var[n,i]of r){var o=e.get(n);if(o===void 0||!t(i,o))return!1}return!0}function TD(r){return r instanceof Map?ms(r):Array.isArray(r)?r.map(e=>TD(e)):r}function ms(r){var e=new Map;for(var[t,n]of r)e.set(t,TD(n));return Object.fromEntries(e.entries())}function ed(r){return r==="__proto__"||r==="prototype"||r==="constructor"}function Qi(r,e,t){if(ed(e))throw new Error("Trying to modify prototype or constructor");r[e]=t}function mi(r){return!(ed(r.room_id)||ed(r.sender)||ed(r.event_id))}class Gt extends Map{constructor(e){super(),this.createDefault=e}getOrCreate(e){return this.has(e)||this.set(e,this.createDefault()),this.get(e)}}var kb="migrationState",Sc=function(r){return r[r.NOT_STARTED=0]="NOT_STARTED",r[r.INITIAL_DATA_MIGRATED=1]="INITIAL_DATA_MIGRATED",r[r.OLM_SESSIONS_MIGRATED=2]="OLM_SESSIONS_MIGRATED",r[r.MEGOLM_SESSIONS_MIGRATED=3]="MEGOLM_SESSIONS_MIGRATED",r[r.ROOM_SETTINGS_MIGRATED=4]="ROOM_SETTINGS_MIGRATED",r[r.INITIAL_OWN_KEY_QUERY_DONE=5]="INITIAL_OWN_KEY_QUERY_DONE",r}({}),bc=50;function wC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Yo(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?wC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):wC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function Zs(r,e){return encodeURIComponent(r)+"/"+encodeURIComponent(e)}function ty(r){var e=r.split("/"),t=decodeURIComponent(e[0]),n=decodeURIComponent(e[1]);return{senderKey:t,sessionId:n}}class Sm{constructor(){v(this,"migrationState",Sc.NOT_STARTED),v(this,"outgoingRoomKeyRequests",[]),v(this,"account",null),v(this,"crossSigningKeys",null),v(this,"privateKeys",{}),v(this,"sessions",{}),v(this,"sessionProblems",{}),v(this,"notifiedErrorDevices",{}),v(this,"inboundGroupSessions",{}),v(this,"inboundGroupSessionsWithheld",{}),v(this,"deviceData",null),v(this,"rooms",{}),v(this,"sessionsNeedingBackup",{}),v(this,"sharedHistoryInboundGroupSessions",{}),v(this,"parkedSharedHistory",new Map)}containsData(){var e=this;return w(function*(){return e.account!==null})()}startup(){var e=this;return w(function*(){return e})()}deleteAllData(){return Promise.resolve()}getMigrationState(){var e=this;return w(function*(){return e.migrationState})()}setMigrationState(e){var t=this;return w(function*(){t.migrationState=e})()}getOrAddOutgoingRoomKeyRequest(e){var t=e.requestBody;return da(()=>{var n=this._getOutgoingRoomKeyRequest(t);return n?(b.log("already have key request outstanding for "+"".concat(t.room_id," / ").concat(t.session_id,": ")+"not sending another"),n):(b.log("enqueueing key request for ".concat(t.room_id," / ")+t.session_id),this.outgoingRoomKeyRequests.push(e),e)})}getOutgoingRoomKeyRequest(e){return Promise.resolve(this._getOutgoingRoomKeyRequest(e))}_getOutgoingRoomKeyRequest(e){for(var t of this.outgoingRoomKeyRequests)if(Va(t.requestBody,e))return t;return null}getOutgoingRoomKeyRequestByState(e){for(var t of this.outgoingRoomKeyRequests)for(var n of e)if(t.state===n)return Promise.resolve(t);return Promise.resolve(null)}getAllOutgoingRoomKeyRequestsByState(e){return Promise.resolve(this.outgoingRoomKeyRequests.filter(t=>t.state==e))}getOutgoingRoomKeyRequestsByTarget(e,t,n){var i=[];for(var o of this.outgoingRoomKeyRequests)for(var s of n)o.state===s&&o.recipients.some(a=>a.userId===e&&a.deviceId===t)&&i.push(o);return Promise.resolve(i)}updateOutgoingRoomKeyRequest(e,t,n){for(var i of this.outgoingRoomKeyRequests)if(i.requestId===e)return i.state!==t?(b.warn("Cannot update room key request from ".concat(t," ")+"as it was already updated to ".concat(i.state)),Promise.resolve(null)):(Object.assign(i,n),Promise.resolve(i));return Promise.resolve(null)}deleteOutgoingRoomKeyRequest(e,t){for(var n=0;n<this.outgoingRoomKeyRequests.length;n++){var i=this.outgoingRoomKeyRequests[n];if(i.requestId===e)return i.state!=t?(b.warn("Cannot delete room key request in state ".concat(i.state," ")+"(expected ".concat(t,")")),Promise.resolve(null)):(this.outgoingRoomKeyRequests.splice(n,1),Promise.resolve(i))}return Promise.resolve(null)}getAccount(e,t){t(this.account)}storeAccount(e,t){this.account=t}getCrossSigningKeys(e,t){t(this.crossSigningKeys)}getSecretStorePrivateKey(e,t,n){var i=this.privateKeys[n];t(i||null)}storeCrossSigningKeys(e,t){this.crossSigningKeys=t}storeSecretStorePrivateKey(e,t,n){this.privateKeys[t]=n}countEndToEndSessions(e,t){var n=0;for(var i of Object.values(this.sessions))n+=Object.keys(i).length;t(n)}getEndToEndSession(e,t,n,i){var o=this.sessions[e]||{};i(o[t]||null)}getEndToEndSessions(e,t,n){n(this.sessions[e]||{})}getAllEndToEndSessions(e,t){Object.entries(this.sessions).forEach(n=>{var[i,o]=n;Object.entries(o).forEach(s=>{var[a,l]=s;t(Yo(Yo({},l),{},{deviceKey:i,sessionId:a}))})})}storeEndToEndSession(e,t,n,i){var o=this.sessions[e];o===void 0&&(o={},this.sessions[e]=o),Qi(o,t,n)}storeEndToEndSessionProblem(e,t,n){var i=this;return w(function*(){var o=i.sessionProblems[e]=i.sessionProblems[e]||[];o.push({type:t,fixed:n,time:Date.now()}),o.sort((s,a)=>s.time-a.time)})()}getEndToEndSessionProblem(e,t){var n=this;return w(function*(){var i=n.sessionProblems[e]||[];if(!i.length)return null;var o=i[i.length-1];for(var s of i)if(s.time>t)return Object.assign({},s,{fixed:o.fixed});return o.fixed?null:o})()}filterOutNotifiedErrorDevices(e){var t=this;return w(function*(){var n=t.notifiedErrorDevices,i=[];for(var o of e){var{userId:s,deviceInfo:a}=o;s in n?a.deviceId in n[s]||(i.push(o),Qi(n[s],a.deviceId,!0)):(i.push(o),Qi(n,s,{[a.deviceId]:!0}))}return i})()}getEndToEndSessionsBatch(){var e=this;return w(function*(){var t=[];for(var n of Object.values(e.sessions))for(var i of Object.values(n))if(t.push(i),t.length>=bc)return t;return t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return w(function*(){for(var{deviceKey:n,sessionId:i}of e){var o=t.sessions[n]||{};delete o[i],Object.keys(o).length===0&&delete t.sessions[n]}})()}getEndToEndInboundGroupSession(e,t,n,i){var o=Zs(e,t);i(this.inboundGroupSessions[o]||null,this.inboundGroupSessionsWithheld[o]||null)}getAllEndToEndInboundGroupSessions(e,t){for(var n of Object.keys(this.inboundGroupSessions))t(Yo(Yo({},ty(n)),{},{sessionData:this.inboundGroupSessions[n]}));t(null)}addEndToEndInboundGroupSession(e,t,n,i){var o=Zs(e,t);this.inboundGroupSessions[o]===void 0&&(this.inboundGroupSessions[o]=n)}storeEndToEndInboundGroupSession(e,t,n,i){var o=Zs(e,t);this.inboundGroupSessions[o]=n}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){var o=Zs(e,t);this.inboundGroupSessionsWithheld[o]=n}countEndToEndInboundGroupSessions(){var e=this;return w(function*(){return Object.keys(e.inboundGroupSessions).length})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return w(function*(){var t=[];for(var[n,i]of Object.entries(e.inboundGroupSessions))if(t.push(Yo(Yo({},ty(n)),{},{sessionData:i,needsBackup:n in e.sessionsNeedingBackup})),t.length>=bc)return t;return t.length===0?null:t})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return w(function*(){for(var{senderKey:n,sessionId:i}of e){var o=Zs(n,i);delete t.inboundGroupSessions[o]}})()}getEndToEndDeviceData(e,t){t(this.deviceData)}storeEndToEndDeviceData(e,t){this.deviceData=e}storeEndToEndRoom(e,t,n){this.rooms[e]=t}getEndToEndRooms(e,t){t(this.rooms)}getSessionsNeedingBackup(e){var t=[];for(var n in this.sessionsNeedingBackup)if(this.inboundGroupSessions[n]&&(t.push(Yo(Yo({},ty(n)),{},{sessionData:this.inboundGroupSessions[n]})),e&&n.length>=e))break;return Promise.resolve(t)}countSessionsNeedingBackup(){return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length)}unmarkSessionsNeedingBackup(e){for(var t of e){var n=Zs(t.senderKey,t.sessionId);delete this.sessionsNeedingBackup[n]}return Promise.resolve()}markSessionsNeedingBackup(e){for(var t of e){var n=Zs(t.senderKey,t.sessionId);this.sessionsNeedingBackup[n]=!0}return Promise.resolve()}addSharedHistoryInboundGroupSession(e,t,n){var i=this.sharedHistoryInboundGroupSessions[e]||[];i.push([t,n]),this.sharedHistoryInboundGroupSessions[e]=i}getSharedHistoryInboundGroupSessions(e){return Promise.resolve(this.sharedHistoryInboundGroupSessions[e]||[])}addParkedSharedHistory(e,t){var n,i=(n=this.parkedSharedHistory.get(e))!==null&&n!==void 0?n:[];i.push(t),this.parkedSharedHistory.set(e,i)}takeParkedSharedHistory(e){var t,n=(t=this.parkedSharedHistory.get(e))!==null&&t!==void 0?t:[];return this.parkedSharedHistory.delete(e),Promise.resolve(n)}doTxn(e,t,n){return Promise.resolve(n(null))}}var SH=/^(?:(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?:\[[\dA-Fa-f:.]{2,45}])|(?:[A-Za-z\d\-.]{1,255}))(?::\d{1,5})?$/;function bH(r){var e=SH.exec(r);return(e==null?void 0:e[0])===r}var _H=/^[\w-]+$/;function EH(r){var e=_H.exec(r);return(e==null?void 0:e[0])===r}function bm(r,e,t,n,i){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1,s=arguments.length>6?arguments[6]:void 0,a=arguments.length>7?arguments[7]:void 0;if(typeof e!="string"||!e)return"";if(!e.startsWith("mxc://"))return o?e:"";var[l,c,...u]=e.slice(6).split("/");if(u.length>0||!bH(l)||!EH(c))return"";a&&(s=!0);var d,f=!!t||!!n||!!i,p=f?"thumbnail":"download";a?d="/_matrix/client/v1/media/".concat(p):d="/_matrix/media/v3/".concat(p);var h=new URL("".concat(d,"/").concat(l,"/").concat(c),r);return t&&h.searchParams.set("width",Math.round(t).toString()),n&&h.searchParams.set("height",Math.round(n).toString()),i&&h.searchParams.set("method",i),typeof s=="boolean"&&h.searchParams.set("allow_redirect",JSON.stringify(s)),h.href}var Iw={exports:{}},Xl=typeof Reflect=="object"?Reflect:null,TC=Xl&&typeof Xl.apply=="function"?Xl.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},tp;Xl&&typeof Xl.ownKeys=="function"?tp=Xl.ownKeys:Object.getOwnPropertySymbols?tp=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:tp=function(e){return Object.getOwnPropertyNames(e)};function wH(r){console&&console.warn&&console.warn(r)}var RD=Number.isNaN||function(e){return e!==e};function mt(){mt.init.call(this)}Iw.exports=mt;Iw.exports.once=kH;mt.EventEmitter=mt;mt.prototype._events=void 0;mt.prototype._eventsCount=0;mt.prototype._maxListeners=void 0;var RC=10;function _m(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(mt,"defaultMaxListeners",{enumerable:!0,get:function(){return RC},set:function(r){if(typeof r!="number"||r<0||RD(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");RC=r}});mt.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};mt.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||RD(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function CD(r){return r._maxListeners===void 0?mt.defaultMaxListeners:r._maxListeners}mt.prototype.getMaxListeners=function(){return CD(this)};mt.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var l=o[e];if(l===void 0)return!1;if(typeof l=="function")TC(l,this,t);else for(var c=l.length,u=PD(l,c),n=0;n<c;++n)TC(u[n],this,t);return!0};function kD(r,e,t,n){var i,o,s;if(_m(t),o=r._events,o===void 0?(o=r._events=Object.create(null),r._eventsCount=0):(o.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),o=r._events),s=o[e]),s===void 0)s=o[e]=t,++r._eventsCount;else if(typeof s=="function"?s=o[e]=n?[t,s]:[s,t]:n?s.unshift(t):s.push(t),i=CD(r),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=s.length,wH(a)}return r}mt.prototype.addListener=function(e,t){return kD(this,e,t,!1)};mt.prototype.on=mt.prototype.addListener;mt.prototype.prependListener=function(e,t){return kD(this,e,t,!0)};function TH(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ID(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},i=TH.bind(n);return i.listener=t,n.wrapFn=i,i}mt.prototype.once=function(e,t){return _m(t),this.on(e,ID(this,e,t)),this};mt.prototype.prependOnceListener=function(e,t){return _m(t),this.prependListener(e,ID(this,e,t)),this};mt.prototype.removeListener=function(e,t){var n,i,o,s,a;if(_m(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():RH(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};mt.prototype.off=mt.prototype.removeListener;mt.prototype.removeAllListeners=function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this};function xD(r,e,t){var n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?t?[i.listener||i]:[i]:t?CH(i):PD(i,i.length)}mt.prototype.listeners=function(e){return xD(this,e,!0)};mt.prototype.rawListeners=function(e){return xD(this,e,!1)};mt.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):OD.call(r,e)};mt.prototype.listenerCount=OD;function OD(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}mt.prototype.eventNames=function(){return this._eventsCount>0?tp(this._events):[]};function PD(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function RH(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function CH(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function kH(r,e){return new Promise(function(t,n){function i(s){r.removeListener(e,o),n(s)}function o(){typeof r.removeListener=="function"&&r.removeListener("error",i),t([].slice.call(arguments))}MD(r,e,o,{once:!0}),e!=="error"&&IH(r,i,{once:!0})})}function IH(r,e,t){typeof r.on=="function"&&MD(r,"error",e,t)}function MD(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function i(o){n.once&&r.removeEventListener(e,i),t(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}var Em=Iw.exports,AD=function(r){return r.NewListener="newListener",r.RemoveListener="removeListener",r.Error="error",r}({});class Tt extends Em.EventEmitter{addListener(e,t){return super.addListener(e,t)}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return super.emit(e,...n)}emitPromised(e){var t=arguments,n=this;return w(function*(){for(var i=t.length,o=new Array(i>1?i-1:0),s=1;s<i;s++)o[s-1]=t[s];var a=n.listeners(e);return Promise.allSettled(a.map(l=>l(...o))).then(()=>a.length>0)})()}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}off(e,t){return super.off(e,t)}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}prependListener(e,t){return super.prependListener(e,t)}prependOnceListener(e,t){return super.prependOnceListener(e,t)}removeAllListeners(e){return e===void 0?super.removeAllListeners():super.removeAllListeners(e)}removeListener(e,t){return super.removeListener(e,t)}rawListeners(e){return super.rawListeners(e)}}var xw=new Bt("m.beacon_info","org.matrix.msc3672.beacon_info"),Ib=new Bt("m.beacon","org.matrix.msc3672.beacon"),xH=new ln.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed"),OH=new ln.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed"),PH=new ln.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start"),Fd=new ln.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response"),sv=new ln.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end"),V=function(r){return r.RoomCanonicalAlias="m.room.canonical_alias",r.RoomCreate="m.room.create",r.RoomJoinRules="m.room.join_rules",r.RoomMember="m.room.member",r.RoomThirdPartyInvite="m.room.third_party_invite",r.RoomPowerLevels="m.room.power_levels",r.RoomName="m.room.name",r.RoomTopic="m.room.topic",r.RoomAvatar="m.room.avatar",r.RoomPinnedEvents="m.room.pinned_events",r.RoomEncryption="m.room.encryption",r.RoomHistoryVisibility="m.room.history_visibility",r.RoomGuestAccess="m.room.guest_access",r.RoomServerAcl="m.room.server_acl",r.RoomTombstone="m.room.tombstone",r.RoomPredecessor="org.matrix.msc3946.room_predecessor",r.PolicyRuleUser="m.policy.rule.user",r.PolicyRuleRoom="m.policy.rule.room",r.PolicyRuleServer="m.policy.rule.server",r.SpaceChild="m.space.child",r.SpaceParent="m.space.parent",r.RoomRedaction="m.room.redaction",r.RoomMessage="m.room.message",r.RoomMessageEncrypted="m.room.encrypted",r.Sticker="m.sticker",r.CallInvite="m.call.invite",r.CallCandidates="m.call.candidates",r.CallAnswer="m.call.answer",r.CallHangup="m.call.hangup",r.CallReject="m.call.reject",r.CallSelectAnswer="m.call.select_answer",r.CallNegotiate="m.call.negotiate",r.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",r.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",r.CallReplaces="m.call.replaces",r.CallAssertedIdentity="m.call.asserted_identity",r.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",r.CallEncryptionKeysPrefix="io.element.call.encryption_keys",r.KeyVerificationRequest="m.key.verification.request",r.KeyVerificationStart="m.key.verification.start",r.KeyVerificationCancel="m.key.verification.cancel",r.KeyVerificationMac="m.key.verification.mac",r.KeyVerificationDone="m.key.verification.done",r.KeyVerificationKey="m.key.verification.key",r.KeyVerificationAccept="m.key.verification.accept",r.KeyVerificationReady="m.key.verification.ready",r.RoomMessageFeedback="m.room.message.feedback",r.Reaction="m.reaction",r.PollStart="org.matrix.msc3381.poll.start",r.Typing="m.typing",r.Receipt="m.receipt",r.Presence="m.presence",r.FullyRead="m.fully_read",r.Tag="m.tag",r.SpaceOrder="org.matrix.msc3230.space_order",r.PushRules="m.push_rules",r.Direct="m.direct",r.IgnoredUserList="m.ignored_user_list",r.RoomKey="m.room_key",r.RoomKeyRequest="m.room_key_request",r.ForwardedRoomKey="m.forwarded_room_key",r.Dummy="m.dummy",r.GroupCallPrefix="org.matrix.msc3401.call",r.GroupCallMemberPrefix="org.matrix.msc3401.call.member",r.CallNotify="org.matrix.msc4075.call.notify",r}({}),Nt=function(r){return r.Annotation="m.annotation",r.Replace="m.replace",r.Reference="m.reference",r.Thread="m.thread",r}({}),xi=function(r){return r.Text="m.text",r.Emote="m.emote",r.Notice="m.notice",r.Image="m.image",r.File="m.file",r.Audio="m.audio",r.Location="m.location",r.Video="m.video",r.KeyVerificationRequest="m.key.verification.request",r}({}),av="type",Ql=function(r){return r.Space="m.space",r.UnstableCall="org.matrix.msc3417.call",r.ElementVideo="io.element.video",r}({}),tn="org.matrix.msgid",xb=new Bt("m.room.purpose","org.matrix.msc3088.purpose"),Ob=new Bt("m.enabled","org.matrix.msc3088.enabled"),Pb=new Bt("m.data_tree","org.matrix.msc3089.data_tree"),DD=new Bt("m.leaf","org.matrix.msc3089.leaf"),So=new Bt("m.branch","org.matrix.msc3089.branch"),ND=new Bt("m.room.marker","org.matrix.msc2716.marker"),Mb=new Bt("with_rel_types","org.matrix.msc3912.with_relations"),LD=new Bt("io.element.functional_members","io.element.functional_members"),Ta=new Bt("m.visibility","org.matrix.msc3531.visibility"),Ab=new Bt("enabled","org.matrix.msc3881.enabled"),MH=new Bt("device_id","org.matrix.msc3881.device_id"),UD=new Bt("m.local_notification_settings","org.matrix.msc3890.local_notification_settings"),lv=new Bt("thread_id","org.matrix.msc4023.thread_id"),jD=new hm("membership","io.element.msc4115.membership"),Be=function(r){return r.Ban="ban",r.Invite="invite",r.Join="join",r.Knock="knock",r.Leave="leave",r}({}),Ar=function(r){return r.Membership="RoomMember.membership",r.Name="RoomMember.name",r.PowerLevel="RoomMember.powerLevel",r.Typing="RoomMember.typing",r}({});class cv extends Tt{constructor(e,t){super(),this.roomId=e,this.userId=t,v(this,"_isOutOfBand",!1),v(this,"modified",-1),v(this,"requestedProfileInfo",!1),v(this,"typing",!1),v(this,"name",void 0),v(this,"rawDisplayName",void 0),v(this,"powerLevel",0),v(this,"powerLevelNorm",0),v(this,"user",void 0),v(this,"membership",void 0),v(this,"disambiguate",!1),v(this,"events",{}),this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){var n,i,o=(n=e.getDirectionalContent().displayname)!==null&&n!==void 0?n:"";if(e.getType()===V.RoomMember){this._isOutOfBand=!1,this.events.member=e;var s=this.membership;this.membership=e.getDirectionalContent().membership,this.membership===void 0&&b.trace("membership event with membership undefined (forwardLooking: ".concat(e.forwardLooking,")!"),e.getContent(),"prevcontent is ",e.getPrevContent()),this.disambiguate=NH(this.userId,o,t);var a=this.name;this.name=LH(this.userId,o,this.disambiguate),this.rawDisplayName=wb((i=e.getDirectionalContent().displayname)!==null&&i!==void 0?i:""),(!this.rawDisplayName||!ka(this.rawDisplayName))&&(this.rawDisplayName=this.userId),s!==this.membership&&(this.updateModifiedTime(),this.emit(Ar.Membership,e,this,s)),a!==this.name&&(this.updateModifiedTime(),this.emit(Ar.Name,e,this,a))}}setPowerLevelEvent(e){if(!(e.getType()!==V.RoomPowerLevels||e.getStateKey()!=="")){var t=e.getDirectionalContent(),n=t.users_default||0,i=t.users||{};Object.values(i).forEach(a=>{n=Math.max(n,a)});var o=this.powerLevel,s=this.powerLevelNorm;i[this.userId]!==void 0&&Number.isInteger(i[this.userId])?this.powerLevel=i[this.userId]:t.users_default!==void 0?this.powerLevel=t.users_default:this.powerLevel=0,this.powerLevelNorm=0,n>0&&(this.powerLevelNorm=this.powerLevel*100/n),(o!==this.powerLevel||s!==this.powerLevelNorm)&&(this.updateModifiedTime(),this.emit(Ar.PowerLevel,e,this))}}setTypingEvent(e){if(e.getType()==="m.typing"){var t=this.typing;this.typing=!1;var n=e.getContent().user_ids;Array.isArray(n)&&(n.indexOf(this.userId)!==-1&&(this.typing=!0),t!==this.typing&&(this.updateModifiedTime(),this.emit(Ar.Typing,e,this)))}}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}isKicked(){return this.membership===Be.Leave&&this.events.member!==void 0&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){var e=this.events.member,t=e.getContent(),n=e.getSender();if(t.membership===Be.Join&&(t=e.getPrevContent(),n=e.getUnsigned().prev_sender),t.membership===Be.Invite&&t.is_direct)return n}}getAvatarUrl(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,s=arguments.length>5?arguments[5]:void 0,a=this.getMxcAvatarUrl();if(!a&&!o)return null;var l=bm(e,a,t,n,i,s);return l||null}getMxcAvatarUrl(){if(this.events.member)return this.events.member.getDirectionalContent().avatar_url;if(this.user)return this.user.avatarUrl}}var AH=/@.+:.+/,DH=/[\u200E\u200F\u202A-\u202F]/;function NH(r,e,t){if(!e||e===r||!t)return!1;var n=ka(e);if(!n)return!1;if(AH.test(n)||DH.test(e))return!0;var i=t.getUserIdsWithDisplayName(e);return!!i.some(o=>o!==r)}function LH(r,e,t){return!e||e===r?r:t?wb(e)+" ("+r+")":ka(e)?wb(e):r}const UH="modulepreload",jH=function(r){return"/"+r},CC={},FD=function(e,t,n){let i=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"));i=Promise.allSettled(t.map(l=>{if(l=jH(l),l in CC)return;CC[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":UH,c||(d.as="script"),d.crossOrigin="",d.href=l,a&&d.setAttribute("nonce",a),document.head.appendChild(d),c)return new Promise((f,p)=>{d.addEventListener("load",f),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return i.then(s=>{for(const a of s||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};function FH(r,e){if(r==null)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)!==-1)continue;t[n]=r[n]}return t}function BH(r,e){if(r==null)return{};var t,n,i=FH(r,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(r);for(n=0;n<o.length;n++)t=o[n],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(r,t)&&(i[t]=r[t])}return i}var ar=function(r){return r.DisplayName="User.displayName",r.AvatarUrl="User.avatarUrl",r.Presence="User.presence",r.CurrentlyActive="User.currentlyActive",r.LastPresenceTs="User.lastPresenceTs",r}({});class ko extends Tt{constructor(e){super(),this.userId=e,v(this,"modified",-1),v(this,"displayName",void 0),v(this,"rawDisplayName",void 0),v(this,"avatarUrl",void 0),v(this,"presenceStatusMsg",void 0),v(this,"presence","offline"),v(this,"lastActiveAgo",0),v(this,"lastPresenceTs",0),v(this,"currentlyActive",!1),v(this,"events",{}),this.displayName=e,this.rawDisplayName=e,this.updateModifiedTime()}static createUser(e,t){var n=new ko(e);return t.reEmitter.reEmit(n,[ar.AvatarUrl,ar.DisplayName,ar.Presence,ar.CurrentlyActive,ar.LastPresenceTs]),n}setPresenceEvent(e){if(e.getType()==="m.presence"){var t=this.events.presence===null;this.events.presence=e;var n=[];(e.getContent().presence!==this.presence||t)&&n.push(ar.Presence),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&n.push(ar.AvatarUrl),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&n.push(ar.DisplayName),e.getContent().currently_active!==void 0&&e.getContent().currently_active!==this.currentlyActive&&n.push(ar.CurrentlyActive),this.presence=e.getContent().presence,n.push(ar.LastPresenceTs),e.getContent().status_msg&&(this.presenceStatusMsg=e.getContent().status_msg),e.getContent().displayname&&(this.displayName=e.getContent().displayname),e.getContent().avatar_url&&(this.avatarUrl=e.getContent().avatar_url),this.lastActiveAgo=e.getContent().last_active_ago,this.lastPresenceTs=Date.now(),this.currentlyActive=e.getContent().currently_active,this.updateModifiedTime();for(var i of n)this.emit(i,e,this)}}setDisplayName(e){var t=this.displayName;this.displayName=e,e!==t&&this.updateModifiedTime()}setRawDisplayName(e){this.rawDisplayName=e}setAvatarUrl(e){var t=this.avatarUrl;this.avatarUrl=e,e!==t&&this.updateModifiedTime()}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getLastActiveTs(){return this.lastPresenceTs-this.lastActiveAgo}}var Ge=function(r){return r.Backward="b",r.Forward="f",r}({});class we{static setEventMetadata(e,t,n){var i,o;(i=e.sender)!==null&&i!==void 0&&(i=i.events)!==null&&i!==void 0&&i.member||(e.sender=t.getSentinelMember(e.getSender())),!((o=e.target)!==null&&o!==void 0&&(o=o.events)!==null&&o!==void 0&&o.member)&&e.getType()===V.RoomMember&&(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)}constructor(e){var t,n;this.eventTimelineSet=e,v(this,"roomId",void 0),v(this,"name",void 0),v(this,"events",[]),v(this,"baseIndex",0),v(this,"startState",void 0),v(this,"endState",void 0),v(this,"startToken",null),v(this,"endToken",null),v(this,"prevTimeline",null),v(this,"nextTimeline",null),v(this,"paginationRequests",{[Ge.Backward]:null,[Ge.Forward]:null}),this.roomId=(t=(n=e.room)===null||n===void 0?void 0:n.roomId)!==null&&t!==void 0?t:null,this.roomId&&(this.startState=new Gd(this.roomId,void 0,!0),this.endState=new Gd(this.roomId)),this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+new Date().toISOString()}initialiseState(e){var t,n,{timelineWasEmpty:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.events.length>0)throw new Error("Cannot initialise state after events are added");(t=this.startState)===null||t===void 0||t.setStateEvents(e,{timelineWasEmpty:i}),(n=this.endState)===null||n===void 0||n.setStateEvents(e,{timelineWasEmpty:i})}forkLive(e){var t=this.getState(e),n=new we(this.eventTimelineSet);return n.startState=t==null?void 0:t.clone(),n.endState=t,this.endState=t==null?void 0:t.clone(),n}fork(e){var t=this.getState(e),n=new we(this.eventTimelineSet);return n.startState=t==null?void 0:t.clone(),n.endState=t==null?void 0:t.clone(),n}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(e){if(e==we.BACKWARDS)return this.startState;if(e==we.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.roomId?this.getState(e).paginationToken:e===Ge.Backward?this.startToken:this.endToken}setPaginationToken(e,t){this.roomId?this.getState(t).paginationToken=e:t===Ge.Backward?this.startToken=e:this.endToken=e}getNeighbouringTimeline(e){if(e==we.BACKWARDS)return this.prevTimeline;if(e==we.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+e+"'")}setNeighbouringTimeline(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+t+")");if(t==we.BACKWARDS)this.prevTimeline=e;else if(t==we.FORWARDS)this.nextTimeline=e;else throw new Error("Invalid direction '"+t+"'");this.setPaginationToken(null,t)}addEvent(e){var{toStartOfTimeline:t,roomState:n,timelineWasEmpty:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{toStartOfTimeline:!1};n||(n=t?this.startState:this.endState);var o=this.getTimelineSet();if(o.room&&(we.setEventMetadata(e,n,t),e.isState()&&o.room.getUnfilteredTimelineSet()===o)){var s;(s=n)===null||s===void 0||s.setStateEvents([e],{timelineWasEmpty:i}),(!e.sender||e.getType()===V.RoomMember&&!t)&&we.setEventMetadata(e,n,t)}var a;t?a=0:a=this.events.length,this.events.splice(a,0,e),t&&this.baseIndex++}insertEvent(e,t,n){var i=this.getTimelineSet();i.room&&(we.setEventMetadata(e,n,!1),e.isState()&&i.room.getUnfilteredTimelineSet()===i&&(n.setStateEvents([e],{}),(!e.sender||e.getType()===V.RoomMember)&&we.setEventMetadata(e,n,!1))),this.events.splice(t,0,e)}removeEvent(e){for(var t=this.events.length-1;t>=0;t--){var n=this.events[t];if(n.getId()==e)return this.events.splice(t,1),t<this.baseIndex&&this.baseIndex--,n}return null}toString(){return this.name}}v(we,"BACKWARDS",Ge.Backward);v(we,"FORWARDS",Ge.Forward);var rp=function(r){return r.Add="Relations.add",r.Remove="Relations.remove",r.Redaction="Relations.redaction",r}({}),KH=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return[t,...n].includes(e)};class Ow extends Tt{constructor(e,t,n,i){var o;super(),o=this,this.relationType=e,this.eventType=t,this.altEventTypes=i,v(this,"relationEventIds",new Set),v(this,"relations",new Set),v(this,"annotationsByKey",{}),v(this,"annotationsBySender",{}),v(this,"sortedAnnotationsByKey",[]),v(this,"targetEvent",null),v(this,"creationEmitted",!1),v(this,"client",void 0),v(this,"onEventStatus",(s,a)=>{if(!s.isSending()){s.removeListener(ot.Status,this.onEventStatus);return}a===je.CANCELLED&&(s.removeListener(ot.Status,this.onEventStatus),this.removeEvent(s))}),v(this,"onBeforeRedaction",function(){var s=w(function*(a){if(o.relations.has(a)){if(o.relations.delete(a),o.relationType===Nt.Annotation)o.removeAnnotationFromAggregation(a);else if(o.relationType===Nt.Replace&&o.targetEvent&&!o.targetEvent.isState()){var l=yield o.getLastReplacement();o.targetEvent.makeReplaced(l)}a.removeListener(ot.BeforeRedaction,o.onBeforeRedaction),o.emit(rp.Redaction,a)}});return function(a){return s.apply(this,arguments)}}()),this.client=n instanceof Tm?n.client:n}addEvent(e){var t=this;return w(function*(){if(!t.relationEventIds.has(e.getId())){var n=e.getRelation();if(!n){b.error("Event must have relation info");return}var i=n.rel_type,o=e.getType();if(t.relationType!==i||!KH(o,t.eventType,t.altEventTypes)){b.error("Event relation info doesn't match this container");return}if(e.isSending()&&e.on(ot.Status,t.onEventStatus),t.relations.add(e),t.relationEventIds.add(e.getId()),t.relationType===Nt.Annotation)t.addAnnotationToAggregation(e);else if(t.relationType===Nt.Replace&&t.targetEvent&&!t.targetEvent.isState()){var s=yield t.getLastReplacement();t.targetEvent.makeReplaced(s)}e.on(ot.BeforeRedaction,t.onBeforeRedaction),t.emit(rp.Add,e),t.maybeEmitCreated()}})()}removeEvent(e){var t=this;return w(function*(){if(t.relations.has(e)){if(t.relations.delete(e),t.relationType===Nt.Annotation)t.removeAnnotationFromAggregation(e);else if(t.relationType===Nt.Replace&&t.targetEvent&&!t.targetEvent.isState()){var n=yield t.getLastReplacement();t.targetEvent.makeReplaced(n)}t.emit(rp.Remove,e)}})()}getRelations(){return[...this.relations]}addAnnotationToAggregation(e){var t,{key:n}=(t=e.getRelation())!==null&&t!==void 0?t:{};if(n){var i=this.annotationsByKey[n];i||(i=this.annotationsByKey[n]=new Set,this.sortedAnnotationsByKey.push([n,i])),i.add(e),this.sortedAnnotationsByKey.sort((a,l)=>{var c=a[1],u=l[1];return u.size-c.size});var o=e.getSender(),s=this.annotationsBySender[o];s||(s=this.annotationsBySender[o]=new Set),s.add(e)}}removeAnnotationFromAggregation(e){var t,{key:n}=(t=e.getRelation())!==null&&t!==void 0?t:{};if(n){var i=this.annotationsByKey[n];i&&(i.delete(e),this.sortedAnnotationsByKey.sort((a,l)=>{var c=a[1],u=l[1];return u.size-c.size}));var o=e.getSender(),s=this.annotationsBySender[o];s&&s.delete(e)}}getSortedAnnotationsByKey(){return this.relationType!==Nt.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==Nt.Annotation?null:this.annotationsBySender}getLastReplacement(){var e=this;return w(function*(){if(e.relationType!==Nt.Replace||!e.targetEvent)return null;var t=e.targetEvent.getServerAggregatedRelation(Nt.Replace),n=t==null?void 0:t.origin_server_ts,i=e.getRelations().reduce((o,s)=>s.getSender()!==e.targetEvent.getSender()||n&&n>s.getTs()||o&&o.getTs()>s.getTs()?o:s,null);return i!=null&&i.shouldAttemptDecryption()&&e.client.isCryptoEnabled()?yield i.attemptDecryption(e.client.crypto):i!=null&&i.isBeingDecrypted()&&(yield i.getDecryptionPromise()),i})()}setTargetEvent(e){var t=this;return w(function*(){if(!t.targetEvent){if(t.targetEvent=e,t.relationType===Nt.Replace&&!t.targetEvent.isState()){var n=yield t.getLastReplacement();n&&t.targetEvent.makeReplaced(n)}t.maybeEmitCreated()}})()}maybeEmitCreated(){this.creationEmitted||!this.targetEvent||!this.relations.size||(this.creationEmitted=!0,this.targetEvent.emit(ot.RelationsCreated,this.relationType,this.eventType))}}class BD{constructor(e,t){this.client=e,this.room=t,v(this,"relations",new Map)}getChildEventsForEvent(e,t,n){var i;return(i=this.relations.get(e))===null||i===void 0||(i=i.get(t))===null||i===void 0?void 0:i.get(n)}getAllChildEventsForEvent(e){var t,n=(t=this.relations.get(e))!==null&&t!==void 0?t:new Map,i=[];for(var o of n.values())for(var s of o.values())i.push(...s.getRelations());return i}aggregateParentEvent(e){var t=this.relations.get(e.getId());if(t)for(var n of t.values())for(var i of n.values())i.setTargetEvent(e)}aggregateChildEvent(e,t){if(!(e.isRedacted()||e.status===je.CANCELLED)){var n=e.getRelation();if(n){var i=()=>{if(e.isDecryptionFailure()){e.once(ot.Decrypted,i);return}this.aggregateChildEvent(e,t)};if(e.isBeingDecrypted()||e.shouldAttemptDecryption()){e.once(ot.Decrypted,i);return}var{event_id:o,rel_type:s}=n,a=e.getType(),l=this.relations.get(o);l||(l=new Map,this.relations.set(o,l));var c=l.get(s);c||(c=new Map,l.set(s,c));var u=c.get(a);if(!u){var d,f,p;u=new Ow(s,a,this.client),c.set(a,u);var h=(d=this.room)!==null&&d!==void 0?d:t==null?void 0:t.room,m=(f=(p=t==null?void 0:t.findEventById(o))!==null&&p!==void 0?p:h==null?void 0:h.findEventById(o))!==null&&f!==void 0?f:h==null?void 0:h.getPendingEvent(o);m&&u.setTargetEvent(m)}u.addEvent(e)}}}}var _l;_l=b.log.bind(b);var td=function(r){return r.Ignore="ignore",r.Replace="replace",r}({});class Bl extends Tt{constructor(e){var t,n,i,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0,a=arguments.length>3?arguments[3]:void 0,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null;super(),this.room=e,this.thread=a,this.threadListType=l,v(this,"relations",void 0),v(this,"timelineSupport",void 0),v(this,"displayPendingEvents",void 0),v(this,"liveTimeline",void 0),v(this,"timelines",void 0),v(this,"_eventIdToTimeline",new Map),v(this,"filter",void 0),this.timelineSupport=!!o.timelineSupport,this.liveTimeline=new we(this),this.displayPendingEvents=o.pendingEvents!==!1,this.timelines=[this.liveTimeline],this._eventIdToTimeline=new Map,this.filter=o.filter,this.relations=(t=(n=this.room)===null||n===void 0?void 0:n.relations)!==null&&t!==void 0?t:new BD((i=e==null?void 0:e.client)!==null&&i!==void 0?i:s)}getTimelines(){return this.timelines}getFilter(){return this.filter}setFilter(e){this.filter=e}getPendingEvents(){return!this.room||!this.displayPendingEvents?[]:this.room.getPendingEvents()}getLiveTimeline(){return this.liveTimeline}setLiveTimeline(e){this.liveTimeline=e}eventIdToTimeline(e){return this._eventIdToTimeline.get(e)}replaceEventId(e,t){var n=this._eventIdToTimeline.get(e);n&&(this._eventIdToTimeline.delete(e),this._eventIdToTimeline.set(t,n))}resetLiveTimeline(e,t){var n=!this.timelineSupport||!t,i=this.liveTimeline,o=n?i.forkLive(we.FORWARDS):i.fork(we.FORWARDS);n?(this.timelines=[o],this._eventIdToTimeline=new Map):this.timelines.push(o),t&&i.setPaginationToken(t,we.FORWARDS),o.setPaginationToken(e??null,we.BACKWARDS),this.liveTimeline=o,this.emit(pe.TimelineReset,this.room,this,n)}getTimelineForEvent(e){if(e==null)return null;var t=this._eventIdToTimeline.get(e);return t===void 0?null:t}findEventById(e){var t=this.getTimelineForEvent(e);if(t)return t.getEvents().find(function(n){return n.getId()==e})}addTimeline(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");var e=new we(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,n,i){if(!n)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&n==this.liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(!(this.filter&&(e=this.filter.filterRoomTimeline(e),!e.length))){var o=t?we.BACKWARDS:we.FORWARDS,s=t?we.FORWARDS:we.BACKWARDS,a=!1,l=!1;for(var c of e){var u=c.getId(),d=this._eventIdToTimeline.get(u);if(!d){this.addEventToTimeline(c,n,{toStartOfTimeline:t}),l=!0,a=!0;continue}if(l=!1,d==n){_l("Event "+u+" already in timeline "+n);continue}var f=n.getNeighbouringTimeline(o);if(f){d==f?_l("Event "+u+" in neighbouring timeline - switching to "+d):_l("Event "+u+" already in a different timeline "+d),n=d;continue}b.info("Already have timeline for "+u+" - joining timeline "+n+" to "+d);var p=d===this.liveTimeline,h=n===this.liveTimeline,m=o===we.BACKWARDS&&p,E=o===we.FORWARDS&&h;if(m||E){m&&b.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+d+")"),E&&b.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+n+")");continue}n.setNeighbouringTimeline(d,o),d.setNeighbouringTimeline(n,s),n=d,a=!0}if(l||!a){if(o===we.FORWARDS&&n===this.liveTimeline){b.warn({lastEventWasNew:l,didUpdate:a}),b.warn("Refusing to set forwards pagination token of live timeline "+"".concat(n," to ").concat(i));return}n.setPaginationToken(i??null,o)}}}addLiveEvent(e){var{duplicateStrategy:t,fromCache:n,roomState:i,timelineWasEmpty:o}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.filter){var s=this.filter.filterRoomTimeline([e]);if(!s.length)return}var a=this._eventIdToTimeline.get(e.getId());if(a){if(t===td.Replace){_l("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());for(var l=a.getEvents(),c=0;c<l.length;c++)if(l[c].getId()===e.getId()){i||(i=a.getState(we.FORWARDS)),we.setEventMetadata(e,i,!1),l[c]=e;break}}else _l("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());return}this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1,fromCache:n,roomState:i,timelineWasEmpty:o})}addEventToTimeline(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,o=arguments.length>4?arguments[4]:void 0,s=!!n,a;if(typeof n=="object"?{toStartOfTimeline:s,fromCache:i=!1,roomState:o,timelineWasEmpty:a}=n:n!==void 0&&b.warn("Overload deprecated: `EventTimelineSet.addEventToTimeline(event, timeline, toStartOfTimeline, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addEventToTimeline(event, timeline, IAddEventToTimelineOptions)`"),t.getTimelineSet()!==this){var l;throw new Error("EventTimelineSet.addEventToTimeline: Timeline=".concat(t.toString(),` does not belong " +
285
- "in timelineSet(threadId=`).concat((l=this.thread)===null||l===void 0?void 0:l.id,")"))}var c=e.getId();if(this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this),this.room&&!this.canContain(e)){var u,d="event=".concat(c);e.threadRootId&&(d+="(belongs to thread=".concat(e.threadRootId,")")),b.warn("EventTimelineSet.addEventToTimeline: Ignoring ".concat(d," that does not belong ")+"in timeline=".concat(t.toString()," timelineSet(threadId=").concat((u=this.thread)===null||u===void 0?void 0:u.id,")"));return}t.addEvent(e,{toStartOfTimeline:s,roomState:o,timelineWasEmpty:a}),this._eventIdToTimeline.set(c,t);var f={timeline:t,liveEvent:!s&&t==this.liveTimeline&&!i};this.emit(pe.Timeline,e,this.room,!!s,!1,f)}insertEventIntoTimeline(e,t,n){if(t.getTimelineSet()!==this){var i;throw new Error("EventTimelineSet.insertEventIntoTimeline: Timeline=".concat(t.toString(),` does not belong " +
286
- "in timelineSet(threadId=`).concat((i=this.thread)===null||i===void 0?void 0:i.id,")"))}var o=e.getId();if(this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this),this.room&&!this.canContain(e)){var s,a="event=".concat(o);e.threadRootId&&(a+="(belongs to thread=".concat(e.threadRootId,")")),b.warn("EventTimelineSet.insertEventIntoTimeline: Ignoring ".concat(a," that does not belong ")+"in timeline=".concat(t.toString()," timelineSet(threadId=").concat((s=this.thread)===null||s===void 0?void 0:s.id,")"));return}var l=e.relationEventId;if(!l){this.addEventToTimeline(e,t,{toStartOfTimeline:!1,fromCache:!1,timelineWasEmpty:!1,roomState:n});return}for(var c=this.findEventById(l),u=t.getEvents(),d=c!==void 0?u.indexOf(c):0,f=d;f<u.length;f++){var p=u[f];if(p.getTs()>e.getTs())break}t.insertEvent(e,f,n),this._eventIdToTimeline.set(o,t);var h={timeline:t,liveEvent:!1};this.emit(pe.Timeline,e,this.room,!1,!1,h)}handleRemoteEcho(e,t,n){var i=this._eventIdToTimeline.get(t);i?(this._eventIdToTimeline.delete(t),this._eventIdToTimeline.set(n,i)):(!this.filter||this.filter.filterRoomTimeline([e]).length)&&this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1})}removeEvent(e){var t=this._eventIdToTimeline.get(e);if(!t)return null;var n=t.removeEvent(e);if(n){this._eventIdToTimeline.delete(e);var i={timeline:t};this.emit(pe.Timeline,n,this.room,void 0,!0,i)}return n}compareEventOrdering(e,t){if(e==t)return 0;var n=this._eventIdToTimeline.get(e),i=this._eventIdToTimeline.get(t);if(n===void 0||i===void 0)return null;if(n===i){for(var o=void 0,s=void 0,a=n.getEvents(),l=0;l<a.length&&(o===void 0||s===void 0);l++){var c=a[l].getId();c==e&&(o=l),c==t&&(s=l)}var u=o-s;return u<0?-1:u>0?1:0}for(var d=n;d;){if(d===i)return-1;d=d.getNeighbouringTimeline(we.FORWARDS)}for(d=n;d;){if(d===i)return 1;d=d.getNeighbouringTimeline(we.BACKWARDS)}return null}canContain(e){if(!this.room)throw new Error("Cannot call `EventTimelineSet::canContain without a `room` set. Set the room when creating the EventTimelineSet to call this method.");var{threadId:t,shouldLiveInRoom:n,shouldLiveInThread:i}=this.room.eventShouldLiveIn(e);if(this.thread)return this.thread.id===t;if(!n&&!i){var o;b.warn("EventTimelineSet:canContain event encountered which cannot be added to any timeline roomId=".concat((o=this.room)===null||o===void 0?void 0:o.roomId," eventId=").concat(e.getId()," threadId=").concat(e.threadRootId))}return n}}var je=function(r){return r.NOT_SENT="not_sent",r.ENCRYPTING="encrypting",r.SENDING="sending",r.QUEUED="queued",r.SENT="sent",r.CANCELLED="cancelled",r}({});class KD{constructor(e,t){this.roomId=e}}class VD{constructor(e){this.target=e,v(this,"reEmitters",new WeakMap)}reEmit(e,t){var n=this,i=this.reEmitters.get(e);i||(i=new Map,this.reEmitters.set(e,i));var o=function(l){if(i.has(l))return 1;var c=function(){if(!(l==="error"&&n.target.listenerCount("error")===0)){for(var d=arguments.length,f=new Array(d),p=0;p<d;p++)f[p]=arguments[p];n.target.emit(l,...f,e)}};e.on(l,c),i.set(l,c)};for(var s of t)o(s)}stopReEmitting(e,t){var n=this.reEmitters.get(e);if(n){for(var i of t)e.off(i,n.get(i)),n.delete(i);n.size===0&&this.reEmitters.delete(e)}}}class Vc extends VD{constructor(e){super(e)}reEmit(e,t){super.reEmit(e,t)}stopReEmitting(e,t){super.stopReEmitting(e,t)}}var Bd=new pm("unread_thread_notifications","org.matrix.msc3773.unread_thread_notifications");function VH(r,e){if(e.endsWith("*")){var t=e.slice(0,-1);return r.slice(0,t.length)===t}else return r===e}class kC{constructor(e,t){this.filterJson=e,this.userId=t}check(e){var t,n,i=((t=e.getUnsigned())===null||t===void 0?void 0:t["m.relations"])||{},o=Object.keys(i),s=[];return this.userId&&i!==null&&i!==void 0&&(n=i[vt.name])!==null&&n!==void 0&&n.current_user_participated&&s.push(this.userId),this.checkFields(e.getRoomId(),e.getSender(),e.getType(),e.getContent()?e.getContent().url!==void 0:!1,o,s)}toJSON(){return{types:this.filterJson.types||null,not_types:this.filterJson.not_types||[],rooms:this.filterJson.rooms||null,not_rooms:this.filterJson.not_rooms||[],senders:this.filterJson.senders||null,not_senders:this.filterJson.not_senders||[],contains_url:this.filterJson.contains_url||null,[ic.name]:this.filterJson[ic.name]||[],[oc.name]:this.filterJson[oc.name]||[]}}checkFields(e,t,n,i,o,s){var a={rooms:function(y){return e===y},senders:function(y){return t===y},types:function(y){return VH(n,y)}};for(var l in a){var c=a[l],u="not_"+l,d=this.filterJson[u];if(d!=null&&d.some(c))return!1;var f=this.filterJson[l];if(f&&!f.some(c))return!1}var p=this.filterJson.contains_url;if(p!==void 0&&p!==i)return!1;var h=this.filterJson[oc.name];if(h!==void 0&&!this.arrayMatchesFilter(h,o))return!1;var m=this.filterJson[ic.name];return!(m!==void 0&&!this.arrayMatchesFilter(m,s))}arrayMatchesFilter(e,t){return t.length>0&&e.every(n=>t.includes(n))}filter(e){return e.filter(this.check,this)}limit(){return this.filterJson.limit!==void 0?this.filterJson.limit:10}}function IC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function cl(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?IC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):IC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function ry(r,e,t){for(var n=e.split("."),i=r,o=0;o<n.length-1;o++)i[n[o]]||(i[n[o]]={}),i=i[n[o]];i[n[n.length-1]]=t}class gn{static fromJson(e,t,n){var i=new gn(e,t);return i.setDefinition(n),i}constructor(e,t){this.userId=e,this.filterId=t,v(this,"definition",{}),v(this,"roomFilter",void 0),v(this,"roomTimelineFilter",void 0)}getFilterId(){return this.filterId}getDefinition(){return this.definition}setDefinition(e){this.definition=e;var t=e.room,n={};t&&(t.rooms&&(n.rooms=t.rooms),t.rooms&&(n.not_rooms=t.not_rooms)),this.roomFilter=new kC(n,this.userId),this.roomTimelineFilter=new kC((t==null?void 0:t.timeline)||{},this.userId)}getRoomTimelineFilterComponent(){return this.roomTimelineFilter}filterRoomTimeline(e){return this.roomFilter&&(e=this.roomFilter.filter(e)),this.roomTimelineFilter&&(e=this.roomTimelineFilter.filter(e)),e}setTimelineLimit(e){ry(this.definition,"room.timeline.limit",e)}setUnreadThreadNotifications(e){var t,n;this.definition=cl(cl({},this.definition),{},{room:cl(cl({},(t=this.definition)===null||t===void 0?void 0:t.room),{},{timeline:cl(cl({},(n=this.definition)===null||n===void 0||(n=n.room)===null||n===void 0?void 0:n.timeline),{},{[Bd.name]:e})})})}setLazyLoadMembers(e){ry(this.definition,"room.state.lazy_load_members",e)}setIncludeLeaveRooms(e){ry(this.definition,"room.include_leave",e)}}v(gn,"LAZY_LOADING_MESSAGES_FILTER",{lazy_load_members:!0});var Pw=new Bt("m.topic","org.matrix.msc3765.topic");function xC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function $H(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?xC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):xC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function $D(r,e){return{msgtype:xi.Text,format:"org.matrix.custom.html",body:r,formatted_body:e}}function WD(r,e){return{msgtype:xi.Notice,format:"org.matrix.custom.html",body:r,formatted_body:e}}function qD(r,e){return{msgtype:xi.Emote,format:"org.matrix.custom.html",body:r,formatted_body:e}}function GD(r){return{msgtype:xi.Text,body:r}}function HD(r){return{msgtype:xi.Notice,body:r}}function zD(r){return{msgtype:xi.Emote,body:r}}var YD=(r,e,t,n)=>{var i="at ".concat(new Date(t).toISOString()),o=e===yc.Self?"User":void 0,s=n?'"'.concat(n,'"'):void 0;return[o,"Location",s,r,i].filter(Boolean).join(" ")},JD=(r,e,t,n,i)=>{var o=r??YD(e,i||yc.Self,t,n),s=t?{[Gs.name]:t}:{};return $H({msgtype:xi.Location,body:o,geo_uri:e,[wf.name]:{description:n,uri:e},[Ef.name]:{type:i||yc.Self},[Cw.name]:o},s)},WH=r=>{var e,t,n=wf.findIn(r),i=Ef.findIn(r),o=Gs.findIn(r),s=Cw.findIn(r),a=(e=n==null?void 0:n.uri)!==null&&e!==void 0?e:r==null?void 0:r.geo_uri,l=n==null?void 0:n.description,c=(t=i==null?void 0:i.type)!==null&&t!==void 0?t:yc.Self,u=s??r.body;return JD(u,a,o??void 0,l,c)},XD=(r,e)=>{var t=[{body:r,mimetype:"text/plain"}];return Rw(e)&&t.push({body:e,mimetype:"text/html"}),{topic:r,[Pw.name]:t}},qH=r=>{var e,t,n,i=Pw.findIn(r);if(!Array.isArray(i))return{text:r.topic};var o=(e=i==null||(t=i.find(a=>!Rw(a.mimetype)||a.mimetype==="text/plain"))===null||t===void 0?void 0:t.body)!==null&&e!==void 0?e:r.topic,s=i==null||(n=i.find(a=>a.mimetype==="text/html"))===null||n===void 0?void 0:n.body;return{text:o,html:s}},GH=(r,e,t,n,i)=>({description:t,timeout:r,live:e,[Gs.name]:i||Date.now(),[Ef.name]:{type:n??yc.Self}}),QD=r=>{var e,{description:t,timeout:n,live:i}=r,o=(e=Gs.findIn(r))!==null&&e!==void 0?e:void 0,s=Ef.findIn(r);return{description:t,timeout:n,live:i,assetType:s==null?void 0:s.type,timestamp:o}},HH=(r,e,t,n)=>({[wf.name]:{description:n,uri:r},[Gs.name]:e,"m.relates_to":{rel_type:yD.name,event_id:t}}),Db=r=>{var e,t=wf.findIn(r),n=(e=Gs.findIn(r))!==null&&e!==void 0?e:void 0;return{description:t==null?void 0:t.description,uri:t==null?void 0:t.uri,timestamp:n}};const zH=Object.freeze(Object.defineProperty({__proto__:null,getTextForLocationEvent:YD,makeBeaconContent:HH,makeBeaconInfoContent:GH,makeEmoteMessage:zD,makeHtmlEmote:qD,makeHtmlMessage:$D,makeHtmlNotice:WD,makeLocationContent:JD,makeNotice:HD,makeTextMessage:GD,makeTopicContent:XD,parseBeaconContent:Db,parseBeaconInfoContent:QD,parseLocationEvent:WH,parseTopicContent:qH},Symbol.toStringTag,{value:"Module"}));var kt=function(r){return r.New="Beacon.new",r.Update="Beacon.update",r.LivenessChange="Beacon.LivenessChange",r.Destroy="Beacon.Destroy",r.LocationUpdate="Beacon.LocationUpdate",r}({}),Nb=(r,e,t)=>t>=r&&r+e>=t,uv=r=>"".concat(r.getRoomId(),"_").concat(r.getStateKey());class ZD extends Tt{constructor(e){super(),this.rootEvent=e,v(this,"roomId",void 0),v(this,"_beaconInfo",void 0),v(this,"_isLive",void 0),v(this,"livenessWatchTimeout",void 0),v(this,"_latestLocationEvent",void 0),v(this,"clearLatestLocation",()=>{this._latestLocationEvent=void 0,this.emit(kt.LocationUpdate,this.latestLocationState)}),this.roomId=this.rootEvent.getRoomId(),this.setBeaconInfo(this.rootEvent)}get isLive(){return!!this._isLive}get identifier(){return uv(this.rootEvent)}get beaconInfoId(){return this.rootEvent.getId()}get beaconInfoOwner(){return this.rootEvent.getStateKey()}get beaconInfoEventType(){return this.rootEvent.getType()}get beaconInfo(){return this._beaconInfo}get latestLocationState(){return this._latestLocationEvent&&Db(this._latestLocationEvent.getContent())}get latestLocationEvent(){return this._latestLocationEvent}update(e){if(uv(e)!==this.identifier)throw new Error("Invalid updating event");e.getTs()<this.rootEvent.getTs()||(this.rootEvent=e,this.setBeaconInfo(this.rootEvent),this.emit(kt.Update,e,this),this.clearLatestLocation())}destroy(){this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this._isLive=!1,this.emit(kt.Destroy,this.identifier)}monitorLiveness(){if(this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this.checkLiveness(),!!this.beaconInfo)if(this.isLive){var e=this.beaconInfo.timestamp+this.beaconInfo.timeout-Date.now();e>1&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},e))}else this.beaconInfo.timestamp>Date.now()&&(this.livenessWatchTimeout=setTimeout(()=>{this.monitorLiveness()},this.beaconInfo.timestamp-Date.now()))}addLocations(e){var t;if(this.isLive){var n=e.filter(o=>{var s=o.getContent(),a=Db(s);if(!a.uri||!a.timestamp)return!1;var{timestamp:l}=a;return this._beaconInfo.timestamp&&Nb(this._beaconInfo.timestamp,this._beaconInfo.timeout,l)&&(!this.latestLocationState||l>this.latestLocationState.timestamp)}),i=(t=n.sort(yH))===null||t===void 0?void 0:t[0];i&&(this._latestLocationEvent=i,this.emit(kt.LocationUpdate,this.latestLocationState))}}setBeaconInfo(e){this._beaconInfo=QD(e.getContent()),this.checkLiveness()}checkLiveness(){var e=this.isLive;if(this.beaconInfo){var t=this.beaconInfo.timestamp>Date.now()?this.beaconInfo.timestamp-36e4:this.beaconInfo.timestamp;this._isLive=!!this._beaconInfo.live&&!!t&&Nb(t,this._beaconInfo.timeout,Date.now()),e!==this.isLive&&this.emit(kt.LivenessChange,this.isLive,this)}}}function OC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function YH(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?OC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):OC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function eN(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;return new pr({content:{[e.getId()]:{[t]:{[r]:YH({ts:e.getTs()},!n&&{thread_id:kc(e)})}}},type:V.Receipt,room_id:e.getRoomId()})}var ul=0,dl=1;class tN extends Tt{constructor(){super(...arguments),v(this,"receipts",new Gt(()=>new Map)),v(this,"receiptCacheByEventId",new Map)}getReadReceiptForUserId(e){var t,n,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Xr.Read,[s,a]=(t=(n=this.receipts.get(o))===null||n===void 0?void 0:n.get(e))!==null&&t!==void 0?t:[null,null];return i?s:a??s}compareReceipts(e,t){var n;return(n=this.getUnfilteredTimelineSet().compareEventOrdering(e.eventId,t.eventId))!==null&&n!==void 0?n:e.data.ts-t.data.ts}getEventReadUpTo(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=this.getLatestReceipt(e,t);return n&&this.receiptPointsAtConsistentEvent(n)?n.eventId:null}receiptPointsAtConsistentEvent(e){var t,n=this.findEventById(e.eventId);if(!n)return!1;if(!((t=e.data)!==null&&t!==void 0&&t.thread_id))return!0;if(e.data.thread_id===Tf){var i=qd(n);if(i)return!0}else if(n.threadRootId===e.data.thread_id)return!0;return b.warn("Ignoring receipt because its thread_id (".concat(e.data.thread_id,") disagrees ")+"with the thread root (".concat(n.threadRootId,") of the referenced event ")+"(event ID = ".concat(e.eventId,")")),!1}getLatestReceipt(e,t){var n,i,o=this.getReadReceiptForUserId(e,t,Xr.Read),s=this.getReadReceiptForUserId(e,t,Xr.ReadPrivate),a;return o!=null&&o.eventId&&s!==null&&s!==void 0&&s.eventId&&(a=this.compareReceipts(o,s)),a?(i=a<0?s:o)!==null&&i!==void 0?i:null:(n=s??o)!==null&&n!==void 0?n:null}addReceiptToStructure(e,t,n,i,o){var s,a,l=this.receipts.getOrCreate(t),c=l.get(n);c||(c=[null,null],l.set(n,c));var u=c[ul];if(o){var d;u=(d=c[dl])!==null&&d!==void 0?d:c[ul]}var f={eventId:e,data:i};if(u){var p=this.compareReceipts(u,f);if(p>=0)return}var h=o?c[ul]:f,m=o?f:c[dl],E=null;h&&m&&(E=this.getUnfilteredTimelineSet().compareEventOrdering(h.eventId,m.eventId));var y=E===null||E<0,S=(s=c[dl])!==null&&s!==void 0?s:c[ul];o&&y?c[dl]=f:o||(c[ul]=f,y||(c[dl]=null));var R=(a=c[dl])!==null&&a!==void 0?a:c[ul];if(S!==R){if(S&&this.receiptCacheByEventId.get(S.eventId)){var k=S.eventId;this.receiptCacheByEventId.set(k,this.receiptCacheByEventId.get(k).filter(x=>x.type!==t||x.userId!==n)),this.receiptCacheByEventId.get(k).length<1&&this.receiptCacheByEventId.delete(k)}this.receiptCacheByEventId.get(e)||this.receiptCacheByEventId.set(e,[]),this.receiptCacheByEventId.get(e).push({userId:n,type:t,data:i})}}getReceiptsForEvent(e){return this.receiptCacheByEventId.get(e.getId())||[]}fixupNotifications(e){var t=this.getReadReceiptForUserId(e,!1),n=this.timeline[this.timeline.length-1];n&&(t==null?void 0:t.eventId)===n.getId()&&e===n.getSender()&&(this.setUnread(it.Total,0),this.setUnread(it.Highlight,0))}addLocalEchoReceipt(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;this.addReceipt(eN(e,t,n,i),!0)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter(function(t){return kw(t.type)}).map(function(t){return t.userId})}}var cs=function(r){return r.New="Poll.new",r.End="Poll.end",r.Update="Poll.update",r.Responses="Poll.Responses",r.Destroy="Poll.Destroy",r.UndecryptableRelations="Poll.UndecryptableRelations",r}({}),PC=(r,e)=>{var t=r.filter(n=>{if(!n.isDecryptionFailure())return Fd.matches(n.getType())&&n.getTs()<=e});return{responseEvents:t}};class rN extends Tt{constructor(e,t,n){if(super(),this.rootEvent=e,this.matrixClient=t,this.room=n,v(this,"roomId",void 0),v(this,"pollEvent",void 0),v(this,"_isFetchingResponses",!1),v(this,"relationsNextBatch",void 0),v(this,"responses",null),v(this,"endEvent",void 0),v(this,"undecryptableRelationEventIds",new Set),v(this,"countUndecryptableEvents",i=>{var o=i.filter(a=>a.isDecryptionFailure()).map(a=>a.getId()),s=this.undecryptableRelationsCount;this.undecryptableRelationEventIds=new Set([...this.undecryptableRelationEventIds,...o]),this.undecryptableRelationsCount!==s&&this.emit(cs.UndecryptableRelations,this.undecryptableRelationsCount)}),!this.rootEvent.getRoomId()||!this.rootEvent.getId())throw new Error("Invalid poll start event.");this.roomId=this.rootEvent.getRoomId(),this.pollEvent=this.rootEvent.unstableExtensibleEvent}get pollId(){return this.rootEvent.getId()}get endEventId(){var e;return(e=this.endEvent)===null||e===void 0?void 0:e.getId()}get isEnded(){return!!this.endEvent}get isFetchingResponses(){return this._isFetchingResponses}get undecryptableRelationsCount(){return this.undecryptableRelationEventIds.size}getResponses(){var e=this;return w(function*(){return e.responses||e.isFetchingResponses||(yield e.fetchResponses()),e.responses})()}onNewRelation(e){var t;if(sv.matches(e.getType())&&this.validateEndEvent(e)&&(this.endEvent=e,this.refilterResponsesOnEnd(),this.emit(cs.End)),!!this.responses){var n=((t=this.endEvent)===null||t===void 0?void 0:t.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:i}=PC([e],n);this.countUndecryptableEvents([e]),i.length&&(i.forEach(o=>{this.responses.addEvent(o)}),this.emit(cs.Responses,this.responses))}}fetchResponses(){var e=this;return w(function*(){var t,n;e._isFetchingResponses=!0;var i=yield e.matrixClient.relations(e.roomId,e.rootEvent.getId(),"m.reference",void 0,{from:e.relationsNextBatch||void 0});yield Promise.all(i.events.map(c=>e.matrixClient.decryptEventIfNeeded(c)));var o=e.responses||new Ow("m.reference",Fd.name,e.matrixClient,[Fd.altName]),s=i.events.find(c=>sv.matches(c.getType()));e.validateEndEvent(s)&&(e.endEvent=s,e.refilterResponsesOnEnd(),e.emit(cs.End));var a=((t=e.endEvent)===null||t===void 0?void 0:t.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:l}=PC(i.events,a);l.forEach(c=>{o.addEvent(c)}),e.relationsNextBatch=(n=i.nextBatch)!==null&&n!==void 0?n:void 0,e.responses=o,e.countUndecryptableEvents(i.events),e.relationsNextBatch?e.fetchResponses():e._isFetchingResponses=!1,e.emit(cs.Responses,e.responses)})()}refilterResponsesOnEnd(){var e;if(this.responses){var t=((e=this.endEvent)===null||e===void 0?void 0:e.getTs())||Number.MAX_SAFE_INTEGER;this.responses.getRelations().forEach(n=>{if(n.getTs()>t){var i;(i=this.responses)===null||i===void 0||i.removeEvent(n)}}),this.emit(cs.Responses,this.responses)}}validateEndEvent(e){if(!e||this.endEvent&&this.endEvent.getTs()<e.getTs())return!1;var t=this.room.currentState,n=e.getSender();return!!n&&(n===this.rootEvent.getSender()||t.maySendRedactionForEvent(this.rootEvent,n))}}var nN=r=>{var e=r.getType();return ln.M_POLL_START.matches(e)||Fd.matches(e)||sv.matches(e)};class JH{constructor(e){v(this,"room",void 0),v(this,"threadedReceipts",void 0),v(this,"unthreadedReceipts",void 0),v(this,"danglingReceipts",void 0),v(this,"onTimelineEvent",t=>{var n=t.getId();if(n){var i=this.danglingReceipts.remove(n);i==null||i.forEach(o=>{o.receipt.thread_id?this.threadedReceipts.set(o.receipt.thread_id,o.eventId,o.receiptType,o.userId,o.receipt.ts,o.synthetic):this.unthreadedReceipts.set(n,o.receiptType,o.userId,o.receipt.ts,o.synthetic)})}}),this.room=e,this.threadedReceipts=new ez(e),this.unthreadedReceipts=new iN(e),this.danglingReceipts=new tz,e.on(pe.Timeline,this.onTimelineEvent)}add(e,t){for(var[n,i]of Object.entries(e))for(var[o,s]of Object.entries(i))for(var[a,l]of Object.entries(s)){var c=this.room.findEventById(n);c?l.thread_id?this.threadedReceipts.set(l.thread_id,n,o,a,l.ts,t):this.unthreadedReceipts.set(n,o,a,l.ts,t):this.danglingReceipts.add(new QH(n,o,a,l,t))}}hasUserReadEvent(e,t){var n=this.unthreadedReceipts.get(e);if(n&&Lb(n.eventId,t,this.room))return!0;var i=this.room.findEventById(t);if(!i)return b.warn("hasUserReadEvent event ID ".concat(t," not found in room ").concat(this.room.roomId,": this shouldn't happen!")),!1;var o=kc(i),s=this.threadedReceipts.get(o,e);return!!(s&&Lb(s.eventId,t,this.room)||this.userSentLatestEventInThread(o,e))}userSentLatestEventInThread(e,t){var n,i=e===Tf?this.room.getLiveTimeline().getEvents():(n=this.room.getThread(e))===null||n===void 0?void 0:n.timeline;return!!(i&&i.length>0&&i[i.length-1].getSender()===t)}}class XH{constructor(e,t,n){this.eventId=e,this.receiptType=t,this.ts=n}}class QH{constructor(e,t,n,i,o){this.eventId=e,this.receiptType=t,this.userId=n,this.receipt=i,this.synthetic=o}}class ZH{constructor(e){v(this,"room",void 0),v(this,"real",void 0),v(this,"synthetic",void 0),this.room=e,this.real=void 0,this.synthetic=void 0}set(e,t){e?this.synthetic=t:this.real=t,this.synthetic&&this.real&&Lb(this.real.eventId,this.synthetic.eventId,this.room)&&(this.synthetic=void 0)}get(){var e;return(e=this.synthetic)!==null&&e!==void 0?e:this.real}getByType(e){return e?this.synthetic:this.real}}class iN{constructor(e){v(this,"room",void 0),v(this,"data",void 0),this.room=e,this.data=new Map}set(e,t,n,i,o){var s=Mw(this.data,n,()=>new ZH(this.room)),a=s.getByType(o);a&&rz(a.eventId,e,this.room)||s.set(o,new XH(e,t,i))}get(e){var t;return(t=this.data.get(e))===null||t===void 0?void 0:t.get()}}class ez{constructor(e){v(this,"room",void 0),v(this,"data",void 0),this.room=e,this.data=new Map}set(e,t,n,i,o,s){var a=Mw(this.data,e,()=>new iN(this.room));a.set(t,n,i,o,s)}get(e,t){var n;return(n=this.data.get(e))===null||n===void 0?void 0:n.get(t)}}class tz{constructor(){v(this,"data",new Map)}add(e){var t=Mw(this.data,e.eventId,()=>[]);t.push(e)}remove(e){var t=this.data.get(e);return this.data.delete(e),t}}function Mw(r,e,t){var n=r.get(e);if(n)return n;var i=t();return r.set(e,i),i}function Lb(r,e,t){var n=t.compareEventOrdering(r,e);return n!==null&&n>=0}function rz(r,e,t){var n=t.compareEventOrdering(r,e);return n!==null&&n>0}function nz(r,e,t){var n=r.findEventById(e),i=r.findEventById(t);if(!n||!i)return null;var o=qd(n),s=qd(i);return o&&s?iz(r,e,t,n,i):oz(e,t,n,i)}function iz(r,e,t,n,i){var o=r.getUnfilteredTimelineSet(),s=o.compareEventOrdering(e,t);if(s!==null)return s;var a=o.getTimelineForEvent(e);if(a===o.getLiveTimeline())return 1;var l=o.getTimelineForEvent(t);return l===o.getLiveTimeline()?-1:oN(n,i)}function oz(r,e,t,n){var i=kc(t),o=kc(n),s=t.getThread();return s&&i===o?s.timelineSet.compareEventOrdering(r,e):oN(t,n)}function oN(r,e){var t=r.getTs(),n=e.getTs();return t<n?-1:t>n?1:0}var Z=function(r){return r.Get="GET",r.Put="PUT",r.Post="POST",r.Delete="DELETE",r.Options="OPTIONS",r.Head="HEAD",r.Patch="PATCH",r}({});function MC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function sz(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?MC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):MC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class _c extends Error{constructor(e,t,n){super(e),this.httpStatus=t,this.httpHeaders=n}isRateLimitError(){return this.httpStatus===429}getRetryAfterMs(){var e,t=(e=this.httpHeaders)===null||e===void 0?void 0:e.get("Retry-After");if(t!=null){if(/^\d+$/.test(t)){var n=Number.parseInt(t)*1e3;if(!Number.isFinite(n))throw new Error("Retry-After header integer value is too large");return n}var i=new Date(t);if(i.toUTCString()!==t)throw new Error("Retry-After header value is not a valid HTTP-date or non-negative decimal integer");return i.getTime()-Date.now()}return null}}class hr extends _c{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0,s=e.error||"Unknown message";t&&(s="[".concat(t,"] ").concat(s)),n&&(s="".concat(s," (").concat(n,")")),super("MatrixError: ".concat(s),t,o),this.url=n,this.event=i,v(this,"errcode",void 0),v(this,"data",void 0),this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.data=e}isRateLimitError(){return this.errcode==="M_LIMIT_EXCEEDED"||(this.errcode==="M_UNKNOWN"||this.errcode===void 0)&&super.isRateLimitError()}getRetryAfterMs(){var e=super.getRetryAfterMs();if(e!==null)return e;if(this.errcode==="M_LIMIT_EXCEEDED"&&"retry_after_ms"in this.data){if(!Number.isInteger(this.data.retry_after_ms))throw new Error("retry_after_ms is not an integer");return this.data.retry_after_ms}return null}asWidgetApiErrorData(){var e,t,n,i,o={};if(this.httpHeaders)for(var[s,a]of this.httpHeaders)o[s]=a;return{http_status:(e=this.httpStatus)!==null&&e!==void 0?e:400,http_headers:o,url:(t=this.url)!==null&&t!==void 0?t:"",response:sz({errcode:(n=this.errcode)!==null&&n!==void 0?n:"M_UNKNOWN",error:(i=this.data.error)!==null&&i!==void 0?i:"Unknown message"},this.data)}}static fromWidgetApiErrorData(e){return new hr(e.response,e.http_status,e.url,void 0,new Headers(e.http_headers))}}function Aw(r,e){if(!(r instanceof _c)||!r.isRateLimitError())return e;try{var t;return(t=r.getRetryAfterMs())!==null&&t!==void 0?t:e}catch{return e}}class Rf extends Error{constructor(e,t){super(e+(t?": ".concat(t.message):""))}get name(){return"ConnectionError"}}var Ub=function(r){return r.SessionLoggedOut="Session.logged_out",r.NoConsent="no_consent",r}({});/*!
287
- * content-type
288
- * Copyright(c) 2015 Douglas Christopher Wilson
289
- * MIT Licensed
290
- */var AC=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,az=/\\([\u000b\u0020-\u00ff])/g,lz=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,cz=uz;function uz(r){if(!r)throw new TypeError("argument string is required");var e=typeof r=="object"?dz(r):r;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var t=e.indexOf(";"),n=t!==-1?e.slice(0,t).trim():e.trim();if(!lz.test(n))throw new TypeError("invalid media type");var i=new fz(n.toLowerCase());if(t!==-1){var o,s,a;for(AC.lastIndex=t;s=AC.exec(e);){if(s.index!==t)throw new TypeError("invalid parameter format");t+=s[0].length,o=s[1].toLowerCase(),a=s[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(az,"$1"))),i.parameters[o]=a}if(t!==e.length)throw new TypeError("invalid parameter format")}return i}function dz(r){var e;if(typeof r.getHeader=="function"?e=r.getHeader("content-type"):typeof r.headers=="object"&&(e=r.headers&&r.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function fz(r){this.parameters=Object.create(null),this.type=r}function wm(r){var e=new AbortController;return setTimeout(()=>{e.abort()},r),e.signal}function sN(r){var e=new AbortController;function t(){for(var o of r)o.removeEventListener("abort",n)}function n(){e.abort(),t()}for(var i of r){if(i.aborted){n();break}i.addEventListener("abort",n)}return{signal:e.signal,cleanup:t}}function Dw(r,e){var t,n,i=DC(r)?new Headers(r.getAllResponseHeaders().trim().split(/[\r\n]+/).map(s=>{var a=s.indexOf(":");return[s.substring(0,a),s.substring(a+1)]})):r.headers,o;try{o=hz(i)}catch(s){return s}return((t=o)===null||t===void 0?void 0:t.type)==="application/json"&&e?new hr(JSON.parse(e),r.status,DC(r)?r.responseURL:r.url,void 0,i):((n=o)===null||n===void 0?void 0:n.type)==="text/plain"?new _c("Server returned ".concat(r.status," error: ").concat(e),r.status,i):new _c("Server returned ".concat(r.status," error"),r.status,i)}function DC(r){return"getResponseHeader"in r}function hz(r){var e=r.get("Content-Type");if(e===null)return null;try{return cz(e)}catch(t){throw new Error("Error parsing Content-Type '".concat(e,"': ").concat(t))}}function aN(r,e){return jb.apply(this,arguments)}function jb(){return jb=w(function*(r,e){for(var t=0,n=null;t<r;)try{if(t>0){var i=1e3*Math.pow(2,t);b.log("network operation failed ".concat(t," times, retrying in ").concat(i,"ms...")),yield As(i)}return yield e()}catch(o){if(o instanceof Rf)t+=1,n=o;else throw o}throw n}),jb.apply(this,arguments)}function lN(r,e,t){return e>4||r instanceof Rf&&!t||r.httpStatus&&(r.httpStatus===400||r.httpStatus===403||r.httpStatus===401)||r.name==="AbortError"||r.name==="M_TOO_LARGE"?-1:Aw(r,1e3*Math.pow(2,e))}function NC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function ny(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?NC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):NC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class pz{constructor(e,t){var n;this.eventEmitter=e,this.opts=t,v(this,"abortController",new AbortController),SD(t,["baseUrl","prefix"]),t.onlyData=!!t.onlyData,t.useAuthorizationHeader=(n=t.useAuthorizationHeader)!==null&&n!==void 0?n:!0}abort(){this.abortController.abort(),this.abortController=new AbortController}fetch(e,t){return this.opts.fetchFn?this.opts.fetchFn(e,t):globalThis.fetch(e,t)}setIdBaseUrl(e){this.opts.idBaseUrl=e}idServerRequest(e,t,n,i,o){if(!this.opts.idBaseUrl)throw new Error("No identity server base URL set");var s=void 0,a=void 0;e===Z.Get?s=n:a=n;var l=this.getUrl(t,s,i,this.opts.idBaseUrl),c={json:!0,headers:{}};return o&&(c.headers.Authorization="Bearer ".concat(o)),this.requestOtherUrl(e,l,a,c)}authedRequest(e,t,n,i){var o=arguments,s=this;return w(function*(){var a=o.length>4&&o[4]!==void 0?o[4]:{};n||(n={});var l=ny({},a);s.opts.accessToken&&(s.opts.useAuthorizationHeader?(l.headers||(l.headers={}),l.headers.Authorization||(l.headers.Authorization="Bearer "+s.opts.accessToken),n.access_token&&delete n.access_token):n.access_token||(n.access_token=s.opts.accessToken));try{var c=yield s.request(e,t,n,i,l);return c}catch(f){var u=f;if(u.errcode==="M_UNKNOWN_TOKEN"&&!l.doNotAttemptTokenRefresh){var d=yield s.tryRefreshToken();if(d)return s.authedRequest(e,t,n,i,ny(ny({},a),{},{doNotAttemptTokenRefresh:!0}))}throw u.errcode=="M_UNKNOWN_TOKEN"&&!(l!=null&&l.inhibitLogoutEmit)?s.eventEmitter.emit(Ub.SessionLoggedOut,u):u.errcode=="M_CONSENT_NOT_GIVEN"&&s.eventEmitter.emit(Ub.NoConsent,u.message,u.data.consent_uri),u}})()}tryRefreshToken(){var e=this;return w(function*(){if(!e.opts.refreshToken||!e.opts.tokenRefreshFunction)return!1;try{var{accessToken:t,refreshToken:n}=yield e.opts.tokenRefreshFunction(e.opts.refreshToken);return e.opts.accessToken=t,e.opts.refreshToken=n,!0}catch(o){var i;return(i=e.opts.logger)===null||i===void 0||i.warn("Failed to refresh token",o),!1}})()}request(e,t,n,i,o){var s=this.getUrl(t,n,o==null?void 0:o.prefix,o==null?void 0:o.baseUrl);return this.requestOtherUrl(e,s,i,o)}requestOtherUrl(e,t,n){var i=arguments,o=this;return w(function*(){var s,a,l,c,u,d=i.length>3&&i[3]!==void 0?i[3]:{},f=o.sanitizeUrlForLogs(t);(s=o.opts.logger)===null||s===void 0||s.debug("FetchHttpApi: --> ".concat(e," ").concat(f));var p=Object.assign({},d.headers||{}),h=(a=d.json)!==null&&a!==void 0?a:!0,m=h&&(n==null||(l=n.constructor)===null||l===void 0?void 0:l.name)===Object.name;h&&(m&&!p["Content-Type"]&&(p["Content-Type"]="application/json"),p.Accept||(p.Accept="application/json"));var E=(c=d.localTimeoutMs)!==null&&c!==void 0?c:o.opts.localTimeoutMs,y=(u=d.keepAlive)!==null&&u!==void 0?u:!1,S=[o.abortController.signal];E!==void 0&&S.push(wm(E)),d.abortSignal&&S.push(d.abortSignal);var R;m?R=JSON.stringify(n):R=n;var{signal:k,cleanup:x}=sN(S),T,O=Date.now();try{var C;T=yield o.fetch(t,{signal:k,method:e,body:R,headers:p,mode:"cors",redirect:"follow",referrer:"",referrerPolicy:"no-referrer",cache:"no-cache",credentials:"omit",keepalive:y,priority:d.priority}),(C=o.opts.logger)===null||C===void 0||C.debug("FetchHttpApi: <-- ".concat(e," ").concat(f," [").concat(Date.now()-O,"ms ").concat(T.status,"]"))}catch(F){var N;throw(N=o.opts.logger)===null||N===void 0||N.debug("FetchHttpApi: <-- ".concat(e," ").concat(f," [").concat(Date.now()-O,"ms ").concat(F,"]")),F.name==="AbortError"?F:new Rf("fetch failed",F)}finally{x()}if(!T.ok)throw Dw(T,yield T.text());return o.opts.onlyData?h?T.json():T.text():T})()}sanitizeUrlForLogs(e){try{var t;typeof e=="string"?t=new URL(e):t=e;var n=new URLSearchParams;for(var i of t.searchParams.keys())n.append(i,"xxx");var o=n.toString(),s=o?"?".concat(o):"";return t.origin+t.pathname+s}catch{return"??"}}getUrl(e,t,n,i){var o=i??this.opts.baseUrl,s=o.endsWith("/")?o.slice(0,-1):o,a=new URL(s+(n??this.opts.prefix)+e);return t&&_b(t,a.searchParams),a}}var Pt=function(r){return r.V1="/_matrix/client/v1",r.V3="/_matrix/client/v3",r.Unstable="/_matrix/client/unstable",r}({}),ho=function(r){return r.V2="/_matrix/identity/v2",r}({}),Zl=function(r){return r.V1="/_matrix/media/v1",r.V3="/_matrix/media/v3",r}({}),vz=1e3,mz=0,iy,wo=[],gz=function(){};function LC(r,e){for(var t=arguments.length,n=new Array(t>2?t-2:0),i=2;i<t;i++)n[i-2]=arguments[i];e=e||0,e<0&&(e=0);var o=Date.now()+e,s=mz++,a={runAt:o,func:r,params:n,key:s},l=Sz(wo,function(c){return c.runAt-o});return wo.splice(l,0,a),Nw(),s}function UC(r){if(wo.length!==0){var e;for(e=0;e<wo.length;e++){var t=wo[e];if(t.key==r){wo.splice(e,1);break}}e===0&&Nw()}}function Nw(){iy&&globalThis.clearTimeout(iy);var r=wo[0];if(r){var e=Date.now(),t=Math.min(r.runAt-e,vz);iy=globalThis.setTimeout(yz,t)}}function yz(){for(var r=Date.now(),e=[];;){var t=wo[0];if(!t||t.runAt>r)break;var n=wo.shift();gz("runCallbacks: popping",n.key),e.push(n)}Nw();for(var i of e)try{i.func.apply(globalThis,i.params)}catch(o){b.error("Uncaught exception in callback function",o)}}function Sz(r,e){for(var t=0,n=r.length;t<n;){var i=t+n>>1,o=e(r[i]);o>0?n=i:t=i+1}return t}class cN extends pz{constructor(){super(...arguments),v(this,"uploads",[])}uploadContent(e){var t,n,i,o,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=(t=s.includeFilename)!==null&&t!==void 0?t:!0,l=(n=s.abortController)!==null&&n!==void 0?n:new AbortController,c=((i=s.type)!==null&&i!==void 0?i:e.type)||"application/octet-stream",u=(o=s.name)!==null&&o!==void 0?o:e.name,d={loaded:0,total:0,abortController:l},f=Hs();if(globalThis.XMLHttpRequest){var p=new globalThis.XMLHttpRequest,h=function(){p.abort(),f.reject(new Error("Timeout"))},m=LC(h,3e4);p.onreadystatechange=function(){switch(p.readyState){case globalThis.XMLHttpRequest.DONE:UC(m);try{if(p.status===0)throw new DOMException(p.statusText,"AbortError");if(!p.responseText)throw new Error("No response body.");p.status>=400?f.reject(Dw(p,p.responseText)):f.resolve(JSON.parse(p.responseText))}catch(R){if(R.name==="AbortError"){f.reject(R);return}f.reject(new Rf("request failed",R))}break}},p.upload.onprogress=R=>{var k;UC(m),d.loaded=R.loaded,d.total=R.total,m=LC(h,3e4),(k=s.progressHandler)===null||k===void 0||k.call(s,{loaded:R.loaded,total:R.total})};var E=this.getUrl("/upload",void 0,Zl.V3);a&&u&&E.searchParams.set("filename",encodeURIComponent(u)),!this.opts.useAuthorizationHeader&&this.opts.accessToken&&E.searchParams.set("access_token",encodeURIComponent(this.opts.accessToken)),p.open(Z.Post,E.href),this.opts.useAuthorizationHeader&&this.opts.accessToken&&p.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),p.setRequestHeader("Content-Type",c),p.send(e),l.signal.addEventListener("abort",()=>{p.abort()})}else{var y={};a&&u&&(y.filename=u);var S={"Content-Type":c};this.authedRequest(Z.Post,"/upload",y,e,{prefix:Zl.V3,headers:S,abortSignal:l.signal}).then(R=>this.opts.onlyData?R:R.json()).then(f.resolve,f.reject)}return d.promise=f.promise.finally(()=>{iv(this.uploads,R=>R===d)}),l.signal.addEventListener("abort",()=>{iv(this.uploads,R=>R===d),f.reject(new DOMException("Aborted","AbortError"))}),this.uploads.push(d),d.promise}cancelUpload(e){var t=this.uploads.find(n=>n.promise===e);return t?(t.abortController.abort(),!0):!1}getCurrentUploads(){return this.uploads}getContentUri(){return{base:this.opts.baseUrl,path:Zl.V3+"/upload",params:{access_token:this.opts.accessToken}}}}var bz=6*60*60*1e3,_z=30*1e3,uN=function(r){return r.Stable="stable",r.Unstable="unstable",r}({});class dN{constructor(e){var t=this;this.http=e,v(this,"capabilities",void 0),v(this,"retryTimeout",void 0),v(this,"refreshTimeout",void 0),v(this,"fetchCapabilities",w(function*(){var n=yield t.http.authedRequest(Z.Get,"/capabilities");return t.capabilities=n.capabilities,t.capabilities})),v(this,"poll",w(function*(){try{yield t.fetchCapabilities(),t.clearTimeouts(),t.refreshTimeout=setTimeout(t.poll,bz),b.debug("Fetched new server capabilities")}catch(i){t.clearTimeouts();var n=Math.floor(_z+Math.random()*5e3);t.retryTimeout=setTimeout(t.poll,n),b.warn("Failed to refresh capabilities: retrying in ".concat(n,"ms"),i)}}))}start(){this.poll().then()}stop(){this.clearTimeouts()}getCachedCapabilities(){return this.capabilities}clearTimeouts(){this.refreshTimeout&&(clearInterval(this.refreshTimeout),this.refreshTimeout=void 0),this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=void 0)}}function jC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function du(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?jC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):jC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var fN="10",Ez=["1","2","3","4","5","6","7","8","9","10"],wz=30,it=function(r){return r.Highlight="highlight",r.Total="total",r}({}),pe=function(r){return r.MyMembership="Room.myMembership",r.Tags="Room.tags",r.AccountData="Room.accountData",r.Receipt="Room.receipt",r.Name="Room.name",r.Redaction="Room.redaction",r.RedactionCancelled="Room.redactionCancelled",r.LocalEchoUpdated="Room.localEchoUpdated",r.Timeline="Room.timeline",r.TimelineReset="Room.timelineReset",r.TimelineRefresh="Room.TimelineRefresh",r.OldStateUpdated="Room.OldStateUpdated",r.CurrentStateUpdated="Room.CurrentStateUpdated",r.HistoryImportedWithinTimeline="Room.historyImportedWithinTimeline",r.UnreadNotifications="Room.UnreadNotifications",r.Summary="Room.Summary",r}({});class Tm extends tN{constructor(e,t,n){var i,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),i=this,this.roomId=e,this.client=t,this.myUserId=n,this.opts=o,v(this,"reEmitter",void 0),v(this,"txnToEvent",new Map),v(this,"notificationCounts",{}),v(this,"threadNotifications",new Map),v(this,"cachedThreadReadReceipts",new Map),v(this,"oldestThreadedReceiptTs",1/0),v(this,"unthreadedReceipts",new Map),v(this,"timelineSets",void 0),v(this,"polls",new Map),v(this,"threadsTimelineSets",[]),v(this,"filteredTimelineSets",{}),v(this,"timelineNeedsRefresh",!1),v(this,"pendingEventList",void 0),v(this,"blacklistUnverifiedDevices",void 0),v(this,"selfMembership",void 0),v(this,"summaryHeroes",null),v(this,"getTypeWarning",!1),v(this,"getVersionWarning",!1),v(this,"membersPromise",void 0),v(this,"name",void 0),v(this,"normalizedName",void 0),v(this,"tags",{}),v(this,"accountData",new Map),v(this,"summary",null),v(this,"oldState",void 0),v(this,"currentState",void 0),v(this,"relations",void 0),v(this,"threads",new Map),v(this,"visibilityEvents",new Map),v(this,"roomReceipts",new JH(this)),v(this,"threadTimelineSetsPromise",null),v(this,"threadsReady",!1),v(this,"updateThreadRootEvents",(s,a,l)=>{if(s.length){var c;if(this.updateThreadRootEvent((c=this.threadsTimelineSets)===null||c===void 0?void 0:c[0],s,a,l),s.hasCurrentUserParticipated){var u;this.updateThreadRootEvent((u=this.threadsTimelineSets)===null||u===void 0?void 0:u[1],s,a,l)}}}),v(this,"updateThreadRootEvent",(s,a,l,c)=>{s&&a.rootEvent&&(c&&s.removeEvent(a.id),Et.hasServerSideSupport?s.addLiveEvent(a.rootEvent,{duplicateStrategy:td.Replace,fromCache:!1,roomState:this.currentState}):s.addEventToTimeline(a.rootEvent,s.getLiveTimeline(),{toStartOfTimeline:l}))}),v(this,"applyRedaction",s=>{if(s.isRedaction()){var a=s.event.redacts,l=a?this.findEventById(a):void 0;if(l){var c=l.threadRootId;if(l.makeRedacted(s,this),l.isState()){var u=this.currentState.getStateEvents(l.getType(),l.getStateKey());(u==null?void 0:u.getId())===l.getId()&&this.currentState.setStateEvents([l])}this.emit(pe.Redaction,s,this,c),this.visibilityEvents.delete(a),l.isVisibilityEvent()&&this.redactVisibilityChangeEvent(s)}}}),this.setMaxListeners(100),this.reEmitter=new Vc(this),o.pendingEventOrdering=o.pendingEventOrdering||Cc.Chronological,this.name=e,this.normalizedName=e,this.relations=new BD(this.client,this),this.on(pe.Receipt,this.onReceipt),this.timelineSets=[new Bl(this,o)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[pe.Timeline,pe.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===Cc.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then(s=>{var a=this.client.getEventMapper({toDevice:!1,decrypt:!1});s.forEach(function(){var l=w(function*(c){var u=a(c);yield t.decryptEventIfNeeded(u),u.setStatus(je.NOT_SENT),i.addPendingEvent(u,u.getTxnId())});return function(c){return l.apply(this,arguments)}}())})),this.opts.lazyLoadMembers?this.membersPromise=void 0:this.membersPromise=Promise.resolve(!1)}createThreadsTimelineSets(){var e=this;return w(function*(){var t;if(e.threadTimelineSetsPromise)return e.threadTimelineSetsPromise;if((t=e.client)!==null&&t!==void 0&&t.supportsThreads())try{e.threadTimelineSetsPromise=Promise.all([e.createThreadTimelineSet(),e.createThreadTimelineSet(di.My)]);var n=yield e.threadTimelineSetsPromise;return e.threadsTimelineSets[0]=n[0],e.threadsTimelineSets[1]=n[1],n}catch{return e.threadTimelineSetsPromise=null,null}return null})()}decryptCriticalEvents(){var e=this;return w(function*(){if(e.client.isCryptoEnabled()){var t=e.getEventReadUpTo(e.client.getUserId(),!0),n=e.getLiveTimeline().getEvents(),i=n.findIndex(s=>s.event.event_id===t),o=n.slice(i).reverse().map(s=>e.client.decryptEventIfNeeded(s));yield Promise.allSettled(o)}})()}decryptAllEvents(){var e=this;return w(function*(){if(e.client.isCryptoEnabled()){var t=e.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0).reverse().map(n=>e.client.decryptEventIfNeeded(n));yield Promise.allSettled(t)}})()}getCreator(){var e,t=this.currentState.getStateEvents(V.RoomCreate,"");return(e=t==null?void 0:t.getSender())!==null&&e!==void 0?e:null}getVersion(){var e,t=this.currentState.getStateEvents(V.RoomCreate,"");return t?(e=t.getContent().room_version)!==null&&e!==void 0?e:"1":(this.getVersionWarning||(b.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}getRecommendedVersion(){var e=this;return w(function*(){var t={};try{t=yield e.client.getCapabilities()}catch{}var n=t["m.room_versions"];if(!n){n={default:fN,available:{}};for(var i of Ez)n.available[i]=uN.Stable}var o=e.checkVersionAgainstCapability(n);if(o.urgent&&o.needsUpgrade){b.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");try{t=yield e.client.fetchCapabilities()}catch(s){b.warn("Failed to refresh room version capabilities",s)}if(n=t["m.room_versions"],n)o=e.checkVersionAgainstCapability(n);else return b.warn("No room version capability - assuming upgrade required."),o}return o})()}checkVersionAgainstCapability(e){var t=this.getVersion();b.log("[".concat(this.roomId,"] Current version: ").concat(t)),b.log("[".concat(this.roomId,"] Version capability: "),e);var n={version:t,needsUpgrade:!1,urgent:!1};if(t===e.default)return n;var i=Object.keys(e.available).filter(o=>e.available[o]==="stable");return i.includes(t)||(n.version=e.default,n.needsUpgrade=!0,n.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),n.urgent?b.warn("URGENT upgrade required on ".concat(this.roomId)):b.warn("Non-urgent upgrade required on ".concat(this.roomId))),n}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(V.RoomTombstone,e)}getPendingEvents(){if(!this.pendingEventList)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(!this.pendingEventList)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);var t=iv(this.pendingEventList,function(n){return n.getId()==e},!1);return this.savePendingEvents(),t}hasPendingEvent(e){var t,n;return(t=(n=this.pendingEventList)===null||n===void 0?void 0:n.some(i=>i.getId()===e))!==null&&t!==void 0?t:!1}getPendingEvent(e){var t,n;return(t=(n=this.pendingEventList)===null||n===void 0?void 0:n.find(i=>i.getId()===e))!==null&&t!==void 0?t:null}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}get timeline(){return this.getLiveTimeline().getEvents()}getLastActiveTimestamp(){var e=this.getLiveTimeline(),t=e.getEvents();if(t.length){var n=t[t.length-1];return n.getTs()}else return Number.MIN_SAFE_INTEGER}getLastLiveEvent(){var e,t,n=this.getLiveTimeline().getEvents(),i=n[n.length-1],o=this.getLastThread();if(!o)return i;var s=o.events[o.events.length-1];return((e=i==null?void 0:i.getTs())!==null&&e!==void 0?e:0)>((t=s==null?void 0:s.getTs())!==null&&t!==void 0?t:0)?i:s}getLastThread(){return this.getThreads().reduce((e,t)=>{var n,i;if(!e)return t;var o=t.events[t.events.length-1],s=e.events[e.events.length-1];return((n=o==null?void 0:o.getTs())!==null&&n!==void 0?n:0)>=((i=s==null?void 0:s.getTs())!==null&&i!==void 0?i:0)?t:e},void 0)}getMyMembership(){var e;return(e=this.selfMembership)!==null&&e!==void 0?e:Be.Leave}getDMInviter(){var e=this.getMember(this.myUserId);if(e)return e.getDMInviter();if(this.selfMembership===Be.Invite){var t=this.getInvitedAndJoinedMemberCount();if(t===2){var n;return(n=this.summaryHeroes)===null||n===void 0?void 0:n[0]}}}guessDMUserId(){var e=this.getMember(this.myUserId);if(e){var t=e.getDMInviter();if(t)return t}if(Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length)return this.summaryHeroes[0];var n=this.currentState.getMembers(),i=n.find(o=>o.userId!==this.myUserId);return i?i.userId:this.myUserId}getFunctionalMembers(){var e=this.currentState.getStateEvents(LD.name,"");return Array.isArray(e==null?void 0:e.getContent().service_members)?e.getContent().service_members:[]}getAvatarFallbackMember(){var e,t=this.getFunctionalMembers(),n=0;if(this.getMembers().forEach(f=>{f.membership!=="join"&&f.membership!=="invite"||t.includes(f.userId)||n++}),!(n>2)){var i=(e=this.summaryHeroes)===null||e===void 0?void 0:e.filter(f=>!t.includes(f)),o=Array.isArray(i)&&i.length;if(o){var s=i.map(f=>this.getMember(f)).find(f=>!!f);if(s)return s}var a=this.getMembers(),l=a==null?void 0:a.filter(f=>!t.includes(f.userId));if(l.length<=2){var c=l.find(f=>f.userId!==this.myUserId);if(c)return c}if(o){var u=i.map(f=>this.client.getUser(f)).find(f=>!!f);if(u){var d=new cv(this.roomId,u.userId);return d.user=u,d}}}}updateMyMembership(e){var t=this.selfMembership;this.selfMembership=e,t!==e&&(e===Be.Leave&&this.cleanupAfterLeaving(),this.emit(pe.MyMembership,this,e,t))}loadMembersFromServer(){var e=this;return w(function*(){var t=e.client.store.getSyncToken(),n=yield e.client.members(e.roomId,void 0,Be.Leave,t??void 0);return n.chunk})()}loadMembers(){var e=this;return w(function*(){var t=!1,n=yield e.client.store.getOutOfBandMembers(e.roomId);(n===null||e.hasEncryptionStateEvent())&&(t=!0,n=yield e.loadMembersFromServer(),b.log("LL: got ".concat(n.length," ")+"members from server for room ".concat(e.roomId)));var i=n.filter(mi).map(e.client.getEventMapper());return{memberEvents:i,fromServer:t}})()}membersLoaded(){return this.opts.lazyLoadMembers?this.currentState.outOfBandMembersReady():!0}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();var e=this.loadMembers().then(t=>(this.currentState.setOutOfBandMembers(t.memberEvents),t.fromServer)).catch(t=>{throw this.membersPromise=void 0,this.currentState.markOutOfBandMembersFailed(),t});return e.then(t=>{if(t){var n=this.currentState.getMembers().filter(o=>o.isOutOfBand()).map(o=>{var s;return(s=o.events.member)===null||s===void 0?void 0:s.event});b.log("LL: telling store to write ".concat(n.length)+" members for room ".concat(this.roomId));var i=this.client.store;return i.setOutOfBandMembers(this.roomId,n).catch(o=>{b.log("LL: storing OOB room members failed, oh well",o)})}}).catch(t=>{b.error(t)}),this.membersPromise=e,this.membersPromise}clearLoadedMembersIfNeeded(){var e=this;return w(function*(){e.opts.lazyLoadMembers&&e.membersPromise&&(yield e.loadMembersIfNeeded(),yield e.client.store.clearOutOfBandMembers(e.roomId),e.currentState.clearOutOfBandMembers(),e.membersPromise=void 0)})()}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch(e=>{b.error("error after clearing loaded members from "+"room ".concat(this.roomId," after leaving")),b.log(e)})}refreshLiveTimeline(){var e=this;return w(function*(){var t=e.getLiveTimeline(),n=t.getPaginationToken(we.FORWARDS),i=t.getPaginationToken(we.BACKWARDS),o=t.getEvents(),s=o[o.length-1];b.log("[refreshLiveTimeline for ".concat(e.roomId,"] at ")+"mostRecentEventInTimeline=".concat(s&&s.getId()," ")+"liveTimelineBefore=".concat(t.toString()," ")+"forwardPaginationToken=".concat(n," ")+"backwardPaginationToken=".concat(i));var a=e.getUnfilteredTimelineSet(),l;s?(e.resetLiveTimeline(null,null),e.emit(pe.TimelineRefresh,e,a),l=yield e.client.getEventTimeline(a,s.getId())):l=yield e.client.getLatestTimeline(a);var c=a.getLiveTimeline();!c||c.getPaginationToken(Ge.Forward)===null&&c.getPaginationToken(Ge.Backward)===null&&c.getEvents().length===0?(b.log("[refreshLiveTimeline for ".concat(e.roomId,"] using our new live timeline")),l.setPaginationToken(n,we.FORWARDS),a.setLiveTimeline(l),e.fixUpLegacyTimelineFields()):b.log("[refreshLiveTimeline for ".concat(e.roomId,"] `/sync` or some other request beat us to creating a new ")+"live timeline after we reset it. We'll use that instead since any events in the scrollback from this timeline will include the history."),e.setTimelineNeedsRefresh(!1),e.emit(pe.TimelineRefresh,e,a)})()}resetLiveTimeline(e,t){for(var n of this.timelineSets)n.resetLiveTimeline(e??void 0,t??void 0);for(var i of this.threads.values())i.resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){var e=this.oldState,t=this.currentState;this.oldState=this.getLiveTimeline().getState(we.BACKWARDS),this.currentState=this.getLiveTimeline().getState(we.FORWARDS),e!==this.oldState&&this.emit(pe.OldStateUpdated,this,e,this.oldState),t!==this.currentState&&(this.emit(pe.CurrentStateUpdated,this,t,this.currentState),this.reEmitter.stopReEmitting(t,[Me.Events,Me.Members,Me.NewMember,Me.Update,Me.Marker,kt.New,kt.Update,kt.Destroy,kt.LivenessChange]),this.reEmitter.reEmit(this.currentState,[Me.Events,Me.Members,Me.NewMember,Me.Update,Me.Marker,kt.New,kt.Update,kt.Destroy,kt.LivenessChange]))}onReceipt(e){this.hasEncryptionStateEvent()&&this.clearNotificationsOnReceipt(e)}clearNotificationsOnReceipt(e){var t=[],n=!1,i=e.getContent();for(var o of Object.values(i))for(var[s,a]of Object.entries(o))if(kw(s)&&a){for(var[l,c]of Object.entries(a))if(!(!c||typeof c!="object")){var u=c;l===this.client.getUserId()&&(u.thread_id===void 0?n=!0:typeof u.thread_id=="string"&&t.push(u.thread_id))}}n&&(t=this.getThreads().filter(x=>this.getThreadUnreadNotificationCount(x.id,it.Total)>0||this.getThreadUnreadNotificationCount(x.id,it.Highlight)>0).map(x=>x.id),t.push("main"));for(var d of t){var f,p=20,h=d==="main"?this.getLiveTimeline():(f=this.getThread(d))===null||f===void 0?void 0:f.liveTimeline;if(!h){b.warn("Couldn't find timeline for thread ID ".concat(d," in room ").concat(this.roomId));continue}for(var m=h.getEvents(),E=0,y=m.length-1;y>=0;y--){var S;if(y===m.length-p)return;var R=m[y];if(this.hasUserReadEvent(this.client.getUserId(),R.getId()))break;var k=this.client.getPushActionsForEvent(R);E+=k!=null&&(S=k.tweaks)!==null&&S!==void 0&&S.highlight?1:0}d==="main"?this.setUnreadNotificationCount(it.Highlight,E):this.setThreadUnreadNotificationCount(d,it.Highlight,E)}}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){var t=this.findEventById(e),n=this.findThreadForEvent(t);return n?n.timelineSet.getTimelineForEvent(e):this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(e){this.timelineNeedsRefresh=e}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(e){var t=this.getUnfilteredTimelineSet().findEventById(e);if(!t)for(var n=this.getThreads(),i=0;i<n.length;i++){var o=n[i];if(t=o.findEventById(e),t)return t}return t}getUnreadNotificationCount(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:it.Total,t=this.getRoomUnreadNotificationCount(e);for(var n of this.threadNotifications.values()){var i;t+=(i=n[e])!==null&&i!==void 0?i:0}return t}getUnreadCountForEventContext(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:it.Total,n=arguments.length>1?arguments[1]:void 0,i=!!n.threadRootId&&!n.isThreadRoot;return(e=i?this.getThreadUnreadNotificationCount(n.threadRootId,t):this.getRoomUnreadNotificationCount(t))!==null&&e!==void 0?e:0}getRoomUnreadNotificationCount(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:it.Total;return(e=this.notificationCounts[t])!==null&&e!==void 0?e:0}getThreadUnreadNotificationCount(e){var t,n,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:it.Total;return(t=(n=this.threadNotifications.get(e))===null||n===void 0?void 0:n[i])!==null&&t!==void 0?t:0}hasThreadUnreadNotification(){for(var e of this.threadNotifications.values()){var t,n;if(((t=e.highlight)!==null&&t!==void 0?t:0)>0||((n=e.total)!==null&&n!==void 0?n:0)>0)return!0}return!1}setThreadUnreadNotificationCount(e,t,n){var i,o,s=du({highlight:(i=this.threadNotifications.get(e))===null||i===void 0?void 0:i.highlight,total:(o=this.threadNotifications.get(e))===null||o===void 0?void 0:o.total},{[t]:n});this.threadNotifications.set(e,s),this.emit(pe.UnreadNotifications,s,e)}get threadsAggregateNotificationType(){var e=null;for(var t of this.threadNotifications.values()){var n,i;if(((n=t.highlight)!==null&&n!==void 0?n:0)>0)return it.Highlight;((i=t.total)!==null&&i!==void 0?i:0)>0&&!e&&(e=it.Total)}return e}resetThreadUnreadNotificationCountFromSync(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=this.hasEncryptionStateEvent();for(var[n,i]of this.threadNotifications)e.includes(n)||(i.total=0,t||(i.highlight=0));this.emit(pe.UnreadNotifications)}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t,this.emit(pe.UnreadNotifications,this.notificationCounts)}setUnread(e,t){return this.setUnreadNotificationCount(e,t)}setSummary(e){var t=e["m.heroes"],n=e["m.joined_member_count"],i=e["m.invited_member_count"];Number.isInteger(n)&&this.currentState.setJoinedMemberCount(n),Number.isInteger(i)&&this.currentState.setInvitedMemberCount(i),Array.isArray(t)&&(this.summaryHeroes=t.filter(o=>o!==this.myUserId)),this.emit(pe.Summary,e)}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return this.blacklistUnverifiedDevices===void 0?null:this.blacklistUnverifiedDevices}getAvatarUrl(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,s=this.currentState.getStateEvents(V.RoomAvatar,"");if(!s&&!o)return null;var a=s?s.getContent().url:null;return a?bm(e,a,t,n,i):null}getMxcAvatarUrl(){var e;return((e=this.currentState.getStateEvents(V.RoomAvatar,""))===null||e===void 0||(e=e.getContent())===null||e===void 0?void 0:e.url)||null}getCanonicalAlias(){var e=this.currentState.getStateEvents(V.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){var e=this.currentState.getStateEvents(V.RoomCanonicalAlias,"");return e?e.getContent().alt_aliases||[]:[]}addEventsToTimeline(e,t,n,i){n.getTimelineSet().addEventsToTimeline(e,t,n,i)}getThread(e){var t;return(t=this.threads.get(e))!==null&&t!==void 0?t:null}getThreads(){return Array.from(this.threads.values())}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership(Be.Join)}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter(function(t){return t.membership===e})}getEncryptionTargetMembers(){var e=this;return w(function*(){yield e.loadMembersIfNeeded();var t=e.getMembersWithMembership(Be.Join);return e.shouldEncryptForInvitedMembers()&&(t=t.concat(e.getMembersWithMembership(Be.Invite))),t})()}shouldEncryptForInvitedMembers(){var e,t=this.currentState.getStateEvents(V.RoomHistoryVisibility,"");return(t==null||(e=t.getContent())===null||e===void 0?void 0:e.history_visibility)!=="joined"}getDefaultRoomName(e){return this.calculateRoomName(e,!0)}hasMembershipState(e,t){var n=this.getMember(e);return n?n.membership===t:!1}getOrCreateFilteredTimelineSet(e){var{prepopulateTimeline:t=!0,useSyncEvents:n=!0,pendingEvents:i=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];var o=Object.assign({filter:e,pendingEvents:i},this.opts),s=new Bl(this,o);this.reEmitter.reEmit(s,[pe.Timeline,pe.TimelineReset]),n&&(this.filteredTimelineSets[e.filterId]=s,this.timelineSets.push(s));var a=this.getLiveTimeline();if(t){a.getEvents().forEach(function(u){s.addLiveEvent(u)});for(var l=a;l.getNeighbouringTimeline(we.BACKWARDS);)l=l.getNeighbouringTimeline(we.BACKWARDS);s.getLiveTimeline().setPaginationToken(l.getPaginationToken(we.BACKWARDS),we.BACKWARDS)}else if(n){var c=a.getPaginationToken(Ge.Forward);s.getLiveTimeline().setPaginationToken(c,Ge.Backward)}return s}getThreadListFilter(){var e=arguments,t=this;return w(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:di.All,i=t.client.getUserId(),o=new gn(i),s={room:{timeline:{[oc.name]:[vt.name]}}};n===di.My&&(s.room.timeline[ic.name]=[i]),o.setDefinition(s);var a=yield t.client.getOrCreateFilter("THREAD_PANEL_".concat(t.roomId,"_").concat(n),o);return o.filterId=a,o})()}createThreadTimelineSet(e){var t=this;return w(function*(){var n;if(Et.hasServerSideListSupport)n=new Bl(t,du(du({},t.opts),{},{pendingEvents:!1}),void 0,void 0,e??di.All),t.reEmitter.reEmit(n,[pe.Timeline,pe.TimelineReset]);else if(Et.hasServerSideSupport){var i=yield t.getThreadListFilter(e);n=t.getOrCreateFilteredTimelineSet(i,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else n=new Bl(t,{pendingEvents:!1}),Array.from(t.threads).forEach(o=>{var[,s]=o;if(s.length!==0){var a=s.timeline.some(l=>l.getSender()===t.client.getUserId());(e!==di.My||a)&&n.getLiveTimeline().addEvent(s.rootEvent,{toStartOfTimeline:!1})}});return n})()}processThreadRoots(e,t){if(this.client.supportsThreads())for(var n of e)we.setEventMetadata(n,this.currentState,t),this.getThread(n.getId())||this.createThread(n.getId(),n,[],t)}fetchRoomThreads(){var e=this;return w(function*(){if(!(e.threadsReady||!e.client.supportsThreads())){if(Et.hasServerSideListSupport)yield Promise.all([e.fetchRoomThreadList(di.All),e.fetchRoomThreadList(di.My)]);else{var t=yield e.getThreadListFilter(),{chunk:n}=yield e.client.createMessagesRequest(e.roomId,"",Number.MAX_SAFE_INTEGER,Ge.Backward,t);if(!n.length)return;var i=n.map(e.client.getEventMapper()).sort((f,p)=>{var h=f.getServerAggregatedRelation(vt.name),m=p.getServerAggregatedRelation(vt.name);return h.latest_event.origin_server_ts-m.latest_event.origin_server_ts}),o,s=e.getLiveTimeline().getState(we.FORWARDS);for(var a of i){var l,c={duplicateStrategy:td.Ignore,fromCache:!1,roomState:s};(l=e.threadsTimelineSets[0])===null||l===void 0||l.addLiveEvent(a,c);var u=a.getServerAggregatedRelation(vt.name);if(u!=null&&u.current_user_participated){var d;(d=e.threadsTimelineSets[1])===null||d===void 0||d.addLiveEvent(a,c),o=a}}e.processThreadRoots(i,!0),e.client.decryptEventIfNeeded(i[i.length-1]),o&&e.client.decryptEventIfNeeded(o)}e.on(Qr.NewReply,e.onThreadReply),e.on(Qr.Update,e.onThreadUpdate),e.on(Qr.Delete,e.onThreadDelete),e.threadsReady=!0}})()}processPollEvents(e){var t=this;return w(function*(){for(var n of e)try{if(!n.isEncrypted()&&!nN(n))continue;yield t.client.decryptEventIfNeeded(n),t.processPollEvent(n)}catch(i){b.warn("Error processing poll event",n.getId(),i)}})()}processPollEvent(e){var t=this;return w(function*(){if(e.isDecryptionFailure()){e.once(ot.Decrypted,s=>{t.processPollEvent(s)});return}if(ln.M_POLL_START.matches(e.getType())){try{var n=new rN(e,t.client,t);t.polls.set(e.getId(),n),t.emit(cs.New,n),e.once(ot.BeforeRedaction,s=>{t.polls.delete(s.getId())})}catch{}return}var i=e.relationEventId;if(i&&t.polls.has(i)){var o=t.polls.get(i);o==null||o.onNewRelation(e)}})()}fetchRoomThreadList(e){var t=this;return w(function*(){if(t.client.supportsThreads()&&t.threadsTimelineSets.length!==0){var n=e===di.My?t.threadsTimelineSets[1]:t.threadsTimelineSets[0],{chunk:i,end:o}=yield t.client.createThreadListMessagesRequest(t.roomId,null,void 0,Ge.Backward,n.threadListType,n.getFilter());if(n.getLiveTimeline().setPaginationToken(o??null,Ge.Backward),!!i.length){var s=i.map(t.client.getEventMapper());t.processThreadRoots(s,!0);var a=t.getLiveTimeline().getState(we.FORWARDS);for(var l of s)n.addLiveEvent(l,{duplicateStrategy:td.Replace,fromCache:!1,roomState:a})}}})()}onThreadUpdate(e){this.updateThreadRootEvents(e,!1,!1)}onThreadReply(e){this.updateThreadRootEvents(e,!1,!0)}onThreadDelete(e){var t;this.threads.delete(e.id);var n=this.getTimelineForEvent(e.id),i=n==null||(t=n.getEvents())===null||t===void 0?void 0:t.find(s=>s.getId()===e.id);i?e.clearEventMetadata(i):b.debug("onThreadDelete: Could not find root event in room timeline");for(var o of this.threadsTimelineSets)o.removeEvent(e.id)}removeFilteredTimelineSet(e){var t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];var n=this.timelineSets.indexOf(t);n>-1&&this.timelineSets.splice(n,1)}eventShouldLiveIn(e,t,n){var i;if(!((i=this.client)!==null&&i!==void 0&&i.supportsThreads()))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||n!=null&&n.has(e.getId()))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};var o=e.isRelation(vt.name),s=e.getAssociatedId(),a=e.threadRootId;if(s&&!o&&(a===s||n!=null&&n.has(s)))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};var l;if(s){var c;l=(c=this.findEventById(s))!==null&&c!==void 0?c:t==null?void 0:t.find(u=>u.getId()===s)}return l&&!o?this.eventShouldLiveIn(l,t,n):a!=null?{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:a}:!s||e.replyEventId?{shouldLiveInRoom:!0,shouldLiveInThread:!1}:{shouldLiveInRoom:!1,shouldLiveInThread:!1}}findThreadForEvent(e){if(!e)return null;var{threadId:t}=this.eventShouldLiveIn(e);return t?this.getThread(t):null}addThreadedEvents(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=this.getThread(e);if(i)i.addEvents(t,n);else{var o,s=(o=this.findEventById(e))!==null&&o!==void 0?o:t.find(a=>a.getId()===e);this.createThread(e,s,t,n)}}processThreadedEvents(e,t){e.forEach(this.applyRedaction);var n={};for(var i of e){var o,{threadId:s,shouldLiveInThread:a}=this.eventShouldLiveIn(i);a&&!n[s]&&(n[s]=[]),(o=n[s])===null||o===void 0||o.push(i)}Object.entries(n).map(l=>{var[c,u]=l;return this.addThreadedEvents(c,u,t)})}createThread(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],o=arguments.length>3?arguments[3]:void 0;if(this.threads.has(e))return this.threads.get(e);if(t){var s=this.relations.getAllChildEventsForEvent(t.getId());s!=null&&s.length&&(i=i.concat(s.filter(l=>!l.isRelation(Nt.Replace))))}var a=new Et(e,t,{room:this,client:this.client,pendingEventOrdering:this.opts.pendingEventOrdering,receipts:(n=this.cachedThreadReadReceipts.get(e))!==null&&n!==void 0?n:[]});return this.reEmitter.reEmit(a,[Qr.Delete,Qr.Update,Qr.NewReply,pe.Timeline,pe.TimelineReset]),this.cachedThreadReadReceipts.delete(e),this.threads.set(a.id,a),a.addEvents(i,!1),this.threadsReady&&a.initialEventsFetched&&this.updateThreadRootEvents(a,o,!1),this.emit(Qr.New,a,o),a}processLiveEvent(e){this.applyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e);var t=e.getUnsigned().transaction_id;if(!t&&e.getSender()===this.myUserId){for(var[n,i]of this.txnToEvent)if(i.getId()===e.getId()){b.debug("processLiveEvent: found sent event without txn ID: ",n,e.getId());var o=e.getUnsigned();o.transaction_id=n,e.setUnsigned(o);break}}}addLiveEvent(e,t){var{duplicateStrategy:n,timelineWasEmpty:i,fromCache:o}=t;for(var s of this.timelineSets)s.addLiveEvent(e,{duplicateStrategy:n,fromCache:o,timelineWasEmpty:i});e.sender&&e.getType()!==V.RoomRedaction&&this.addReceipt(eN(e.sender.userId,e,Xr.Read),!0)}addPendingEvent(e,t){if(e.status!==je.SENDING&&e.status!==je.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent.get(t))throw new Error("addPendingEvent called on an event with known txnId "+t);if(we.setEventMetadata(e,this.getLiveTimeline().getState(we.FORWARDS),!1),this.txnToEvent.set(t,e),this.pendingEventList){if(this.pendingEventList.some(s=>s.status===je.NOT_SENT)&&(b.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(je.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){var n=e.event.redacts,i=this.pendingEventList.find(s=>s.getId()===n);!i&&n&&(i=this.findEventById(n)),i&&(i.markLocallyRedacted(e),this.emit(pe.Redaction,e,this,i.threadRootId))}}else for(var o of this.timelineSets)o.getFilter()?o.getFilter().filterRoomTimeline([e]).length&&o.addEventToTimeline(e,o.getLiveTimeline(),{toStartOfTimeline:!1}):o.addEventToTimeline(e,o.getLiveTimeline(),{toStartOfTimeline:!1});this.emit(pe.LocalEchoUpdated,e,this)}savePendingEvents(){if(this.pendingEventList){var e=this.pendingEventList.map(t=>du(du({},t.event),{},{txn_id:t.getTxnId()})).filter(t=>{var n=t.type===V.RoomMessageEncrypted,i=this.hasEncryptionStateEvent();return n||!i});this.client.store.setPendingEvents(this.roomId,e)}}aggregateNonLiveRelation(e){this.relations.aggregateChildEvent(e)}getEventForTxnId(e){return this.txnToEvent.get(e)}handleRemoteEcho(e,t){var n=t.getId(),i=e.getId(),o=t.status;b.debug("Got remote echo for event ".concat(n," -> ").concat(i," old status ").concat(o)),this.txnToEvent.delete(e.getUnsigned().transaction_id),this.pendingEventList&&this.removePendingEvent(n),t.handleRemoteEcho(e.event);var{shouldLiveInRoom:s,threadId:a}=this.eventShouldLiveIn(e),l=a?this.getThread(a):null;if(l==null||l.setEventMetadata(t),l==null||l.timelineSet.handleRemoteEcho(t,n,i),s)for(var c of this.timelineSets)c.handleRemoteEcho(t,n,i);this.emit(pe.LocalEchoUpdated,t,this,n,o)}updatePendingEvent(e,t,n){if(b.log("setting pendingEvent status to ".concat(t," in ").concat(e.getRoomId()," ")+"event ID ".concat(e.getId()," -> ").concat(n)),t==je.SENT&&!n)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==je.SENT){var i=this.getTimelineForEvent(n);if(i){var o=this.findEventById(n),s=o==null?void 0:o.getUnsigned().transaction_id;if(!s&&o){var a=o.getUnsigned();a.transaction_id=e.getTxnId(),o.setUnsigned(a),this.removeEvent(o.getId()),this.handleRemoteEcho(o,e)}return}}var l=e.status,c=e.getId();if(!l)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");var u=Tz[l];if(!(u!=null&&u.includes(t)))throw new Error("Invalid EventStatus transition ".concat(l,"->").concat(t));if(e.setStatus(t),t==je.SENT){e.replaceLocalEventId(n);var{shouldLiveInRoom:d,threadId:f}=this.eventShouldLiveIn(e),p=f?this.getThread(f):void 0;if(p==null||p.setEventMetadata(e),p==null||p.timelineSet.replaceEventId(c,n),d)for(var h of this.timelineSets)h.replaceEventId(c,n)}else if(t==je.CANCELLED){if(this.pendingEventList){var m=this.getPendingEvent(c);this.removePendingEvent(c),m!=null&&m.isRedaction()&&this.revertRedactionLocalEcho(m)}this.removeEvent(c)}this.savePendingEvents(),this.emit(pe.LocalEchoUpdated,e,this,c,l)}revertRedactionLocalEcho(e){var t=e.event.redacts;if(t){var n=this.getUnfilteredTimelineSet().findEventById(t);n&&(n.unmarkLocallyRedacted(),this.emit(pe.RedactionCancelled,e,this),n.isRelation()&&this.aggregateNonLiveRelation(n))}}assertTimelineSetsAreLive(){for(var e=0;e<this.timelineSets.length;e++){var t=this.timelineSets[e].getLiveTimeline();if(t.getPaginationToken(we.FORWARDS))throw new Error("live timeline "+e+" is no longer live - it has a pagination token ("+t.getPaginationToken(we.FORWARDS)+")");if(t.getNeighbouringTimeline(we.FORWARDS))throw new Error("live timeline ".concat(e," is no longer live - it has a neighbouring timeline"))}}addLiveEvents(e,t){var n=this;return w(function*(){var{duplicateStrategy:i,fromCache:o,timelineWasEmpty:s=!1}=t??{};if(i&&["replace","ignore"].indexOf(i)===-1)throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");n.assertTimelineSetsAreLive();var a=n.findThreadRoots(e),l={},c={duplicateStrategy:i,fromCache:o,timelineWasEmpty:s},u=[...e];for(var d of e){var f;if(n.processLiveEvent(d),d.getUnsigned().transaction_id){var p=n.txnToEvent.get(d.getUnsigned().transaction_id);if(p){n.handleRemoteEcho(d,p);continue}}var{shouldLiveInRoom:h,shouldLiveInThread:m,threadId:E=""}=n.eventShouldLiveIn(d,u,a);if(!m&&!h&&d.isRelation())try{var y=new pr(yield n.client.fetchRoomEvent(n.roomId,d.relationEventId));if(u.push(y),y.threadRootId){a.add(y.threadRootId);var S=d.getUnsigned();S[lv.name]=y.threadRootId,d.setUnsigned(S)}({shouldLiveInRoom:h,shouldLiveInThread:m,threadId:E=""}=n.eventShouldLiveIn(d,u,a))}catch(R){b.error("Failed to load parent event of unhandled relation",R)}m&&!l[E]&&(l[E]=[]),(f=l[E])===null||f===void 0||f.push(d),h?n.addLiveEvent(d,c):!m&&d.isRelation()&&n.relations.aggregateChildEvent(d)}Object.entries(l).forEach(R=>{var[k,x]=R;n.addThreadedEvents(k,x,!1)})})()}partitionThreadedEvents(e){var t=0,n=1,i=2;if(this.client.supportsThreads()){var o=this.findThreadRoots(e);return e.reduce((s,a)=>{var{shouldLiveInRoom:l,shouldLiveInThread:c,threadId:u}=this.eventShouldLiveIn(a,e,o);return l&&s[t].push(a),c&&(a.setThreadId(u??""),s[n].push(a)),!c&&!l&&s[i].push(a),s},[[],[],[]])}else return[e,[],[]]}findThreadRoots(e){var t=new Set;for(var n of e){var i=n.threadRootId;i!=null&&t.add(i)}return t}addReceipt(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=e.getContent();this.roomReceipts.add(n,t),Object.keys(n).forEach(i=>{Object.keys(n[i]).forEach(o=>{Object.keys(n[i][o]).forEach(s=>{var a,l,c,u=n[i][o][s],d=!u.thread_id||u.thread_id===Tf,f=d?this:this.threads.get((a=u.thread_id)!==null&&a!==void 0?a:"");if(f){if(f.addReceiptToStructure(i,o,s,u,t),!t&&this.client.isInitialSyncComplete()&&s===this.client.getUserId()){var p=f.timeline[f.timeline.length-1];p&&i===p.getId()&&s===p.getSender()&&(f.setUnread(it.Total,0),f.setUnread(it.Highlight,0))}}else{var h;this.cachedThreadReadReceipts.set(u.thread_id,[...(h=this.cachedThreadReadReceipts.get(u.thread_id))!==null&&h!==void 0?h:[],{eventId:i,receiptType:o,userId:s,receipt:u,synthetic:t}])}var m=this.client.getUserId();s===m&&!d&&u.ts<this.oldestThreadedReceiptTs&&(this.oldestThreadedReceiptTs=u.ts),!u.thread_id&&u.ts>((l=(c=this.unthreadedReceipts.get(s))===null||c===void 0?void 0:c.ts)!==null&&l!==void 0?l:0)&&this.unthreadedReceipts.set(s,u)})})}),this.emit(pe.Receipt,e,this)}addEphemeralEvents(e){for(var t of e)t.getType()===V.Typing?this.currentState.setTypingEvent(t):t.getType()===V.Receipt&&this.addReceipt(t)}removeEvents(e){for(var t of e)this.removeEvent(t)}removeEvent(e){var t=!1;for(var n of this.timelineSets){var i=n.removeEvent(e);i&&(i.isRedaction()&&this.revertRedactionLocalEcho(i),t=!0)}return t}recalculate(){var e=this.currentState.getStateEvents(V.RoomMember,this.myUserId);if(e){var t=e.getContent().membership;if(this.updateMyMembership(t),t===Be.Invite){var n=e.getUnsigned().invite_room_state||[];n.forEach(o=>{var s=this.currentState.getStateEvents(o.type,o.state_key);s||this.currentState.setStateEvents([new pr({type:o.type,state_key:o.state_key,content:o.content,event_id:"$fake"+Date.now(),room_id:this.roomId,sender:this.myUserId})])})}}var i=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=fH(this.name),this.summary=new KD(this.roomId,{title:this.name}),i!==this.name&&this.emit(pe.Name,this)}addTags(e){this.tags=e.getContent().tags||{},this.emit(pe.Tags,e,this)}addAccountData(e){for(var t of e){t.getType()==="m.tag"&&this.addTags(t);var n=t.getType(),i=this.accountData.get(n);this.accountData.set(n,t),this.emit(pe.AccountData,t,this,i)}}getAccountData(e){return this.accountData.get(e)}maySendMessage(){return this.getMyMembership()===Be.Join&&(this.hasEncryptionStateEvent()?this.currentState.maySendEvent(V.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(V.RoomMessage,this.myUserId))}canInvite(e){var t=this.getMyMembership()===Be.Join,n=this.currentState.getStateEvents(V.RoomPowerLevels,""),i=n&&n.getContent(),o=this.getMember(e);return i&&o&&i.invite>o.powerLevel&&(t=!1),t}getJoinRule(){return this.currentState.getJoinRule()}getHistoryVisibility(){return this.currentState.getHistoryVisibility()}getGuestAccess(){return this.currentState.getGuestAccess()}getType(){var e=this.currentState.getStateEvents(V.RoomCreate,"");if(!e){this.getTypeWarning||(b.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0);return}return e.getContent()[av]}isSpaceRoom(){return this.getType()===Ql.Space}isCallRoom(){return this.getType()===Ql.UnstableCall}isElementVideoRoom(){return this.getType()===Ql.ElementVideo}findPredecessor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.getLiveTimeline().getState(we.FORWARDS);return t?t.findPredecessor(e):null}roomNameGenerator(e){if(this.client.roomNameGenerator){var t=this.client.roomNameGenerator(this.roomId,e);if(t!==null)return t}switch(e.type){case Ni.Actual:return e.name;case Ni.Generated:switch(e.subtype){case"Inviting":return"Inviting ".concat(FC(e.names,e.count));default:return FC(e.names,e.count)}case Ni.EmptyRoom:return e.oldName?"Empty room (was ".concat(e.oldName,")"):"Empty room"}}calculateRoomName(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!t){var n=this.currentState.getStateEvents(V.RoomName,"");if(n!=null&&n.getContent().name)return this.roomNameGenerator({type:Ni.Actual,name:n.getContent().name})}var i=this.getCanonicalAlias();if(i)return this.roomNameGenerator({type:Ni.Actual,name:i});var o=this.currentState.getJoinedMemberCount(),s=this.currentState.getInvitedMemberCount(),a=o+s-1,l=this.getFunctionalMembers(),c=[];if(this.summaryHeroes)this.summaryHeroes.forEach(y=>{if(l.includes(y)){a--;return}var S=this.getMember(y);c.push(S?S.name:y)});else{var u=this.currentState.getMembers().filter(y=>y.userId!==e&&(y.membership===Be.Invite||y.membership===Be.Join));u=u.filter(y=>{var{userId:S}=y;return l.includes(S)?(a--,!1):!0});var d=new Intl.Collator;u.sort((y,S)=>d.compare(y.userId,S.userId)),u=u.slice(0,5),c=u.map(y=>y.name)}if(a)return this.roomNameGenerator({type:Ni.Generated,names:c,count:a});var f=this.getMyMembership();if(f==Be.Join){var p=this.currentState.getStateEvents(V.RoomThirdPartyInvite);if(p!=null&&p.length){var h=p.map(y=>y.getContent().display_name);return this.roomNameGenerator({type:Ni.Generated,subtype:"Inviting",names:h,count:h.length+1})}}var m=c;m.length||(m=this.currentState.getMembers().filter(y=>y.userId!==e&&y.membership!==Be.Invite&&y.membership!==Be.Join).map(y=>y.name));var E;return m.length&&(E=this.roomNameGenerator({type:Ni.Generated,names:m,count:m.length+1})),this.roomNameGenerator({type:Ni.EmptyRoom,oldName:E})}applyNewVisibilityEvent(e){var t=e.asVisibilityChange();if(t){var n=e.getSender();if(n){var i=Ta.name&&this.currentState.maySendStateEvent(Ta.name,n)||Ta.altName&&this.currentState.maySendStateEvent(Ta.altName,n);if(i){var o=this.visibilityEvents.get(t.eventId);if(o){for(var s=o.length-1,a=Math.max(0,o.length-wz);s>=a;--s){var l=o[s];if(l.getTs()<e.getTs())break}s===-1?o.unshift(e):o.splice(s+1,0,e)}else this.visibilityEvents.set(t.eventId,[e]);var c=this.findEventById(t.eventId);c&&c.applyVisibilityEvent(t)}}}}redactVisibilityChangeEvent(e){if(!e.isVisibilityEvent)throw new Error("expected a visibility change event");var t=e.getRelation(),n=t==null?void 0:t.event_id,i=this.visibilityEvents.get(n);if(i){var o=i.findIndex(c=>c.getId()===e.getId());if(o!==-1&&(i.splice(o,1),o===i.length)){var s=this.findEventById(n);if(!s)return;if(o===0)this.visibilityEvents.delete(n),s.applyVisibilityEvent();else{var a=i[i.length-1],l=a.asVisibilityChange();if(!l)throw new Error("at this stage, visibility changes should be well-formed");s.applyVisibilityEvent(l)}}}}applyPendingVisibilityEvents(e){var t=this.visibilityEvents.get(e.getId());if(!(!t||t.length==0)){var n=t[t.length-1],i=n.asVisibilityChange();i&&(i.visible,!(n.getTs()<e.getTs())&&e.applyVisibilityEvent(i))}}getOldestThreadedReceiptTs(){return this.oldestThreadedReceiptTs}hasUserReadEvent(e,t){return this.roomReceipts.hasUserReadEvent(e,t)}getLastUnthreadedReceiptFor(e){return this.unthreadedReceipts.get(e)}fixupNotifications(e){super.fixupNotifications(e);var t=this.getThreads().filter(i=>this.getThreadUnreadNotificationCount(i.id,it.Total)>0);for(var n of t)n.fixupNotifications(e)}compareEventOrdering(e,t){return nz(this,e,t)}hasEncryptionStateEvent(){var e;return!!(!((e=this.getLiveTimeline().getState(we.FORWARDS))===null||e===void 0)&&e.getStateEvents(V.RoomEncryption,""))}}var Tz={[je.ENCRYPTING]:[je.SENDING,je.NOT_SENT,je.CANCELLED],[je.SENDING]:[je.ENCRYPTING,je.QUEUED,je.NOT_SENT,je.SENT],[je.QUEUED]:[je.SENDING,je.NOT_SENT,je.CANCELLED],[je.SENT]:[],[je.NOT_SENT]:[je.SENDING,je.QUEUED,je.CANCELLED],[je.CANCELLED]:[]},Ni=function(r){return r[r.EmptyRoom=0]="EmptyRoom",r[r.Generated=1]="Generated",r[r.Actual=2]="Actual",r}({});function FC(r,e){var t=e-1;if(r.length){if(r.length===1&&t<=1)return r[0];if(r.length===2&&t<=2)return"".concat(r[0]," and ").concat(r[1]);var n=t>1;return n?"".concat(r[0]," and ").concat(t," others"):"".concat(r[0]," and 1 other")}else return"Empty room"}var lr=function(r){return r[r.Stable=0]="Stable",r[r.Unstable=1]="Unstable",r[r.Unsupported=2]="Unsupported",r}({}),dr=function(r){return r.Thread="Thread",r.ThreadUnreadNotifications="ThreadUnreadNotifications",r.LoginTokenRequest="LoginTokenRequest",r.RelationBasedRedactions="RelationBasedRedactions",r.AccountDataDeletion="AccountDataDeletion",r.RelationsRecursion="RelationsRecursion",r.IntentionalMentions="IntentionalMentions",r}({}),Rz={[dr.Thread]:{unstablePrefixes:["org.matrix.msc3440"],matrixVersion:"v1.3"},[dr.ThreadUnreadNotifications]:{unstablePrefixes:["org.matrix.msc3771","org.matrix.msc3773"],matrixVersion:"v1.4"},[dr.LoginTokenRequest]:{unstablePrefixes:["org.matrix.msc3882"]},[dr.RelationBasedRedactions]:{unstablePrefixes:["org.matrix.msc3912"]},[dr.AccountDataDeletion]:{unstablePrefixes:["org.matrix.msc3391"]},[dr.RelationsRecursion]:{unstablePrefixes:["org.matrix.msc3981"]},[dr.IntentionalMentions]:{unstablePrefixes:["org.matrix.msc3952_intentional_mentions"],matrixVersion:"v1.7"}};function Cz(r){return Fb.apply(this,arguments)}function Fb(){return Fb=w(function*(r){var e=new Map;for(var[t,n]of Object.entries(Rz)){var i,o,s,a,l=(i=(o=r.versions)===null||o===void 0?void 0:o.includes(n.matrixVersion||""))!==null&&i!==void 0?i:!1,c=(s=(a=n.unstablePrefixes)===null||a===void 0?void 0:a.every(u=>{var d;return((d=r.unstable_features)===null||d===void 0?void 0:d[u])===!0}))!==null&&s!==void 0?s:!1;l?e.set(t,lr.Stable):c?e.set(t,lr.Unstable):e.set(t,lr.Unsupported)}return e}),Fb.apply(this,arguments)}function BC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function dv(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?BC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):BC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var KC=80*1e3,kz=3,ct=function(r){return r.Error="ERROR",r.Prepared="PREPARED",r.Stopped="STOPPED",r.Syncing="SYNCING",r.Catchup="CATCHUP",r.Reconnecting="RECONNECTING",r}({}),Iz=["org.matrix.msc2716v3"];function VC(r,e){return"FILTER_SYNC_".concat(r)+(e?"_"+e:"")}function Ot(){b.log(...arguments)}var hN=function(r){return r.Offline="offline",r.Online="online",r.Unavailable="unavailable",r}({});function pN(r){return dv({initialSyncLimit:8,resolveInvitesToProfiles:!1,pollTimeout:30*1e3,pendingEventOrdering:Cc.Chronological,threadSupport:!1},r)}function vN(r){return dv({canResetEntireTimeline:e=>!1},r)}class Au{constructor(e,t,n){var i=this;this.client=e,v(this,"opts",void 0),v(this,"syncOpts",void 0),v(this,"_peekRoom",null),v(this,"currentSyncRequest",void 0),v(this,"abortController",void 0),v(this,"syncState",null),v(this,"syncStateData",void 0),v(this,"catchingUp",!1),v(this,"running",!1),v(this,"keepAliveTimer",void 0),v(this,"connectionReturnedDefer",void 0),v(this,"notifEvents",[]),v(this,"failedSyncCount",0),v(this,"storeIsInvalid",!1),v(this,"presence",void 0),v(this,"getPushRules",w(function*(){try{Ot("Getting push rules...");var o=yield i.client.getPushRules();Ot("Got push rules"),i.client.pushRules=o}catch(s){return b.error("Getting push rules failed",s),i.shouldAbortSync(s)?void 0:(Ot("Waiting for saved sync before retrying push rules..."),yield i.recoverFromSyncStartupError(i.savedSyncPromise,s),i.getPushRules())}})),v(this,"buildDefaultFilter",()=>{var o=new gn(this.client.credentials.userId);return this.client.canSupport.get(dr.ThreadUnreadNotifications)!==lr.Unsupported&&o.setUnreadThreadNotifications(!0),o}),v(this,"prepareLazyLoadingForSync",w(function*(){if(Ot("Prepare lazy loading for sync..."),i.client.isGuest()&&(i.opts.lazyLoadMembers=!1),i.opts.lazyLoadMembers&&(Ot("Enabling lazy load on sync filter..."),i.opts.filter||(i.opts.filter=i.buildDefaultFilter()),i.opts.filter.setLazyLoadMembers(!0)),i.opts.lazyLoadMembers){var o;(o=i.syncOpts.crypto)===null||o===void 0||o.enableLazyLoading()}})),v(this,"storeClientOptions",w(function*(){try{Ot("Storing client options..."),yield i.client.storeClientOptions(),Ot("Stored client options")}catch(o){throw b.error("Storing client options failed",o),o}})),v(this,"getFilter",w(function*(){Ot("Getting filter...");var o;i.opts.filter?o=i.opts.filter:o=i.buildDefaultFilter();var s;try{s=yield i.client.getOrCreateFilter(VC(i.client.credentials.userId),o)}catch(a){return b.error("Getting filter failed",a),i.shouldAbortSync(a)?{}:(Ot("Waiting for saved sync before retrying filter..."),yield i.recoverFromSyncStartupError(i.savedSyncPromise,a),i.getFilter())}return{filter:o,filterId:s}})),v(this,"savedSyncPromise",void 0),v(this,"onOnline",()=>{Ot("Browser thinks we are back online"),this.startKeepAlives(0)}),this.opts=pN(t),this.syncOpts=vN(n),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),[pe.Timeline,pe.TimelineReset])}createRoom(e){var t=mN(this.client,e,this.opts);return t.on(Me.Marker,(n,i)=>{this.onMarkerStateEvent(t,n,i)}),t}onMarkerStateEvent(e,t){var{timelineWasEmpty:n}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(n){b.debug("MarkerState: Ignoring markerEventId=".concat(t.getId()," in roomId=").concat(e.roomId," ")+"because the timeline was empty before the marker arrived which means there is nothing to refresh.");return}var i=Iz.includes(e.getVersion())||t.getSender()===e.getCreator();i?(b.debug("MarkerState: Timeline needs to be refreshed because "+"a new markerEventId=".concat(t.getId()," was sent in roomId=").concat(e.roomId)),e.setTimelineNeedsRefresh(!0),e.emit(pe.HistoryImportedWithinTimeline,t,e)):b.debug("MarkerState: Ignoring markerEventId=".concat(t.getId()," in roomId=").concat(e.roomId," because ")+"MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.")}syncLeftRooms(){var e=this;return w(function*(){var t,n=e.client,i=new gn(e.client.credentials.userId);i.setTimelineLimit(1),i.setIncludeLeaveRooms(!0);var o=e.opts.pollTimeout+KC,s=yield n.getOrCreateFilter(VC(n.credentials.userId,"LEFT_ROOMS"),i),a={timeout:0,filter:s},l=yield n.http.authedRequest(Z.Get,"/sync",a,void 0,{localTimeoutMs:o}),c=[];(t=l.rooms)!==null&&t!==void 0&&t.leave&&(c=e.mapSyncResponseToRoomArray(l.rooms.leave));var u=yield Promise.all(c.map(function(){var d=w(function*(f){var p=f.room;if(f.isBrandNewRoom){f.timeline=f.timeline||{prev_batch:null,events:[]};var h=e.mapSyncEventsFormat(f.timeline,p),m=e.mapSyncEventsFormat(f.state,p);return p.getLiveTimeline().setPaginationToken(f.timeline.prev_batch,we.BACKWARDS),yield e.injectRoomEvents(p,m,h),p.recalculate(),n.store.storeRoom(p),n.emit(be.Room,p),e.processEventsForNotifs(p,h),p}});return function(f){return d.apply(this,arguments)}}()));return u.filter(Boolean)})()}peek(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;if(((t=this._peekRoom)===null||t===void 0?void 0:t.roomId)===e)return Promise.resolve(this._peekRoom);var i=this.client;return this._peekRoom=this.createRoom(e),this.client.roomInitialSync(e,n).then(o=>{var s;if(((s=this._peekRoom)===null||s===void 0?void 0:s.roomId)!==e)throw new Error("Peeking aborted");o.messages=o.messages||{chunk:[]},o.messages.chunk=o.messages.chunk||[],o.state=o.state||[];var a=ym(o.state).map(i.getEventMapper()),l=o.state.map(i.getEventMapper()),c=o.messages.chunk.map(i.getEventMapper());return Array.isArray(o.presence)&&o.presence.map(i.getEventMapper()).forEach(function(u){var d=i.store.getUser(u.getContent().user_id);d?d.setPresenceEvent(u):(d=ko.createUser(u.getContent().user_id,i),d.setPresenceEvent(u),i.store.storeUser(d)),i.emit(be.Event,u)}),o.messages.start&&(this._peekRoom.oldState.paginationToken=o.messages.start),this._peekRoom.oldState.setStateEvents(a),this._peekRoom.currentState.setStateEvents(l),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(c.reverse(),!0,this._peekRoom.getLiveTimeline(),o.messages.start),i.store.storeRoom(this._peekRoom),i.emit(be.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom})}stopPeeking(){this._peekRoom=null}peekPoll(e,t){var n,i=this;if(this._peekRoom!==e){Ot("Stopped peeking in room %s",e.roomId);return}this.client.http.authedRequest(Z.Get,"/events",{room_id:e.roomId,timeout:String(30*1e3),from:t},void 0,{localTimeoutMs:50*1e3,abortSignal:(n=this.abortController)===null||n===void 0?void 0:n.signal}).then(function(){var o=w(function*(s){if(i._peekRoom!==e){Ot("Stopped peeking in room %s",e.roomId);return}s.chunk.filter(function(l){return l.type==="m.presence"}).map(i.client.getEventMapper()).forEach(l=>{var c=i.client.store.getUser(l.getContent().user_id);c?c.setPresenceEvent(l):(c=ko.createUser(l.getContent().user_id,i.client),c.setPresenceEvent(l),i.client.store.storeUser(c)),i.client.emit(be.Event,l)});var a=s.chunk.filter(function(l){return l.room_id===e.roomId&&l.event_id}).map(i.client.getEventMapper());yield e.addLiveEvents(a),i.peekPoll(e,s.end)});return function(s){return o.apply(this,arguments)}}(),o=>{b.error("[%s] Peek poll failed: %s",e.roomId,o),setTimeout(()=>{this.peekPoll(e,t)},30*1e3)})}getSyncState(){return this.syncState}getSyncStateData(){var e;return(e=this.syncStateData)!==null&&e!==void 0?e:null}recoverFromSyncStartupError(e,t){var n=this;return w(function*(){yield e;var i=n.startKeepAlives();n.updateSyncState(ct.Error,{error:t}),yield i})()}shouldAbortSync(e){return e.errcode==="M_UNKNOWN_TOKEN"?(b.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(ct.Error,{error:e}),!0):!1}sync(){var e=this;return w(function*(){var t,n;if(e.running=!0,e.abortController=new AbortController,(t=globalThis.window)===null||t===void 0||(n=t.addEventListener)===null||n===void 0||n.call(t,"online",e.onOnline,!1),e.client.isGuest())return e.doSync({});Ot("Getting saved sync token...");var i=e.client.store.getSavedSyncToken().then(u=>(Ot("Got saved sync token"),u));e.savedSyncPromise=e.client.store.getSavedSync().then(u=>{if(Ot("Got reply from saved sync, exists? ".concat(!!u)),u)return e.syncFromCache(u)}).catch(u=>{b.error("Getting saved sync failed",u)}),yield e.getPushRules(),yield e.prepareLazyLoadingForSync(),yield e.storeClientOptions();var{filterId:o,filter:s}=yield e.getFilter();if(s){if(e.client.resetNotifTimelineSet(),!e.currentSyncRequest){var a=o,l=yield i;if(l)Ot("Sending first sync request...");else{Ot("Sending initial sync request...");var c=e.buildDefaultFilter();c.setDefinition(s.getDefinition()),c.setTimelineLimit(e.opts.initialSyncLimit),a=JSON.stringify(c.getDefinition())}e.currentSyncRequest=e.doSyncRequest({filter:a},l)}return Ot("Waiting for saved sync before starting sync processing..."),yield e.savedSyncPromise,e.doSync({filter:o})}})()}stop(){var e,t,n;Ot("SyncApi.stop"),(e=globalThis.window)===null||e===void 0||(t=e.removeEventListener)===null||t===void 0||t.call(e,"online",this.onOnline,!1),this.running=!1,(n=this.abortController)===null||n===void 0||n.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=void 0)}retryImmediately(){return this.connectionReturnedDefer?(this.startKeepAlives(0),!0):!1}syncFromCache(e){var t=this;return w(function*(){Ot("sync(): not doing HTTP hit, instead returning stored /sync data");var n=e.nextBatch;t.client.store.setSyncToken(n);var i={nextSyncToken:n,catchingUp:!1,fromCache:!0},o={next_batch:n,rooms:e.roomsData,account_data:{events:e.accountData}};try{yield t.processSyncResponse(i,o)}catch(s){b.error("Error processing cached sync",s)}t.storeIsInvalid||t.updateSyncState(ct.Prepared,i)})()}doSync(e){var t=this;return w(function*(){for(;t.running;){var n=t.client.store.getSyncToken(),i=void 0;try{t.currentSyncRequest||(t.currentSyncRequest=t.doSyncRequest(e,n)),i=yield t.currentSyncRequest}catch(a){var o=yield t.onSyncError(a);if(o)return;continue}finally{t.currentSyncRequest=void 0}t.client.store.setSyncToken(i.next_batch),t.failedSyncCount=0;var s={oldSyncToken:n??void 0,nextSyncToken:i.next_batch,catchingUp:t.catchingUp};t.syncOpts.crypto&&(yield t.syncOpts.crypto.onSyncWillProcess(s));try{yield t.processSyncResponse(s,i)}catch(a){b.error("Caught /sync error",a),t.client.emit(be.SyncUnexpectedError,a)}yield t.client.store.setSyncData(i),s.catchingUp=t.catchingUp,e.hasSyncedBefore||(t.updateSyncState(ct.Prepared,s),e.hasSyncedBefore=!0),t.syncOpts.cryptoCallbacks&&(yield t.syncOpts.cryptoCallbacks.onSyncCompleted(s)),t.updateSyncState(ct.Syncing,s),t.client.store.wantsSave()&&(t.syncOpts.crypto&&(yield t.syncOpts.crypto.saveDeviceList(0)),yield t.client.store.save())}t.running||(Ot("Sync no longer running: exiting."),t.connectionReturnedDefer&&(t.connectionReturnedDefer.reject(),t.connectionReturnedDefer=void 0),t.updateSyncState(ct.Stopped))})()}doSyncRequest(e,t){var n,i=this.getSyncParams(e,t);return this.client.http.authedRequest(Z.Get,"/sync",i,void 0,{localTimeoutMs:i.timeout+KC,abortSignal:(n=this.abortController)===null||n===void 0?void 0:n.signal})}getSyncParams(e,t){var n=this.opts.pollTimeout;(this.getSyncState()!==ct.Syncing||this.catchingUp)&&(this.catchingUp=!0,n=0);var i=e.filter;this.client.isGuest()&&!i&&(i=this.getGuestFilter());var o={filter:i,timeout:n};return this.opts.disablePresence?o.set_presence=hN.Offline:this.presence!==void 0&&(o.set_presence=this.presence),t?o.since=t:o._cacheBuster=Date.now(),[ct.Reconnecting,ct.Error].includes(this.getSyncState())&&(o.timeout=0),o}setPresence(e){this.presence=e}onSyncError(e){var t=this;return w(function*(){if(!t.running)return Ot("Sync no longer running: exiting"),t.connectionReturnedDefer&&(t.connectionReturnedDefer.reject(),t.connectionReturnedDefer=void 0),t.updateSyncState(ct.Stopped),!0;if(b.error("/sync error %s",e),t.shouldAbortSync(e))return!0;t.failedSyncCount++,b.log("Number of consecutive failed sync requests:",t.failedSyncCount),Ot("Starting keep-alive");var n=t.startKeepAlives();t.currentSyncRequest=void 0,t.updateSyncState(t.failedSyncCount>=kz?ct.Error:ct.Reconnecting,{error:e});var i=yield n;return i&&t.getSyncState()===ct.Error&&t.updateSyncState(ct.Catchup,{catchingUp:!0}),!1})()}processSyncResponse(e,t){var n=this;return w(function*(){var i,o,s,a,l=n.client;if(Array.isArray((i=t.presence)===null||i===void 0?void 0:i.events)&&t.presence.events.filter(mi).map(l.getEventMapper()).forEach(function(y){var S=l.store.getUser(y.getSender());S?S.setPresenceEvent(y):(S=ko.createUser(y.getSender(),l),S.setPresenceEvent(y),l.store.storeUser(S)),l.emit(be.Event,y)}),Array.isArray((o=t.account_data)===null||o===void 0?void 0:o.events)){var c=t.account_data.events.filter(mi).map(l.getEventMapper()),u=c.reduce((y,S)=>(y[S.getType()]=l.store.getAccountData(S.getType()),y),{});l.store.storeAccountDataEvents(c),c.forEach(function(y){if(y.getType()===V.PushRules){var S=y.getContent();l.setPushRules(S)}var R=u[y.getType()];return l.emit(be.AccountData,y,R),y})}if(t.to_device&&Array.isArray(t.to_device.events)&&t.to_device.events.length>0){var d=t.to_device.events.filter(mi);n.syncOpts.cryptoCallbacks&&(d=yield n.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(d));var f=[];d.map(l.getEventMapper({toDevice:!0})).map(y=>{if(y.getType()==="m.key.verification.cancel"){var S=y.getContent().transaction_id;S&&f.push(S)}return y}).forEach(function(y){var S=y.getContent();if(y.getType()=="m.room.message"&&S.msgtype=="m.bad.encrypted"){b.log("Ignoring undecryptable to-device event from "+y.getSender());return}if(y.getType()==="m.key.verification.start"||y.getType()==="m.key.verification.request"){var R=S.transaction_id;f.includes(R)&&y.flagCancelled()}l.emit(be.ToDeviceEvent,y)})}else n.catchingUp=!1;var p=[],h=[],m=[],E=[];t.rooms&&(t.rooms.invite&&(p=n.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(h=n.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(m=n.mapSyncResponseToRoomArray(t.rooms.leave)),t.rooms.knock&&(E=n.mapSyncResponseToRoomArray(t.rooms.knock))),n.notifEvents=[],yield Fl(p,function(){var y=w(function*(S){var R,k=S.room,x=n.mapSyncEventsFormat(S.invite_state,k);yield n.injectRoomEvents(k,x);var T=(R=k.currentState.getStateEvents(V.RoomMember,l.getUserId()))===null||R===void 0?void 0:R.getSender(),O=l.crypto;if(O){var C=yield O.cryptoStore.takeParkedSharedHistory(k.roomId);for(var N of C)N.senderId===T&&(yield O.olmDevice.addInboundGroupSession(k.roomId,N.senderKey,N.forwardingCurve25519KeyChain,N.sessionId,N.sessionKey,N.keysClaimed,!0,{sharedHistory:!0,untrusted:!0}))}S.isBrandNewRoom?(k.recalculate(),l.store.storeRoom(k),l.emit(be.Room,k)):k.recalculate(),x.forEach(function(F){l.emit(be.Event,F)})});return function(S){return y.apply(this,arguments)}}()),yield Fl(h,function(){var y=w(function*(S){var R,k=S.room,x=n.mapSyncEventsFormat(S.state,k),T=n.mapSyncEventsFormat(S.timeline,k,!1),O=n.mapSyncEventsFormat(S.ephemeral),C=n.mapSyncEventsFormat(S.account_data),N=n.isRoomEncrypted(k,x,T);if(S.unread_notifications){if(!N||S.unread_notifications.notification_count===0){var F;k.setUnreadNotificationCount(it.Total,(F=S.unread_notifications.notification_count)!==null&&F!==void 0?F:0)}if(!N||k.getUnreadNotificationCount(it.Highlight)<=0){var H;k.setUnreadNotificationCount(it.Highlight,(H=S.unread_notifications.highlight_count)!==null&&H!==void 0?H:0)}}var ie=(R=S[Bd.name])!==null&&R!==void 0?R:S[Bd.altName];if(ie){k.resetThreadUnreadNotificationCountFromSync(Object.keys(ie));for(var[$,X]of Object.entries(ie)){if(!N||X.notification_count===0){var oe;k.setThreadUnreadNotificationCount($,it.Total,(oe=X.notification_count)!==null&&oe!==void 0?oe:0)}var re=k.getThreadUnreadNotificationCount($,it.Highlight)<=0;if(!N||N&&re){var ae;k.setThreadUnreadNotificationCount($,it.Highlight,(ae=X.highlight_count)!==null&&ae!==void 0?ae:0)}}}else k.resetThreadUnreadNotificationCountFromSync();if(S.timeline=S.timeline||{},S.isBrandNewRoom)S.timeline.prev_batch!==null&&k.getLiveTimeline().setPaginationToken(S.timeline.prev_batch,we.BACKWARDS);else if(S.timeline.limited){for(var q=!0,z=T.length-1;z>=0;z--){var Q=T[z].getId();if(k.getTimelineForEvent(Q)){Ot("Already have event ".concat(Q," in limited sync - not resetting")),q=!1,T.splice(0,z);break}}if(q){var Ie;k.resetLiveTimeline(S.timeline.prev_batch,n.syncOpts.canResetEntireTimeline(k.roomId)?null:(Ie=e.oldSyncToken)!==null&&Ie!==void 0?Ie:null),l.resetNotifTimelineSet()}}if(n.syncOpts.cryptoCallbacks)for(var Y of x.concat(T))Y.isState()&&Y.getType()===V.RoomEncryption&&Y.getStateKey()===""&&(yield n.syncOpts.cryptoCallbacks.onCryptoEvent(k,Y));try{yield n.injectRoomEvents(k,x,T,e.fromCache)}catch(B){b.error("Failed to process events on room ".concat(k.roomId,":"),B)}S.summary&&k.setSummary(S.summary),k.addEphemeralEvents(O),k.addAccountData(C),k.recalculate(),S.isBrandNewRoom&&(l.store.storeRoom(k),l.emit(be.Room,k)),n.processEventsForNotifs(k,T);var le=B=>l.emit(be.Event,B);x.forEach(le),T.forEach(le),O.forEach(le),C.forEach(le),k.decryptCriticalEvents()});return function(S){return y.apply(this,arguments)}}()),yield Fl(m,function(){var y=w(function*(S){var R=S.room,k=n.mapSyncEventsFormat(S.state,R),x=n.mapSyncEventsFormat(S.timeline,R),T=n.mapSyncEventsFormat(S.account_data);yield n.injectRoomEvents(R,k,x),R.addAccountData(T),R.recalculate(),S.isBrandNewRoom&&(l.store.storeRoom(R),l.emit(be.Room,R)),n.processEventsForNotifs(R,x),k.forEach(function(O){l.emit(be.Event,O)}),x.forEach(function(O){l.emit(be.Event,O)}),T.forEach(function(O){l.emit(be.Event,O)})});return function(S){return y.apply(this,arguments)}}()),yield Fl(E,function(){var y=w(function*(S){var R=S.room,k=n.mapSyncEventsFormat(S.knock_state,R);yield n.injectRoomEvents(R,k),S.isBrandNewRoom?(R.recalculate(),l.store.storeRoom(R),l.emit(be.Room,R)):R.recalculate(),k.forEach(function(x){l.emit(be.Event,x)})});return function(S){return y.apply(this,arguments)}}()),e.oldSyncToken&&n.notifEvents.length&&(n.notifEvents.sort(function(y,S){return y.getTs()-S.getTs()}),n.notifEvents.forEach(function(y){var S;(S=l.getNotifTimelineSet())===null||S===void 0||S.addLiveEvent(y)})),t.device_lists&&n.syncOpts.cryptoCallbacks&&(yield n.syncOpts.cryptoCallbacks.processDeviceLists(t.device_lists)),yield(s=n.syncOpts.cryptoCallbacks)===null||s===void 0?void 0:s.processKeyCounts(t.device_one_time_keys_count,(a=t.device_unused_fallback_key_types)!==null&&a!==void 0?a:t["org.matrix.msc2732.device_unused_fallback_key_types"])})()}startKeepAlives(e){return e===void 0&&(e=2e3+Math.floor(Math.random()*5e3)),this.keepAliveTimer!==null&&clearTimeout(this.keepAliveTimer),e>0?this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this),e):this.pokeKeepAlive(),this.connectionReturnedDefer||(this.connectionReturnedDefer=Hs()),this.connectionReturnedDefer.promise}pokeKeepAlive(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!this.running){clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject("SyncApi.stop() was called"),this.connectionReturnedDefer=void 0);return}var n=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.resolve(t),this.connectionReturnedDefer=void 0)};this.client.http.request(Z.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15*1e3,abortSignal:(e=this.abortController)===null||e===void 0?void 0:e.signal}).then(()=>{n()},i=>{i.httpStatus==400||i.httpStatus==404?this.keepAliveTimer=setTimeout(n,2e3):(t=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,t),5e3+Math.floor(Math.random()*5e3)),this.updateSyncState(ct.Error,{error:i}))})}mapSyncResponseToRoomArray(e){var t=this.client;return Object.keys(e).filter(n=>!ed(n)).map(n=>{var i=t.store.getRoom(n),o=!1;return i||(i=this.createRoom(n),o=!0),dv(dv({},e[n]),{},{room:i,isBrandNewRoom:o})})}mapSyncEventsFormat(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!Array.isArray(e.events))return[];var i=this.client.getEventMapper({decrypt:n});return e.events.filter(mi).map(function(o){return t&&(o.room_id=t.roomId),i(o)})}resolveInvites(e){if(!(!e||!this.opts.resolveInvitesToProfiles)){var t=this.client;e.getMembersWithMembership(Be.Invite).forEach(function(n){if(!n.requestedProfileInfo){n.requestedProfileInfo=!0;var i=t.getUser(n.userId),o;i?o=Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):o=t.getProfileInfo(n.userId),o.then(function(s){var a=n.events.member;(a==null?void 0:a.getContent().membership)===Be.Invite&&(a.getContent().avatar_url=s.avatar_url,a.getContent().displayname=s.displayname,n.setMembershipEvent(a,e.currentState))},function(s){})}})}}findEncryptionEvent(e){return e==null?void 0:e.find(t=>t.getType()===V.RoomEncryption&&t.getStateKey()==="")}isRoomEncrypted(e,t,n){return e.hasEncryptionStateEvent()||!!this.findEncryptionEvent(t)||!!this.findEncryptionEvent(n)}injectRoomEvents(e,t,n){var i=arguments,o=this;return w(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!1,a=e.getLiveTimeline(),l=a.getEvents().length==0;if(l){for(var c of t)o.client.getPushActionsForEvent(c);a.initialiseState(t,{timelineWasEmpty:l})}o.resolveInvites(e),e.recalculate(),l||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),yield e.addLiveEvents(n||[],{fromCache:s,timelineWasEmpty:l}),o.client.processBeaconEvents(e,n)})()}processEventsForNotifs(e,t){if(this.client.getNotifTimelineSet())for(var n of t){var i,o=this.client.getPushActionsForEvent(n);o!=null&&o.notify&&(i=o.tweaks)!==null&&i!==void 0&&i.highlight&&this.notifEvents.push(n)}}getGuestFilter(){return"{}"}updateSyncState(e,t){var n=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(be.Sync,this.syncState,n,t)}}function mN(r,e,t){var{timelineSupport:n}=r,i=new Tm(e,r,r.getUserId(),{lazyLoadMembers:t.lazyLoadMembers,pendingEventOrdering:t.pendingEventOrdering,timelineSupport:n});return r.reEmitter.reEmit(i,[pe.Name,pe.Redaction,pe.RedactionCancelled,pe.Receipt,pe.Tags,pe.LocalEchoUpdated,pe.AccountData,pe.MyMembership,pe.Timeline,pe.TimelineReset,Me.Events,Me.Members,Me.NewMember,Me.Update,kt.New,kt.Update,kt.Destroy,kt.LivenessChange]),i.on(Me.NewMember,(o,s,a)=>{var l;a.user=(l=r.getUser(a.userId))!==null&&l!==void 0?l:void 0,r.reEmitter.reEmit(a,[Ar.Name,Ar.Typing,Ar.PowerLevel,Ar.Membership])}),i}class xz{constructor(){v(this,"accountData",new Map),v(this,"fromToken",null)}isNewlyCreated(){return Promise.resolve(!0)}getSyncToken(){return this.fromToken}setSyncToken(e){this.fromToken=e}storeRoom(e){}getRoom(e){return null}getRooms(){return[]}removeRoom(e){}getRoomSummaries(){return[]}storeUser(e){}getUser(e){return null}getUsers(){return[]}scrollback(e,t){return[]}setUserCreator(e){}storeEvents(e,t,n,i){}storeFilter(e){}getFilter(e,t){return null}getFilterIdByName(e){return null}setFilterIdByName(e,t){}storeAccountDataEvents(e){}getAccountData(e){}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(){return Promise.resolve()}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return Promise.resolve()}getOutOfBandMembers(){return Promise.resolve(null)}setOutOfBandMembers(e,t){return Promise.resolve()}clearOutOfBandMembers(){return Promise.resolve()}getClientOptions(){return Promise.resolve(void 0)}storeClientOptions(e){return Promise.resolve()}getPendingEvents(e){return w(function*(){return[]})()}setPendingEvents(e,t){return Promise.resolve()}saveToDeviceBatches(e){return w(function*(){return Promise.resolve()})()}getOldestToDeviceBatch(){return Promise.resolve(null)}removeToDeviceBatch(e){return w(function*(){return Promise.resolve()})()}destroy(){return w(function*(){})()}}const kr=[];for(let r=0;r<256;++r)kr.push((r+256).toString(16).slice(1));function Oz(r,e=0){return(kr[r[e+0]]+kr[r[e+1]]+kr[r[e+2]]+kr[r[e+3]]+"-"+kr[r[e+4]]+kr[r[e+5]]+"-"+kr[r[e+6]]+kr[r[e+7]]+"-"+kr[r[e+8]]+kr[r[e+9]]+"-"+kr[r[e+10]]+kr[r[e+11]]+kr[r[e+12]]+kr[r[e+13]]+kr[r[e+14]]+kr[r[e+15]]).toLowerCase()}let oy;const Pz=new Uint8Array(16);function Mz(){if(!oy){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");oy=crypto.getRandomValues.bind(crypto)}return oy(Pz)}const Az=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),$C={randomUUID:Az};function _i(r,e,t){var i;if($C.randomUUID&&!r)return $C.randomUUID();r=r||{};const n=r.random??((i=r.rng)==null?void 0:i.call(r))??Mz();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Oz(n)}var gN={},yN={exports:{}},WC=yN.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var e="candidate:%s %d %s %d %s %d typ %s";return e+=r.raddr!=null?" raddr %s rport %d":"%v%v",e+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(e+=" generation %d"),e+=r["network-id"]!=null?" network-id %d":"%v",e+=r["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(r){var e="ssrc:%d";return r.attribute!=null&&(e+=" %s",r.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(r){return r.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(r){return r.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(r){return"imageattr:%s %s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var e="mediaclk:";return e+=r.id!=null?"id=%s %s":"%v%s",e+=r.mediaClockValue!=null?"=%s":"",e+=r.rateNumerator!=null?" rate=%s":"",e+=r.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(WC).forEach(function(r){var e=WC[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})});var SN=yN.exports;(function(r){var e=function(a){return String(Number(a))===a?Number(a):a},t=function(a,l,c,u){if(u&&!c)l[u]=e(a[1]);else for(var d=0;d<c.length;d+=1)a[d+1]!=null&&(l[c[d]]=e(a[d+1]))},n=function(a,l,c){var u=a.name&&a.names;a.push&&!l[a.push]?l[a.push]=[]:u&&!l[a.name]&&(l[a.name]={});var d=a.push?{}:u?l[a.name]:l;t(c.match(a.reg),d,a.names,a.name),a.push&&l[a.push].push(d)},i=SN,o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(a){var l={},c=[],u=l;return a.split(/(\r\n|\r|\n)/).filter(o).forEach(function(d){var f=d[0],p=d.slice(2);f==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var h=0;h<(i[f]||[]).length;h+=1){var m=i[f][h];if(m.reg.test(p))return n(m,u,p)}}),l.media=c,l};var s=function(a,l){var c=l.split(/=(.+)/,2);return c.length===2?a[c[0]]=e(c[1]):c.length===1&&l.length>1&&(a[c[0]]=void 0),a};r.parseParams=function(a){return a.split(/;\s?/).reduce(s,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(a){return a.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(a){for(var l=[],c=a.split(" ").map(e),u=0;u<c.length;u+=3)l.push({component:c[u],ip:c[u+1],port:c[u+2]});return l},r.parseImageAttributes=function(a){return a.split(" ").map(function(l){return l.substring(1,l.length-1).split(",").reduce(s,{})})},r.parseSimulcastStreamList=function(a){return a.split(";").map(function(l){return l.split(",").map(function(c){var u,d=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),d=!0),{scid:u,paused:d}})})}})(gN);var sy=SN,Dz=/%[sdv%]/g,Nz=function(r){var e=1,t=arguments,n=t.length;return r.replace(Dz,function(i){if(e>=n)return i;var o=t[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},fu=function(r,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,i=[r+"="+n];if(e.names)for(var o=0;o<e.names.length;o+=1){var s=e.names[o];e.name?i.push(t[e.name][s]):i.push(t[e.names[o]])}else i.push(t[e.name]);return Nz.apply(null,i)},Lz=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Uz=["i","c","b","a"],jz=function(r,e){e=e||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var t=e.outerOrder||Lz,n=e.innerOrder||Uz,i=[];return t.forEach(function(o){sy[o].forEach(function(s){s.name in r&&r[s.name]!=null?i.push(fu(o,s,r)):s.push in r&&r[s.push]!=null&&r[s.push].forEach(function(a){i.push(fu(o,s,a))})})}),r.media.forEach(function(o){i.push(fu("m",sy.m[0],o)),n.forEach(function(s){sy[s].forEach(function(a){a.name in o&&o[a.name]!=null?i.push(fu(s,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(l){i.push(fu(s,a,l))})})})}),i.join(`\r
291
- `)+`\r
292
- `},el=gN,Fz=jz,Bz=Fz,bN=el.parse;el.parseParams;el.parseFmtpConfig;el.parsePayloads;el.parseRemoteCandidates;el.parseImageAttributes;el.parseSimulcastStreamList;function Zr(r){if(typeof Buffer=="function")return Buffer.from(r).toString("base64");if(typeof btoa=="function"&&r instanceof Uint8Array)return btoa(r.reduce((e,t)=>e+String.fromCharCode(t),""));throw new Error("No base64 impl found!")}function Rm(r){return Zr(r).replace(/={1,2}$/,"")}function Cm(r){return Rm(r).replace(/\+/g,"-").replace(/\//g,"_")}function Dr(r){if(typeof Buffer=="function")return Buffer.from(r,"base64");if(typeof atob=="function"){var e=function*(){for(var n=atob(r.replace(/-/g,"+").replace(/_/g,"/")),i=0;i<n.length;++i)yield n.charCodeAt(i)};return Uint8Array.from(e())}else throw new Error("No base64 impl found!")}var Kz="abcdefghijklmnopqrstuvwxyz",Vz="ABCDEFGHIJKLMNOPQRSTUVWXYZ",$z="0123456789";function Wz(r){var e=new Uint8Array(r);return globalThis.crypto.getRandomValues(e),Cm(e)}function Ei(r){return qz(r,Vz+Kz+$z)}function qz(r,e){for(var t="",n=0;n<r;++n)t+=e.charAt(Math.floor(Math.random()*e.length));return t}var Jo="org.matrix.msc3077.sdp_stream_metadata",St=function(r){return r.Usermedia="m.usermedia",r.Screenshare="m.screenshare",r}({}),rd=null,Bb=0,Gz=()=>(rd===null&&(rd=new AudioContext),Bb++,rd),Hz=()=>{if(Bb--,Bb===0){var r;(r=rd)===null||r===void 0||r.close(),rd=null}},zz=200,Kb=-60,Yz=8,Li=function(r){return r.NewStream="new_stream",r.MuteStateChanged="mute_state_changed",r.LocalVolumeChanged="local_volume_changed",r.VolumeChanged="volume_changed",r.ConnectedChanged="connected_changed",r.Speaking="speaking",r.Disposed="disposed",r}({});class bo extends Tt{constructor(e){super(),v(this,"stream",void 0),v(this,"sdpMetadataStreamId",void 0),v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"purpose",void 0),v(this,"speakingVolumeSamples",void 0),v(this,"client",void 0),v(this,"call",void 0),v(this,"roomId",void 0),v(this,"audioMuted",void 0),v(this,"videoMuted",void 0),v(this,"localVolume",1),v(this,"measuringVolumeActivity",!1),v(this,"audioContext",void 0),v(this,"analyser",void 0),v(this,"frequencyBinCount",void 0),v(this,"speakingThreshold",Kb),v(this,"speaking",!1),v(this,"volumeLooperTimeout",void 0),v(this,"_disposed",!1),v(this,"_connected",!1),v(this,"onAddTrack",()=>{this.emit(Li.NewStream,this.stream)}),v(this,"onCallState",t=>{t===Fe.Connected?this.connected=!0:t===Fe.Connecting&&(this.connected=!1)}),v(this,"volumeLooper",()=>{if(this.analyser&&this.measuringVolumeActivity){this.analyser.getFloatFrequencyData(this.frequencyBinCount);var t=-1/0;for(var n of this.frequencyBinCount)n>t&&(t=n);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(t),this.emit(Li.VolumeChanged,t);var i=!1;for(var o of this.speakingVolumeSamples)if(o>this.speakingThreshold){i=!0;break}this.speaking!==i&&(this.speaking=i,this.emit(Li.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,zz)}}),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(Yz).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(Ye.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit(Li.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){if(t!==e){var n=this.measuringVolumeActivity;e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?(this.initVolumeMeasuring(),n&&this.measureVolumeActivity(!0)):this.measureVolumeActivity(!1),this.emit(Li.NewStream,this.stream)}}initVolumeMeasuring(){if(this.hasAudioTrack){this.audioContext||(this.audioContext=Gz()),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1;var e=this.audioContext.createMediaStreamSource(this.stream);e.connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount)}}getMember(){var e,t=this.client.getRoom(this.roomId);return(e=t==null?void 0:t.getMember(this.userId))!==null&&e!==void 0?e:null}isLocal(){return this.userId===this.client.getUserId()&&(this.deviceId===void 0||this.deviceId===this.client.getDeviceId())}isAudioMuted(){return this.stream.getAudioTracks().length===0||this.audioMuted}isVideoMuted(){return this.stream.getVideoTracks().length===0||this.videoMuted}isSpeaking(){return this.speaking}setNewStream(e){this.updateStream(this.stream,e)}setAudioVideoMuted(e,t){e!==null&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),t!==null&&(this.videoMuted=t),this.emit(Li.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(Li.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){var e=this.client.getMediaHandler(),t=this.stream.clone();return b.log("CallFeed clone() cloning stream (originalStreamId=".concat(this.stream.id,", newStreamId").concat(t.id,")")),this.purpose===St.Usermedia?e.userMediaStreams.push(t):e.screensharingStreams.push(t),new bo({client:this.client,roomId:this.roomId,userId:this.userId,deviceId:this.deviceId,stream:t,purpose:this.purpose,audioMuted:this.audioMuted,videoMuted:this.videoMuted})}dispose(){var e,t;clearTimeout(this.volumeLooperTimeout),(e=this.stream)===null||e===void 0||e.removeEventListener("addtrack",this.onAddTrack),(t=this.call)===null||t===void 0||t.removeListener(Ye.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,Hz()),this._disposed=!0,this.emit(Li.Disposed)}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit(Li.LocalVolumeChanged,e)}}var To=function(r){return r[r.Blocked=-1]="Blocked",r[r.Unverified=0]="Unverified",r[r.Verified=1]="Verified",r}({});class _N{constructor(e){v(this,"deviceId",void 0),v(this,"userId",void 0),v(this,"algorithms",void 0),v(this,"keys",void 0),v(this,"verified",void 0),v(this,"signatures",void 0),v(this,"displayName",void 0),v(this,"dehydrated",!1),this.deviceId=e.deviceId,this.userId=e.userId,this.algorithms=e.algorithms,this.keys=e.keys,this.verified=e.verified||To.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))}}class rn{static fromStorage(e,t){var n=new rn(t);for(var i in e)e.hasOwnProperty(i)&&(n[i]=e[i]);return n}constructor(e){this.deviceId=e,v(this,"algorithms",[]),v(this,"keys",{}),v(this,"verified",To.Unverified),v(this,"known",!1),v(this,"unsigned",{}),v(this,"signatures",{})}toStorage(){return{algorithms:this.algorithms,keys:this.keys,verified:this.verified,known:this.known,unsigned:this.unsigned,signatures:this.signatures}}getFingerprint(){return this.keys["ed25519:"+this.deviceId]}getIdentityKey(){return this.keys["curve25519:"+this.deviceId]}getDisplayName(){return this.unsigned.device_display_name||null}isBlocked(){return this.verified==To.Blocked}isVerified(){return this.verified==To.Verified}isUnverified(){return this.verified==To.Unverified}isKnown(){return this.known===!0}}v(rn,"DeviceVerification",{VERIFIED:To.Verified,UNVERIFIED:To.Unverified,BLOCKED:To.Blocked});var Jz=3e3,Vb=function(r){return r.Incoming="Call.incoming",r}({});class Xz{constructor(e){v(this,"calls",void 0),v(this,"callEventBuffer",void 0),v(this,"nextSeqByCall",new Map),v(this,"toDeviceEventBuffers",new Map),v(this,"client",void 0),v(this,"candidateEventsByCall",void 0),v(this,"eventBufferPromiseChain",void 0),v(this,"onSync",()=>{var t=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then(()=>this.evaluateEventBuffer(t)):this.eventBufferPromiseChain=this.evaluateEventBuffer(t)}),v(this,"onRoomTimeline",t=>{this.callEventBuffer.push(t)}),v(this,"onToDeviceEvent",t=>{var n=t.getContent();if(!n.call_id){this.callEventBuffer.push(t);return}if(this.nextSeqByCall.has(n.call_id)||this.nextSeqByCall.set(n.call_id,0),n.seq===void 0){this.callEventBuffer.push(t);return}var i=this.nextSeqByCall.get(n.call_id)||0;if(n.seq!==i){this.toDeviceEventBuffers.has(n.call_id)||this.toDeviceEventBuffers.set(n.call_id,[]);var o=this.toDeviceEventBuffers.get(n.call_id),s=o.findIndex(u=>u.getContent().seq>n.seq);s===-1?o.push(t):o.splice(s,0,t)}else{var a=n.call_id;this.callEventBuffer.push(t),this.nextSeqByCall.set(a,n.seq+1);for(var l=this.toDeviceEventBuffers.get(a),c=l&&l.shift();c&&c.getContent().seq===this.nextSeqByCall.get(a);)this.callEventBuffer.push(c),this.nextSeqByCall.set(a,c.getContent().seq+1),c=l.shift()}}),this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(be.Sync,this.onSync),this.client.on(pe.Timeline,this.onRoomTimeline),this.client.on(be.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(be.Sync,this.onSync),this.client.removeListener(pe.Timeline,this.onRoomTimeline),this.client.removeListener(be.ToDeviceEvent,this.onToDeviceEvent)}evaluateEventBuffer(e){var t=this;return w(function*(){yield Promise.all(e.map(u=>t.client.decryptEventIfNeeded(u)));var n=e.filter(u=>{var d=u.getType();return d.startsWith("m.call.")||d.startsWith("org.matrix.call.")}),i=new Set;for(var o of n){var s=o.getType();(s===V.CallAnswer||s===V.CallHangup)&&i.add(o.getContent().call_id)}for(var a of n){var l=a.getType(),c=a.getContent().call_id;if(!(l===V.CallInvite&&i.has(c)))try{yield t.handleCallEvent(a)}catch(u){b.error("CallEventHandler evaluateEventBuffer() caught exception handling call event",u)}}})()}handleCallEvent(e){var t=this;return w(function*(){var n;t.client.emit(be.ReceivedVoipEvent,e);var i=e.getContent(),o=e.getRoomId()||((n=t.client.groupCallEventHandler.getGroupCallById(i.conf_id))===null||n===void 0||(n=n.room)===null||n===void 0?void 0:n.roomId),s=i.conf_id,a=e.getType(),l=e.getSender(),c=i.call_id?t.calls.get(i.call_id):void 0,u,d;if(s){if(d=t.client.groupCallEventHandler.getGroupCallById(s),!d){b.warn("CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=".concat(s,", type=").concat(a,")"));return}if(u=i.device_id,!u){b.warn("CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=".concat(l,")")),d.emit(yt.Error,new TN(l));return}if(i.dest_session_id!==t.client.getSessionId()){b.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring");return}}var f=l===t.client.credentials.userId&&(u===void 0||u===t.client.getDeviceId());if(o){if(a===V.CallInvite){var p,h,m;if(f||e.getLocalAge()>i.lifetime-Jz||c&&c.state===Fe.Ended||(c&&b.warn("CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=".concat(i.call_id,")")),i.invitee&&i.invitee!==t.client.getUserId()))return;var E=((p=t.client.getTurnServersExpiry())!==null&&p!==void 0?p:0)-Date.now();if(b.info("CallEventHandler handleCallEvent() current turn creds expire in "+E+" ms"),c=(h=Kd(t.client,o,{forceTURN:t.client.forceTURN,opponentDeviceId:u,groupCallId:s,opponentSessionId:i.sender_session_id}))!==null&&h!==void 0?h:void 0,!c){b.log("CallEventHandler handleCallEvent() this client does not support WebRTC (callId=".concat(i.call_id,")"));return}c.callId=i.call_id;var y=(m=d)===null||m===void 0?void 0:m.getGroupCallStats();y&&c.initStats(y);try{yield c.initWithInvite(e)}catch(N){if(N instanceof mo)if(N.code===id.UnknownDevice){var S;(S=d)===null||S===void 0||S.emit(yt.Error,N)}else b.error(N)}if(t.calls.set(c.callId,c),t.candidateEventsByCall.get(c.callId))for(var R of t.candidateEventsByCall.get(c.callId))c.onRemoteIceCandidatesReceived(R);var k;for(var x of t.calls.values()){var T,O=[Fe.WaitLocalMedia,Fe.CreateOffer,Fe.InviteSent].includes(x.state);if(c.roomId===x.roomId&&x.direction===ts.Outbound&&((T=c.getOpponentMember())===null||T===void 0?void 0:T.userId)===x.invitee&&O){k=x;break}}k?k.callId>c.callId?(b.log("CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=".concat(c.callId,", outgoingId=").concat(k.callId,")")),k.replacedBy(c)):(b.log("CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=".concat(c.callId,", outgoingId=").concat(k.callId,")")),c.hangup(qe.Replaced,!0)):t.client.emit(Vb.Incoming,c);return}else if(a===V.CallCandidates){if(f)return;c?c.onRemoteIceCandidatesReceived(e):(t.candidateEventsByCall.has(i.call_id)||t.candidateEventsByCall.set(i.call_id,[]),t.candidateEventsByCall.get(i.call_id).push(e));return}else if([V.CallHangup,V.CallReject].includes(a)){if(c)c.state!==Fe.Ended&&(a===V.CallHangup?c.onHangupReceived(i):c.onRejectReceived(i),c.state===Fe.Ended&&t.calls.delete(i.call_id));else{var C;c=(C=Kd(t.client,o,{opponentDeviceId:u,opponentSessionId:i.sender_session_id}))!==null&&C!==void 0?C:void 0,c&&(c.callId=i.call_id,c.initWithHangup(e),t.calls.set(i.call_id,c))}return}if(!c||!c.hasPeerConnection){b.info("CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=".concat(a,")"));return}if(e.getContent().party_id!==c.ourPartyId)switch(a){case V.CallAnswer:f?c.state===Fe.Ringing&&c.onAnsweredElsewhere(i):c.onAnswerReceived(e);break;case V.CallSelectAnswer:c.onSelectAnswerReceived(e);break;case V.CallNegotiate:c.onNegotiateReceived(e);break;case V.CallAssertedIdentity:case V.CallAssertedIdentityPrefix:c.onAssertedIdentityReceived(e);break;case V.CallSDPStreamMetadataChanged:case V.CallSDPStreamMetadataChangedPrefix:c.onSDPStreamMetadataChangedReceived(e);break}}})()}}var $b=function(r){return r.Incoming="GroupCall.incoming",r.Outgoing="GroupCall.outgoing",r.Ended="GroupCall.ended",r.Participants="GroupCall.participants",r}({});class Qz{constructor(e){this.client=e,v(this,"groupCalls",new Map),v(this,"roomDeferreds",new Map),v(this,"onRoomsChanged",t=>{this.createGroupCallForRoom(t)}),v(this,"onRoomStateChanged",(t,n)=>{var i=t.getType();if(i===V.GroupCallPrefix){var o=t.getStateKey(),s=t.getContent(),a=this.groupCalls.get(n.roomId);!a&&!s["m.terminated"]&&!t.isRedacted()?this.createGroupCallFromRoomStateEvent(t):a&&a.groupCallId===o?s["m.terminated"]||t.isRedacted()?a.terminate(!1):s["m.type"]!==a.type&&b.warn("GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=".concat(n.roomId,")")):a&&a.groupCallId!==o&&b.warn("GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=".concat(n.roomId,")"))}})}start(){var e=this;return w(function*(){e.client.getSyncState()!==ct.Syncing&&(b.debug("GroupCallEventHandler start() waiting for client to start syncing"),yield new Promise(i=>{var o=()=>{if(e.client.getSyncState()===ct.Syncing)return e.client.off(be.Sync,o),i()};e.client.on(be.Sync,o)}));var t=e.client.getRooms();for(var n of t)e.createGroupCallForRoom(n);e.client.on(be.Room,e.onRoomsChanged),e.client.on(Me.Events,e.onRoomStateChanged)})()}stop(){this.client.removeListener(be.Room,this.onRoomsChanged),this.client.removeListener(Me.Events,this.onRoomStateChanged)}getRoomDeferred(e){var t=this.roomDeferreds.get(e);if(t===void 0){var n;t={prom:new Promise(i=>{n=i})},t.resolve=n,this.roomDeferreds.set(e,t)}return t}waitUntilRoomReadyForGroupCalls(e){return this.getRoomDeferred(e).prom}getGroupCallById(e){return[...this.groupCalls.values()].find(t=>t.groupCallId===e)}createGroupCallForRoom(e){var t=e.currentState.getStateEvents(V.GroupCallPrefix),n=t.sort((s,a)=>a.getTs()-s.getTs());for(var i of n){var o=i.getContent();if(!(o["m.terminated"]||i.isRedacted())){b.debug("GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=".concat(i.getStateKey(),", ts=").concat(i.getTs(),", roomId=").concat(e.roomId,", numOfPossibleCalls=").concat(t.length,")")),this.createGroupCallFromRoomStateEvent(i);break}}this.getRoomDeferred(e.roomId).resolve()}createGroupCallFromRoomStateEvent(e){var t=e.getRoomId(),n=e.getContent(),i=this.client.getRoom(t);if(!i){b.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=".concat(t,")"));return}var o=e.getStateKey(),s=n["m.type"];if(!Object.values(km).includes(s)){b.warn("GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=".concat(s,", roomId=").concat(t,")"));return}var a=n["m.intent"];if(!Object.values(wN).includes(a)){b.warn("Received invalid group call intent (type=".concat(s,", roomId=").concat(t,")"));return}var l=!!n["io.element.ptt"],c;if(n!=null&&n.dataChannelsEnabled&&n!==null&&n!==void 0&&n.dataChannelOptions){var{ordered:u,maxPacketLifeTime:d,maxRetransmits:f,protocol:p}=n.dataChannelOptions;c={ordered:u,maxPacketLifeTime:d,maxRetransmits:f,protocol:p}}var h=new Lw(this.client,i,s,l,a,o,(n==null?void 0:n.dataChannelsEnabled)||this.client.isVoipWithNoMediaAllowed,c,this.client.isVoipWithNoMediaAllowed,this.client.useLivekitForGroupCalls,n["io.element.livekit_service_url"]);return this.groupCalls.set(i.roomId,h),this.client.emit($b.Incoming,h),h}}class Zz{constructor(){v(this,"bandwidth",{}),v(this,"bitrate",{}),v(this,"packetLoss",{}),v(this,"transport",[])}}class e8{static buildBandwidthReport(e){var t=e.availableIncomingBitrate,n=e.availableOutgoingBitrate;return{download:t?Math.round(t/1e3):0,upload:n?Math.round(n/1e3):0}}}class t8{static buildReport(e,t,n,i){var o=e==null?void 0:e.get(t.localCandidateId),s=e==null?void 0:e.get(t.remoteCandidateId);if(s&&o){var a=s.ip!==void 0?s.ip:s.address,l=s.port,c="".concat(a,":").concat(l),u=o.ip!==void 0?o.ip:o.address,d=o.port,f="".concat(u,":").concat(d),p=s.protocol;n.some(h=>h.ip===c&&h.type===p&&h.localIp===f)||n.push({ip:c,type:p,localIp:f,isFocus:i,localCandidateType:o.candidateType,remoteCandidateType:s.candidateType,networkType:o.networkType,rtt:t.currentRoundTripTime?t.currentRoundTripTime*1e3:NaN})}return n}}class r8{constructor(){v(this,"ssrcToMid",{local:new Map,remote:new Map})}findMidBySsrc(e,t){var n;return this.ssrcToMid[t].forEach((i,o)=>{if(i.find(s=>s==e)){n=o;return}}),n}parse(e,t){var n=bN(e),i=new Map;n.media.forEach(o=>{if(o.mid&&o.type==="video"||o.type==="audio"){var s,a=[];(s=o.ssrcs)===null||s===void 0||s.forEach(l=>{l.attribute==="cname"&&a.push("".concat(l.id))}),i.set("".concat(o.mid),a)}}),this.ssrcToMid[t]=i}getSsrcToMidMap(e){return this.ssrcToMid[e]}}class n8{constructor(e){this.pc=e}getLocalTracks(e){var t=n=>n!==null&&n.kind===e;return this.pc.getTransceivers().filter(n=>n.currentDirection==="sendonly"||n.currentDirection==="sendrecv").filter(n=>n.sender!==null).map(n=>n.sender).map(n=>n.track).filter(t)}getTackById(e){return this.pc.getTransceivers().map(t=>{if((t==null?void 0:t.sender.track)!==null&&t.sender.track.id===e)return t.sender.track;if((t==null?void 0:t.receiver.track)!==null&&t.receiver.track.id===e)return t.receiver.track}).find(t=>t!==void 0)}getLocalTrackIdByMid(e){var t=this.pc.getTransceivers().find(n=>n.mid===e);if(t!==void 0&&t.sender&&t.sender.track)return t.sender.track.id}getRemoteTrackIdByMid(e){var t=this.pc.getTransceivers().find(n=>n.mid===e);if(t!==void 0&&t.receiver&&t.receiver.track)return t.receiver.track.id}getActiveSimulcastStreams(){return 3}getTransceiverByTrackId(e){return this.pc.getTransceivers().find(t=>t.receiver.track.id===e||t.sender.track!==null&&t.sender.track.id===e)}}class i8{constructor(e,t,n){this.trackId=e,this.type=t,this.kind=n,v(this,"loss",{packetsTotal:0,packetsLost:0,isDownloadStream:!1}),v(this,"bitrate",{download:0,upload:0}),v(this,"resolution",{width:-1,height:-1}),v(this,"audioConcealment",{concealedAudio:0,totalAudioDuration:0}),v(this,"framerate",0),v(this,"jitter",0),v(this,"codec",""),v(this,"isAlive",!0),v(this,"isMuted",!1),v(this,"isEnabled",!0)}getType(){return this.type}setLoss(e){this.loss=e}getLoss(){return this.loss}setResolution(e){this.resolution=e}getResolution(){return this.resolution}setFramerate(e){this.framerate=e}getFramerate(){return this.framerate}setBitrate(e){this.bitrate=e}getBitrate(){return this.bitrate}setCodec(e){return this.codec=e,!0}getCodec(){return this.codec}resetBitrate(){this.bitrate={download:0,upload:0}}set alive(e){this.isAlive=e}get alive(){return this.isAlive}set muted(e){this.isMuted=e}get muted(){return this.isMuted}set enabled(e){this.isEnabled=e}get enabled(){return this.isEnabled}setJitter(e){this.jitter=e}getJitter(){return this.jitter}setAudioConcealment(e,t){this.audioConcealment.concealedAudio=e,this.audioConcealment.totalAudioDuration=t}getAudioConcealment(){return this.audioConcealment}}class o8{constructor(e,t){this.mediaSsrcHandler=e,this.mediaTrackHandler=t,v(this,"track2stats",new Map)}findTrack2Stats(e,t){var n;if(e.trackIdentifier)n=e.trackIdentifier;else if(e.mid)n=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid);else if(e.ssrc){var i=this.mediaSsrcHandler.findMidBySsrc(e.ssrc,t);if(!i)return;n=t==="remote"?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid)}if(n){var o=this.track2stats.get(n);if(!o){var s=this.mediaTrackHandler.getTackById(n);if(s!==void 0){var a=s.kind==="audio"?s.kind:"video";o=new i8(n,t,a),this.track2stats.set(n,o)}else return}return o}}findLocalVideoTrackStats(e){var t=this.mediaTrackHandler.getLocalTracks("video");if(t.length!==0)return this.findTrack2Stats(e,"local")}getTrack2stats(){return this.track2stats}findTransceiverByTrackId(e){return this.mediaTrackHandler.getTransceiverByTrackId(e)}}class fa{static getNonNegativeValue(e){var t=e;return typeof t!="number"&&(t=Number(t)),isNaN(t)?0:Math.max(0,t)}}class Mn{static buildFramerateResolution(e,t){var n={height:t.frameHeight,width:t.frameWidth},i=t.framesPerSecond;n.height&&n.width&&e.setResolution(n),e.setFramerate(Math.round(i||0))}static calculateSimulcastFramerate(e,t,n,i){var o=e.getFramerate();if(!o){if(n){var s=t.timestamp-n.timestamp;if(s>0&&t.framesSent){var a=t.framesSent-n.framesSent;o=a/s*1e3}}if(!o)return}o=i?Math.round(o/i):0,e.setFramerate(o)}static buildCodec(e,t,n){var i=e==null?void 0:e.get(n.codecId);if(i){var o=i.mimeType.split("/")[1];o&&t.setCodec(o)}}static buildBitrateReceived(e,t,n){e.setBitrate({download:Mn.calculateBitrate(t.bytesReceived,n.bytesReceived,t.timestamp,n.timestamp),upload:0})}static buildBitrateSend(e,t,n){e.setBitrate({download:0,upload:this.calculateBitrate(t.bytesSent,n.bytesSent,t.timestamp,n.timestamp)})}static buildPacketsLost(e,t,n){var i=t.type==="outbound-rtp"?"packetsSent":"packetsReceived",o=t[i];(!o||o<0)&&(o=0);var s=fa.getNonNegativeValue(n[i]),a=Math.max(0,o-s),l=fa.getNonNegativeValue(t.packetsLost),c=fa.getNonNegativeValue(n.packetsLost),u=Math.max(0,l-c);e.setLoss({packetsTotal:a+u,packetsLost:u,isDownloadStream:t.type!=="outbound-rtp"})}static calculateBitrate(e,t,n,i){var o=fa.getNonNegativeValue(e),s=fa.getNonNegativeValue(t),a=Math.max(0,o-s),l=n-i,c=0;return l>0&&(c=Math.round(a*8/l)),c}static setTrackStatsState(e,t){var n;if(t===void 0){e.alive=!1;return}var i=e.getType()==="remote"?t.receiver.track:t==null||(n=t.sender)===null||n===void 0?void 0:n.track;if(i==null){e.alive=!1;return}if(i.readyState==="ended"){e.alive=!1;return}e.muted=i.muted,e.enabled=i.enabled,e.alive=!0}static buildTrackSummary(e){var t={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},n={count:0,muted:0,maxJitter:0,maxPacketLoss:0,concealedAudio:0,totalAudio:0},i=e.filter(s=>s.getType()==="remote"),o=i.filter(s=>s.kind==="audio");return i.forEach(s=>{var a=s.kind==="video"?t:n;if(a.count++,s.alive&&s.muted&&a.muted++,a.maxJitter<s.getJitter()&&(a.maxJitter=s.getJitter()),a.maxPacketLoss<s.getLoss().packetsLost&&(a.maxPacketLoss=s.getLoss().packetsLost),o.length>0){var l,c;a.concealedAudio+=(l=s.getAudioConcealment())===null||l===void 0?void 0:l.concealedAudio,a.totalAudio+=(c=s.getAudioConcealment())===null||c===void 0?void 0:c.totalAudioDuration}}),{audioTrackSummary:n,videoTrackSummary:t}}static buildJitter(e,t){if(t.type==="inbound-rtp"){var n=t==null?void 0:t.jitter;if(n!==void 0){var i=fa.getNonNegativeValue(n);e.setJitter(Math.round(i*1e3))}else e.setJitter(-1)}}static buildAudioConcealment(e,t){if(t.type==="inbound-rtp"){var n=1e3*(t==null?void 0:t.totalSamplesDuration)/(t==null?void 0:t.totalSamplesReceived),i=n*(t==null?void 0:t.concealedSamples),o=1e3*(t==null?void 0:t.totalSamplesDuration);e.setAudioConcealment(i,o)}}}class nd{static build(e){var t={},n={download:0,upload:0},i={download:0,upload:0},o=0,s=0,a={local:new Map,remote:new Map},l={local:new Map,remote:new Map},c={local:new Map,remote:new Map},u=new Map,d=new Map,f=0,p=0,h=0,m=0,E=0,y=0;for(var[S,R]of e){var k=R.getLoss(),x=k.isDownloadStream?"download":"upload";if(n[x]+=k.packetsTotal,i[x]+=k.packetsLost,o+=R.getBitrate().download,s+=R.getBitrate().upload,R.kind==="audio"){var T=R.getAudioConcealment();E+=T.concealedAudio,y+=T.totalAudioDuration,f+=R.getBitrate().download,p+=R.getBitrate().upload}else h+=R.getBitrate().download,m+=R.getBitrate().upload;a[R.getType()].set(S,R.getResolution()),l[R.getType()].set(S,R.getFramerate()),c[R.getType()].set(S,R.getCodec()),R.getType()==="remote"&&(u.set(S,R.getJitter()),R.kind==="audio"&&d.set(S,R.getAudioConcealment())),R.resetBitrate()}return t.bitrate={upload:s,download:o},t.bitrate.audio={upload:p,download:f},t.bitrate.video={upload:m,download:h},t.packetLoss={total:nd.calculatePacketLoss(i.download+i.upload,n.download+n.upload),download:nd.calculatePacketLoss(i.download,n.download),upload:nd.calculatePacketLoss(i.upload,n.upload)},t.audioConcealment=d,t.totalAudioConcealment={concealedAudio:E,totalAudioDuration:y},t.framerate=l,t.resolution=a,t.codec=c,t.jitter=u,t}static calculatePacketLoss(e,t){return!t||t<=0||!e||e<=0?0:Math.round(e/t*100)}}class gs{static buildCallFeedReport(e,t,n){var i=n.getTransceivers(),o=[],s=[];return i.forEach(a=>{var l,c=(l=a.sender)!==null&&l!==void 0&&l.track?gs.buildTrackStats(a.sender.track,"sender"):null,u=gs.buildTrackStats(a.receiver.track,"receiver");o.push({mid:a.mid==null?"null":a.mid,direction:a.direction,currentDirection:a.currentDirection==null?"null":a.currentDirection,sender:c,receiver:u})}),{callId:e,opponentMemberId:t,transceiver:o,callFeeds:s}}static buildTrackStats(e){var t,n,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"--",o=(t=e.getSettings())===null||t===void 0?void 0:t.deviceId,s=(n=e.getConstraints())===null||n===void 0?void 0:n.deviceId;return{id:e.id,kind:e.kind,settingDeviceId:o||"unknown",constrainDeviceId:s||"unknown",muted:e.muted,enabled:e.enabled,readyState:e.readyState,label:i}}static expandCallFeedReport(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unknown";return e.callFeeds||(e.callFeeds=[]),t.forEach(i=>{var o=i.stream.getAudioTracks(),s=i.stream.getVideoTracks(),a=o.length>0?gs.buildTrackStats(i.stream.getAudioTracks()[0],i.purpose):null,l=s.length>0?gs.buildTrackStats(i.stream.getVideoTracks()[0],i.purpose):null,c={stream:i.stream.id,type:i.isLocal()?"local":"remote",audio:a,video:l,purpose:i.purpose,prefix:n,isVideoMuted:i.isVideoMuted(),isAudioMuted:i.isAudioMuted()};e.callFeeds.push(c)}),e}}function qC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function vh(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?qC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):qC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class s8{constructor(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;this.callId=e,this.opponentMemberId=t,this.pc=n,this.emitter=i,this.isFocus=o,v(this,"isActive",!0),v(this,"previousStatsReport",void 0),v(this,"currentStatsReport",void 0),v(this,"connectionStats",new Zz),v(this,"trackStats",void 0),n.addEventListener("signalingstatechange",this.onSignalStateChange.bind(this)),this.trackStats=new o8(new r8,new n8(n))}processStats(e,t){var n=this;return w(function*(){var i={isFirstCollection:n.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(n.isActive){var o=n.pc.getStats();if(typeof(o==null?void 0:o.then)=="function")return o.then(s=>{var a,l;n.currentStatsReport=typeof(s==null?void 0:s.result)=="function"?s.result():s;try{n.processStatsReport(e,t)}catch(u){return n.handleError(u),i}n.previousStatsReport=n.currentStatsReport,i.receivedMedia=n.connectionStats.bitrate.download,i.receivedAudioMedia=((a=n.connectionStats.bitrate.audio)===null||a===void 0?void 0:a.download)||0,i.receivedVideoMedia=((l=n.connectionStats.bitrate.video)===null||l===void 0?void 0:l.download)||0;var c=Mn.buildTrackSummary(Array.from(n.trackStats.getTrack2stats().values()));return vh(vh({},i),{},{audioTrackSummary:c.audioTrackSummary,videoTrackSummary:c.videoTrackSummary})}).catch(s=>(n.handleError(s),i));n.isActive=!1}return Promise.resolve(i)})()}processStatsReport(e,t){var n,i=new Map;i.callId=this.callId,i.opponentMemberId=this.opponentMemberId,(n=this.currentStatsReport)===null||n===void 0||n.forEach(o=>{var s=this.previousStatsReport?this.previousStatsReport.get(o.id):null;if(o.type==="candidate-pair"&&o.nominated&&o.state==="succeeded")this.connectionStats.bandwidth=e8.buildBandwidthReport(o),this.connectionStats.transport=t8.buildReport(this.currentStatsReport,o,this.connectionStats.transport,this.isFocus);else if(o.type==="inbound-rtp"||o.type==="outbound-rtp"){var a=this.trackStats.findTrack2Stats(o,o.type==="inbound-rtp"?"remote":"local");if(!a)return;if(s&&Mn.buildPacketsLost(a,o,s),o.type==="inbound-rtp"){Mn.buildFramerateResolution(a,o),s&&Mn.buildBitrateReceived(a,o,s);var l=this.trackStats.findTransceiverByTrackId(a.trackId);Mn.setTrackStatsState(a,l),Mn.buildJitter(a,o),Mn.buildAudioConcealment(a,o)}else s&&(i.set(a.trackId,fa.getNonNegativeValue(o.bytesSent)),Mn.buildBitrateSend(a,o,s));Mn.buildCodec(this.currentStatsReport,a,o)}else if(o.type==="track"&&o.kind==="video"&&!o.remoteSource){var c=this.trackStats.findLocalVideoTrackStats(o);if(!c)return;Mn.buildFramerateResolution(c,o),Mn.calculateSimulcastFramerate(c,o,s,this.trackStats.mediaTrackHandler.getActiveSimulcastStreams())}}),this.emitter.emitByteSendReport(i),this.emitter.emitCallFeedReport(gs.buildCallFeedReport(this.callId,this.opponentMemberId,this.pc)),this.processAndEmitConnectionStatsReport()}setActive(e){this.isActive=e}getActive(){return this.isActive}handleError(e){this.isActive=!1,b.warn("CallStatsReportGatherer ".concat(this.callId," processStatsReport fails and set to inactive ").concat(e))}processAndEmitConnectionStatsReport(){var e=nd.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(vh(vh({},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 Ro=function(r){return r.CONNECTION_STATS="StatsReport.connection_stats",r.CALL_FEED_REPORT="StatsReport.call_feed_report",r.BYTE_SENT_STATS="StatsReport.byte_sent_stats",r.SUMMARY_STATS="StatsReport.summary_stats",r}({});class a8 extends Tt{emitByteSendReport(e){this.emit(Ro.BYTE_SENT_STATS,e)}emitConnectionStatsReport(e){this.emit(Ro.CONNECTION_STATS,e)}emitCallFeedReport(e){this.emit(Ro.CALL_FEED_REPORT,e)}emitSummaryStatsReport(e){this.emit(Ro.SUMMARY_STATS,e)}}class EN{constructor(e){this.emitter=e}build(e){var t=e.filter(u=>!u.isFirstCollection),n=t.length,i=e.length;if(n!==0){var o={receivedAudio:0,receivedVideo:0,receivedMedia:0,concealedAudio:0,totalAudio:0},s=0,a=0;t.forEach(u=>{this.countTrackListReceivedMedia(o,u),this.countConcealedAudio(o,u),s=this.buildMaxJitter(s,u),a=this.buildMaxPacketLoss(a,u)});var l=5,c={percentageReceivedMedia:Number((o.receivedMedia/n).toFixed(l)),percentageReceivedVideoMedia:Number((o.receivedVideo/n).toFixed(l)),percentageReceivedAudioMedia:Number((o.receivedAudio/n).toFixed(l)),maxJitter:s,maxPacketLoss:a,percentageConcealedAudio:Number(o.totalAudio>0?(o.concealedAudio/o.totalAudio).toFixed(l):0),peerConnections:i};this.emitter.emitSummaryStatsReport(c)}}static extendSummaryReport(e,t){var n=[],i=[];for(var o of t){i.push(o);for(var s of o[1])n.push(s)}e.opponentDevicesInCall=Math.max(0,n.length-1),e.opponentUsersInCall=Math.max(0,i.length-1),e.diffDevicesToPeerConnections=Math.max(0,n.length-1)-e.peerConnections,e.ratioPeerConnectionToDevices=Math.max(0,n.length-1)==0?0:e.peerConnections/(n.length-1)}countTrackListReceivedMedia(e,t){var n=!1,i=!1;(t.receivedAudioMedia>0||t.audioTrackSummary.count===0)&&(e.receivedAudio++,n=!0),(t.receivedVideoMedia>0||t.videoTrackSummary.count===0||t.videoTrackSummary.muted>0&&t.videoTrackSummary.muted===t.videoTrackSummary.count)&&(e.receivedVideo++,i=!0),i&&n&&e.receivedMedia++}buildMaxJitter(e,t){return e<t.videoTrackSummary.maxJitter&&(e=t.videoTrackSummary.maxJitter),e<t.audioTrackSummary.maxJitter&&(e=t.audioTrackSummary.maxJitter),e}buildMaxPacketLoss(e,t){return e<t.videoTrackSummary.maxPacketLoss&&(e=t.videoTrackSummary.maxPacketLoss),e<t.audioTrackSummary.maxPacketLoss&&(e=t.audioTrackSummary.maxPacketLoss),e}countConcealedAudio(e,t){e.concealedAudio+=t.audioTrackSummary.concealedAudio,e.totalAudio+=t.audioTrackSummary.totalAudio}}class l8{constructor(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1e4;this.groupCallId=e,this.userId=t,this.interval=n,v(this,"timer",void 0),v(this,"gatherers",new Map),v(this,"reports",new a8),v(this,"summaryStatsReportGatherer",new EN(this.reports))}start(){this.timer===void 0&&this.interval>0&&(this.timer=setInterval(()=>{this.processStats()},this.interval))}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.gatherers.forEach(e=>e.stopProcessingStats()))}hasStatsReportGatherer(e){return this.gatherers.has(e)}addStatsReportGatherer(e,t,n){return this.hasStatsReportGatherer(e)?!1:(this.gatherers.set(e,new s8(e,t,n,this.reports)),!0)}removeStatsReportGatherer(e){return this.gatherers.delete(e)}getStatsReportGatherer(e){return this.hasStatsReportGatherer(e)?this.gatherers.get(e):void 0}updateOpponentMember(e,t){var n;(n=this.getStatsReportGatherer(e))===null||n===void 0||n.setOpponentMemberId(t)}processStats(){var e=[];this.gatherers.forEach(t=>{e.push(t.processStats(this.groupCallId,this.userId))}),Promise.all(e).then(t=>this.summaryStatsReportGatherer.build(t)).catch(t=>{b.error("Could not build summary stats report",t)})}setInterval(e){this.interval=e}}function GC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function mh(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?GC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):GC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var wN=function(r){return r.Ring="m.ring",r.Prompt="m.prompt",r.Room="m.room",r}({}),km=function(r){return r.Video="m.video",r.Voice="m.voice",r}({}),c8=function(r){return r.CallEnded="call_ended",r}({}),yt=function(r){return r.GroupCallStateChanged="group_call_state_changed",r.ActiveSpeakerChanged="active_speaker_changed",r.CallsChanged="calls_changed",r.UserMediaFeedsChanged="user_media_feeds_changed",r.ScreenshareFeedsChanged="screenshare_feeds_changed",r.LocalScreenshareStateChanged="local_screenshare_state_changed",r.LocalMuteStateChanged="local_mute_state_changed",r.ParticipantsChanged="participants_changed",r.Error="group_call_error",r}({}),Du=function(r){return r.ConnectionStats="GroupCall.connection_stats",r.ByteSentStats="GroupCall.byte_sent_stats",r.SummaryStats="GroupCall.summary_stats",r.CallFeedStats="GroupCall.call_feed_stats",r}({}),id=function(r){return r.NoUserMedia="no_user_media",r.UnknownDevice="unknown_device",r.PlaceCallFailed="place_call_failed",r}({});class Wb extends Error{constructor(e,t,n){n?(super(t+": "+n),v(this,"code",void 0)):(super(t),v(this,"code",void 0)),this.code=e}}class TN extends Wb{constructor(e){super(id.UnknownDevice,"No device found for "+e),this.userId=e}}var Dt=function(r){return r.LocalCallFeedUninitialized="local_call_feed_uninitialized",r.InitializingLocalCallFeed="initializing_local_call_feed",r.LocalCallFeedInitialized="local_call_feed_initialized",r.Entered="entered",r.Ended="ended",r}({}),HC=1e3*60*60;function gh(r){var e;return((e=r.getOpponentMember())===null||e===void 0?void 0:e.userId)||r.invitee||null}class Lw extends Tt{constructor(e,t,n,i,o,s,a,l,c){var u,d,f=arguments.length>9&&arguments[9]!==void 0?arguments[9]:!1,p=arguments.length>10?arguments[10]:void 0;super(),this.client=e,this.room=t,this.type=n,this.isPtt=i,this.intent=o,this.dataChannelsEnabled=a,this.dataChannelOptions=l,this.useLivekit=f,v(this,"activeSpeakerInterval",1e3),v(this,"retryCallInterval",5e3),v(this,"participantTimeout",1e3*15),v(this,"pttMaxTransmitTime",1e3*20),v(this,"activeSpeaker",void 0),v(this,"localCallFeed",void 0),v(this,"localScreenshareFeed",void 0),v(this,"localDesktopCapturerSourceId",void 0),v(this,"userMediaFeeds",[]),v(this,"screenshareFeeds",[]),v(this,"groupCallId",void 0),v(this,"allowCallWithoutVideoAndAudio",void 0),v(this,"calls",new Map),v(this,"callHandlers",new Map),v(this,"activeSpeakerLoopInterval",void 0),v(this,"retryCallLoopInterval",void 0),v(this,"retryCallCounts",new Map),v(this,"reEmitter",void 0),v(this,"transmitTimer",null),v(this,"participantsExpirationTimer",null),v(this,"resendMemberStateTimer",null),v(this,"initWithAudioMuted",!1),v(this,"initWithVideoMuted",!1),v(this,"initCallFeedPromise",void 0),v(this,"_livekitServiceURL",void 0),v(this,"stats",void 0),v(this,"statsCollectIntervalTime",0),v(this,"onConnectionStats",h=>{this.emit(Du.ConnectionStats,{report:h})}),v(this,"onByteSentStats",h=>{this.emit(Du.ByteSentStats,{report:h})}),v(this,"onSummaryStats",h=>{EN.extendSummaryReport(h,this.participants),this.emit(Du.SummaryStats,{report:h})}),v(this,"onCallFeedReport",h=>{this.localCallFeed&&(h=gs.expandCallFeedReport(h,[this.localCallFeed],"from-local-feed"));var m=[];this.forEachCall(E=>{E.callId===h.callId&&E.getFeeds().forEach(y=>m.push(y))}),h=gs.expandCallFeedReport(h,m,"from-call-feed"),this.emit(Du.CallFeedStats,{report:h})}),v(this,"_state",Dt.LocalCallFeedUninitialized),v(this,"_participants",new Map),v(this,"_creationTs",null),v(this,"_enteredViaAnotherSession",!1),v(this,"onIncomingCall",h=>{var m,E;if(h.roomId===this.room.roomId){if(h.state!==Fe.Ringing){b.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call no longer in ringing state - ignoring"));return}if(!h.groupCallId||h.groupCallId!==this.groupCallId){b.log("GroupCall ".concat(this.groupCallId," onIncomingCall() ignored because it doesn't match the current group call")),h.reject();return}var y=(m=h.getOpponentMember())===null||m===void 0?void 0:m.userId;if(y===void 0){b.warn("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call with no member - ignoring"));return}if(this.useLivekit){b.info("Received incoming call whilst in signaling-only mode! Ignoring.");return}var S=(E=this.calls.get(y))!==null&&E!==void 0?E:new Map,R=S.get(h.getOpponentDeviceId());if((R==null?void 0:R.callId)!==h.callId){b.log("GroupCall ".concat(this.groupCallId," onIncomingCall() incoming call (userId=").concat(y,", callId=").concat(h.callId,")")),R&&R.hangup(qe.Replaced,!1),S.set(h.getOpponentDeviceId(),h),this.calls.set(y,S),this.initCall(h);var k=this.getLocalFeeds().map(T=>T.clone());if(!this.callExpected(h))for(var x of k)tr(x.stream.getAudioTracks(),!1),tr(x.stream.getVideoTracks(),!1);h.answerWithCallFeeds(k),this.emit(yt.CallsChanged,this.calls)}}}),v(this,"onRetryCallLoop",()=>{var h=!1;for(var[{userId:m},E]of this.participants){var y=this.calls.get(m),S=this.retryCallCounts.get(m);for(var[R,k]of E){var x,T,O=y==null?void 0:y.get(R),C=(x=(T=S)===null||T===void 0?void 0:T.get(R))!==null&&x!==void 0?x:0;(O==null?void 0:O.getOpponentSessionId())!==k.sessionId&&this.wantsOutgoingCall(m,R)&&C<3&&(S===void 0&&(S=new Map,this.retryCallCounts.set(m,S)),S.set(R,C+1),h=!0)}}h&&this.placeOutgoingCalls()}),v(this,"onCallFeedsChanged",h=>{var m=gh(h),E=h.getOpponentDeviceId();if(!m)throw new Error("Cannot change call feeds without user id");var y=this.getUserMediaFeed(m,E),S=h.remoteUsermediaFeed,R=S!==y,k=this.calls.get(m),x=k==null?void 0:k.get(E);if((x==null?void 0:x.callId)===h.callId){R&&(!y&&S?this.addUserMediaFeed(S):y&&S?this.replaceUserMediaFeed(y,S):y&&!S&&this.removeUserMediaFeed(y));var T=this.getScreenshareFeed(m,E),O=h.remoteScreensharingFeed,C=O!==T;C&&(!T&&O?this.addScreenshareFeed(O):T&&O?this.replaceScreenshareFeed(T,O):T&&!O&&this.removeScreenshareFeed(T))}}),v(this,"onCallStateChanged",(h,m,E)=>{var y;if(m!==Fe.Ended){var S=this.localCallFeed.isAudioMuted();h.localUsermediaStream&&h.isMicrophoneMuted()!==S&&h.setMicrophoneMuted(S);var R=this.localCallFeed.isVideoMuted();h.localUsermediaStream&&h.isLocalVideoMuted()!==R&&h.setLocalVideoMuted(R);var k=(y=h.getOpponentMember())===null||y===void 0?void 0:y.userId;if(m===Fe.Connected&&k){var x=this.retryCallCounts.get(k);x==null||x.delete(h.getOpponentDeviceId()),(x==null?void 0:x.size)===0&&this.retryCallCounts.delete(k)}}}),v(this,"onCallHangup",h=>{var m,E;if(h.hangupReason!==qe.Replaced){var y=(m=(E=h.getOpponentMember())===null||E===void 0?void 0:E.userId)!==null&&m!==void 0?m:this.room.getMember(h.invitee).userId,S=this.calls.get(y);(S==null?void 0:S.get(h.getOpponentDeviceId()))===h&&(this.disposeCall(h,h.hangupReason),S.delete(h.getOpponentDeviceId()),S.size===0&&this.calls.delete(y),this.emit(yt.CallsChanged,this.calls))}}),v(this,"onCallReplaced",(h,m)=>{var E=h.getOpponentMember().userId,y=this.calls.get(E);y===void 0&&(y=new Map,this.calls.set(E,y)),h.hangup(qe.Replaced,!1),this.initCall(m),y.set(h.getOpponentDeviceId(),m),this.emit(yt.CallsChanged,this.calls)}),v(this,"onActiveSpeakerLoop",()=>{var h=void 0,m=void 0;for(var E of this.userMediaFeeds)if(!(E.isLocal()&&this.userMediaFeeds.length>1)){var y=E.speakingVolumeSamples.reduce((R,k)=>R+Math.max(k,Kb)),S=y/E.speakingVolumeSamples.length;(!h||S>h)&&(h=S,m=E)}m&&this.activeSpeaker!==m&&h&&h>Kb&&(this.activeSpeaker=m,this.emit(yt.ActiveSpeakerChanged,this.activeSpeaker))}),v(this,"onRoomState",()=>this.updateParticipants()),v(this,"onParticipantsChanged",()=>{this.forEachCall(h=>{var m=this.callExpected(h);for(var E of h.getLocalFeeds())tr(E.stream.getAudioTracks(),!E.isAudioMuted()&&m),tr(E.stream.getVideoTracks(),!E.isVideoMuted()&&m)}),this.state===Dt.Entered&&!this.useLivekit&&this.placeOutgoingCalls()}),v(this,"onStateChanged",(h,m)=>{(h===Dt.Entered||m===Dt.Entered||h===Dt.Ended)&&(this.updateParticipants(),this.updateMemberState().catch(E=>b.error("GroupCall ".concat(this.groupCallId,' onStateChanged() failed to update member state devices"'),E)))}),v(this,"onLocalFeedsChanged",()=>{this.state===Dt.Entered&&this.updateMemberState().catch(h=>b.error("GroupCall ".concat(this.groupCallId," onLocalFeedsChanged() failed to update member state feeds"),h))}),this.reEmitter=new VD(this),this.groupCallId=s??ha(),this._livekitServiceURL=p,this.creationTs=(u=(d=t.currentState.getStateEvents(V.GroupCallPrefix,this.groupCallId))===null||d===void 0?void 0:d.getTs())!==null&&u!==void 0?u:null,this.updateParticipants(),t.on(Me.Update,this.onRoomState),this.on(yt.ParticipantsChanged,this.onParticipantsChanged),this.on(yt.GroupCallStateChanged,this.onStateChanged),this.on(yt.LocalScreenshareStateChanged,this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!c}create(){var e=this;return w(function*(){return e.creationTs=Date.now(),e.client.groupCallEventHandler.groupCalls.set(e.room.roomId,e),e.client.emit($b.Outgoing,e),yield e.sendCallStateEvent(),e})()}sendCallStateEvent(){var e=this;return w(function*(){var t={"m.intent":e.intent,"m.type":e.type,"io.element.ptt":e.isPtt,dataChannelsEnabled:e.dataChannelsEnabled,dataChannelOptions:e.dataChannelsEnabled?e.dataChannelOptions:void 0};e.livekitServiceURL&&(t["io.element.livekit_service_url"]=e.livekitServiceURL),yield e.client.sendStateEvent(e.room.roomId,V.GroupCallPrefix,t,e.groupCallId)})()}get livekitServiceURL(){return this._livekitServiceURL}updateLivekitServiceURL(e){return this._livekitServiceURL=e,this.sendCallStateEvent()}get state(){return this._state}set state(e){var t=this._state;e!==t&&(this._state=e,this.emit(yt.GroupCallStateChanged,e,t))}get participants(){return this._participants}set participants(e){var t=this._participants,n=(o,s)=>o.sessionId===s.sessionId&&o.screensharing===s.screensharing,i=(o,s)=>EC(o,s,n);EC(e,t,i)||(this._participants=e,this.emit(yt.ParticipantsChanged,e))}get creationTs(){return this._creationTs}set creationTs(e){this._creationTs=e}get enteredViaAnotherSession(){return this._enteredViaAnotherSession}set enteredViaAnotherSession(e){this._enteredViaAnotherSession=e,this.updateParticipants()}forEachCall(e){for(var t of this.calls.values())for(var n of t.values())e(n)}getLocalFeeds(){var e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e,t;return(e=(t=this.participants.get(this.room.getMember(this.client.getUserId())))===null||t===void 0?void 0:t.has(this.client.getDeviceId()))!==null&&e!==void 0?e:!1}callExpected(e){var t,n=gh(e),i=n===null?null:this.room.getMember(n),o=e.getOpponentDeviceId();return i!==null&&o!==void 0&&((t=this.participants.get(i))===null||t===void 0?void 0:t.get(o))!==void 0}initLocalCallFeed(){var e=this;return w(function*(){if(e.useLivekit){b.info("Livekit group call: not starting local call feed.");return}if(e.state!==Dt.LocalCallFeedUninitialized)throw new Error('Cannot initialize local call feed in the "'.concat(e.state,'" state.'));if(e.state=Dt.InitializingLocalCallFeed,e.initCallFeedPromise)return e.initCallFeedPromise;try{e.initCallFeedPromise=e.initLocalCallFeedInternal(),yield e.initCallFeedPromise}finally{e.initCallFeedPromise=void 0}})()}initLocalCallFeedInternal(){var e=this;return w(function*(){b.log("GroupCall ".concat(e.groupCallId," initLocalCallFeedInternal() running"));var t;try{t=yield e.client.getMediaHandler().getUserMediaStream(!0,e.type===km.Video)}catch(i){if(e.allowCallWithoutVideoAndAudio)t=new MediaStream;else throw e.state=Dt.LocalCallFeedUninitialized,i}if(e._state!==Dt.InitializingLocalCallFeed)throw e.client.getMediaHandler().stopUserMediaStream(t),new Error("Group call disposed while gathering media stream");var n=new bo({client:e.client,roomId:e.room.roomId,userId:e.client.getUserId(),deviceId:e.client.getDeviceId(),stream:t,purpose:St.Usermedia,audioMuted:e.initWithAudioMuted||t.getAudioTracks().length===0||e.isPtt,videoMuted:e.initWithVideoMuted||t.getVideoTracks().length===0});tr(t.getAudioTracks(),!n.isAudioMuted()),tr(t.getVideoTracks(),!n.isVideoMuted()),e.localCallFeed=n,e.addUserMediaFeed(n),e.state=Dt.LocalCallFeedInitialized})()}updateLocalUsermediaStream(e){var t=this;return w(function*(){if(t.localCallFeed){var n=t.localCallFeed.stream;t.localCallFeed.setNewStream(e);var i=t.localCallFeed.isAudioMuted(),o=t.localCallFeed.isVideoMuted();b.log("GroupCall ".concat(t.groupCallId," updateLocalUsermediaStream() (oldStreamId=").concat(n.id,", newStreamId=").concat(e.id,", micShouldBeMuted=").concat(i,", vidShouldBeMuted=").concat(o,")")),tr(e.getAudioTracks(),!i),tr(e.getVideoTracks(),!o),t.client.getMediaHandler().stopUserMediaStream(n)}})()}enter(){var e=this;return w(function*(){if(e.state===Dt.LocalCallFeedUninitialized)yield e.initLocalCallFeed();else if(e.state!==Dt.LocalCallFeedInitialized)throw new Error('Cannot enter call in the "'.concat(e.state,'" state'));b.log("GroupCall ".concat(e.groupCallId," enter() running")),e.state=Dt.Entered,e.client.on(Vb.Incoming,e.onIncomingCall);for(var t of e.client.callEventHandler.calls.values())e.onIncomingCall(t);e.useLivekit||(e.retryCallLoopInterval=setInterval(e.onRetryCallLoop,e.retryCallInterval),e.activeSpeaker=void 0,e.onActiveSpeakerLoop(),e.activeSpeakerLoopInterval=setInterval(e.onActiveSpeakerLoop,e.activeSpeakerInterval))})()}dispose(){var e;this.localCallFeed&&(this.removeUserMediaFeed(this.localCallFeed),this.localCallFeed=void 0),this.localScreenshareFeed&&(this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0),this.client.getMediaHandler().stopAllStreams(),this.transmitTimer!==null&&(clearTimeout(this.transmitTimer),this.transmitTimer=null),this.retryCallLoopInterval!==void 0&&(clearInterval(this.retryCallLoopInterval),this.retryCallLoopInterval=void 0),this.participantsExpirationTimer!==null&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===Dt.Entered&&(this.forEachCall(t=>t.hangup(qe.UserHangup,!1)),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(Vb.Incoming,this.onIncomingCall),(e=this.stats)===null||e===void 0||e.stop())}leave(){this.dispose(),this.state=Dt.LocalCallFeedUninitialized}terminate(){var e=arguments,t=this;return w(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:!0;if(t.dispose(),t.room.off(Me.Update,t.onRoomState),t.client.groupCallEventHandler.groupCalls.delete(t.room.roomId),t.client.emit($b.Ended,t),t.state=Dt.Ended,n){var i=t.room.currentState.getStateEvents(V.GroupCallPrefix,t.groupCallId);yield t.client.sendStateEvent(t.room.roomId,V.GroupCallPrefix,mh(mh({},i.getContent()),{},{"m.terminated":c8.CallEnded}),t.groupCallId)}})()}isLocalVideoMuted(){return this.localCallFeed?this.localCallFeed.isVideoMuted():!0}isMicrophoneMuted(){return this.localCallFeed?this.localCallFeed.isAudioMuted():!0}setMicrophoneMuted(e){var t=this;return w(function*(){if(!e&&!(yield t.client.getMediaHandler().hasAudioDevice()))return!1;var n=!e&&t.isPtt;t.isPtt&&(!e&&t.isMicrophoneMuted()?t.transmitTimer=setTimeout(()=>{t.setMicrophoneMuted(!0)},t.pttMaxTransmitTime):e&&!t.isMicrophoneMuted()&&(t.transmitTimer!==null&&clearTimeout(t.transmitTimer),t.transmitTimer=null)),t.forEachCall(s=>{var a;return(a=s.localUsermediaFeed)===null||a===void 0?void 0:a.setAudioVideoMuted(e,null)});var i=function(){var s=w(function*(){var a=[];t.forEachCall(l=>a.push(l.sendMetadataUpdate())),yield Promise.all(a).catch(l=>b.info("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() failed to send some metadata updates"),l))});return function(){return s.apply(this,arguments)}}();if(n&&(yield i()),t.localCallFeed){b.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() (streamId=").concat(t.localCallFeed.stream.id,", muted=").concat(e,")"));var o=yield t.checkAudioPermissionIfNecessary(e);if(!o)return!1;t.localCallFeed.setAudioVideoMuted(e,null),tr(t.localCallFeed.stream.getAudioTracks(),!e)}else b.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no stream muted (muted=").concat(e,")")),t.initWithAudioMuted=e;return t.forEachCall(s=>tr(s.localUsermediaFeed.stream.getAudioTracks(),!e&&t.callExpected(s))),t.emit(yt.LocalMuteStateChanged,e,t.isLocalVideoMuted()),n||(yield i()),!0})()}checkAudioPermissionIfNecessary(e){var t=this;return w(function*(){try{if(!e&&t.localCallFeed&&!t.localCallFeed.hasAudioTrack){var n=yield t.client.getMediaHandler().getUserMediaStream(!0,!t.localCallFeed.isVideoMuted());if((n==null?void 0:n.getTracks().length)===0)return b.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no device to receive local stream, muted=").concat(e)),!1}}catch{return b.log("GroupCall ".concat(t.groupCallId," setMicrophoneMuted() no device or permission to receive local stream, muted=").concat(e)),!1}return!0})()}setLocalVideoMuted(e){var t=this;return w(function*(){if(!e&&!(yield t.client.getMediaHandler().hasVideoDevice()))return!1;if(t.localCallFeed){b.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() (stream=").concat(t.localCallFeed.stream.id,", muted=").concat(e,")"));try{var n=yield t.client.getMediaHandler().getUserMediaStream(!0,!e);yield t.updateLocalUsermediaStream(n),t.localCallFeed.setAudioVideoMuted(null,e),tr(t.localCallFeed.stream.getVideoTracks(),!e)}catch{return b.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() no device or permission to receive local stream, muted=").concat(e)),!1}}else b.log("GroupCall ".concat(t.groupCallId," setLocalVideoMuted() no stream muted (muted=").concat(e,")")),t.initWithVideoMuted=e;var i=[];return t.forEachCall(o=>i.push(o.setLocalVideoMuted(e))),yield Promise.all(i),t.forEachCall(o=>tr(o.localUsermediaFeed.stream.getVideoTracks(),!e&&t.callExpected(o))),t.emit(yt.LocalMuteStateChanged,t.isMicrophoneMuted(),e),!0})()}setScreensharingEnabled(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};if(e===n.isScreensharing())return e;if(e)try{b.log("GroupCall ".concat(n.groupCallId," setScreensharingEnabled() is asking for screensharing permissions"));var o=yield n.client.getMediaHandler().getScreensharingStream(i),s=function*(c){var u=()=>{n.setScreensharingEnabled(!1),c.removeEventListener("ended",u)};c.addEventListener("ended",u)};for(var a of o.getTracks())yield*s(a);return b.log("GroupCall ".concat(n.groupCallId," setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls")),n.localDesktopCapturerSourceId=i.desktopCapturerSourceId,n.localScreenshareFeed=new bo({client:n.client,roomId:n.room.roomId,userId:n.client.getUserId(),deviceId:n.client.getDeviceId(),stream:o,purpose:St.Screenshare,audioMuted:!1,videoMuted:!1}),n.addScreenshareFeed(n.localScreenshareFeed),n.emit(yt.LocalScreenshareStateChanged,!0,n.localScreenshareFeed,n.localDesktopCapturerSourceId),n.forEachCall(l=>l.pushLocalFeed(n.localScreenshareFeed.clone())),!0}catch(l){if(i.throwOnFail)throw l;return b.error("GroupCall ".concat(n.groupCallId," setScreensharingEnabled() enabling screensharing error"),l),n.emit(yt.Error,new Wb(id.NoUserMedia,"Failed to get screen-sharing stream: ",l)),!1}else return n.forEachCall(l=>{l.localScreensharingFeed&&l.removeLocalFeed(l.localScreensharingFeed)}),n.client.getMediaHandler().stopScreensharingStream(n.localScreenshareFeed.stream),n.removeScreenshareFeed(n.localScreenshareFeed),n.localScreenshareFeed=void 0,n.localDesktopCapturerSourceId=void 0,n.emit(yt.LocalScreenshareStateChanged,!1,void 0,void 0),!1})()}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,t){var n=this.client.getUserId(),i=this.client.getDeviceId();return e>=n&&(e!==n||t>i)}placeOutgoingCalls(){var e=this,t=!1,n=function(a){var l,c=(l=e.calls.get(a))!==null&&l!==void 0?l:new Map,u=function(h){var m=c.get(h);if((m==null?void 0:m.getOpponentSessionId())!==f.sessionId&&e.wantsOutgoingCall(a,h)){t=!0,m!==void 0&&(b.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() replacing call (userId=").concat(a,", deviceId=").concat(h,", callId=").concat(m.callId,")")),m.hangup(qe.NewSession,!1));var E=Kd(e.client,e.room.roomId,{invitee:a,opponentDeviceId:h,opponentSessionId:f.sessionId,groupCallId:e.groupCallId});E===null?(b.error("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to create call (userId=").concat(a,", device=").concat(h,")")),c.delete(h)):(e.initCall(E),c.set(h,E),b.debug("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() placing call (userId=").concat(a,", deviceId=").concat(h,", sessionId=").concat(f.sessionId,")")),E.placeCallWithCallFeeds(e.getLocalFeeds().map(y=>y.clone()),f.screensharing).then(()=>{e.dataChannelsEnabled&&E.createDataChannel("datachannel",e.dataChannelOptions)}).catch(y=>{b.warn("GroupCall ".concat(e.groupCallId," placeOutgoingCalls() failed to place call (userId=").concat(a,")"),y),y instanceof mo&&y.code===id.UnknownDevice?e.emit(yt.Error,y):e.emit(yt.Error,new Wb(id.PlaceCallFailed,"Failed to place call to ".concat(a))),E.hangup(qe.SignallingFailed,!1),c.get(h)===E&&c.delete(h)}))}};for(var[d,f]of o)u(d);c.size>0?e.calls.set(a,c):e.calls.delete(a)};for(var[{userId:i},o]of this.participants)n(i);t&&this.emit(yt.CallsChanged,this.calls)}getMemberStateEvents(e){return e===void 0?this.room.currentState.getStateEvents(V.GroupCallMemberPrefix):this.room.currentState.getStateEvents(V.GroupCallMemberPrefix,e)}initCall(e){var t=gh(e);if(!t)throw new Error("Cannot init call without user id");var n=()=>this.onCallFeedsChanged(e),i=(l,c)=>this.onCallStateChanged(e,l,c),o=this.onCallHangup,s=l=>this.onCallReplaced(e,l),a=this.callHandlers.get(t);a===void 0&&(a=new Map,this.callHandlers.set(t,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:n,onCallStateChanged:i,onCallHangup:o,onCallReplaced:s}),e.on(Ye.FeedsChanged,n),e.on(Ye.State,i),e.on(Ye.Hangup,o),e.on(Ye.Replaced,s),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(Ye)),e.initStats(this.getGroupCallStats()),n()}disposeCall(e,t){var n=gh(e),i=e.getOpponentDeviceId();if(!n)throw new Error("Cannot dispose call without user id");var o=this.callHandlers.get(n),{onCallFeedsChanged:s,onCallStateChanged:a,onCallHangup:l,onCallReplaced:c}=o.get(i);if(e.removeListener(Ye.FeedsChanged,s),e.removeListener(Ye.State,a),e.removeListener(Ye.Hangup,l),e.removeListener(Ye.Replaced,c),o.delete(n),o.size===0&&this.callHandlers.delete(n),e.hangupReason!==qe.Replaced){var u=this.getUserMediaFeed(n,i);u&&this.removeUserMediaFeed(u);var d=this.getScreenshareFeed(n,i);d&&this.removeScreenshareFeed(d)}}getUserMediaFeed(e,t){return this.userMediaFeeds.find(n=>n.userId===e&&n.deviceId===t)}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit(yt.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(e,t){var n=this.userMediaFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(n===-1)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(n,1,t),e.dispose(),t.measureVolumeActivity(!0),this.emit(yt.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(e){var t=this.userMediaFeeds.findIndex(n=>n.userId===e.userId&&n.deviceId===e.deviceId);if(t===-1)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(t,1),e.dispose(),this.emit(yt.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(yt.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(e,t){return this.screenshareFeeds.find(n=>n.userId===e&&n.deviceId===t)}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit(yt.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(e,t){var n=this.screenshareFeeds.findIndex(i=>i.userId===e.userId&&i.deviceId===e.deviceId);if(n===-1)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(n,1,t),e.dispose(),this.emit(yt.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(e){var t=this.screenshareFeeds.findIndex(n=>n.userId===e.userId&&n.deviceId===e.deviceId);if(t===-1)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(t,1),e.dispose(),this.emit(yt.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){var e=this.room.getMember(this.client.getUserId());if(!e){b.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===Dt.Ended){this.participants=new Map;return}var t=new Map,n=Date.now(),i=this.state===Dt.Entered||this.enteredViaAnotherSession,o=1/0;for(var s of this.getMemberStateEvents()){var a=this.room.getMember(s.getStateKey()),l=s.getContent(),c=Array.isArray(l["m.calls"])?l["m.calls"]:[],u=c.find(E=>E["m.call_id"]===this.groupCallId),d=Array.isArray(u==null?void 0:u["m.devices"])?u["m.devices"]:[],f=d.filter(E=>typeof E.device_id=="string"&&typeof E.session_id=="string"&&typeof E.expires_ts=="number"&&E.expires_ts>n&&Array.isArray(E.feeds));if(!i&&(a==null?void 0:a.userId)===this.client.getUserId()&&(f=f.filter(E=>E.device_id!==this.client.getDeviceId())),f.length>0&&(a==null?void 0:a.membership)===Be.Join){var p=new Map;t.set(a,p);for(var h of f)p.set(h.device_id,{sessionId:h.session_id,screensharing:h.feeds.some(E=>E.purpose===St.Screenshare)}),h.expires_ts<o&&(o=h.expires_ts)}}if(i){var m=t.get(e);m===void 0&&(m=new Map,t.set(e,m)),m.has(this.client.getDeviceId())||m.set(this.client.getDeviceId(),{sessionId:this.client.getSessionId(),screensharing:this.getLocalFeeds().some(E=>E.purpose===St.Screenshare)})}this.participants=t,o<1/0&&(this.participantsExpirationTimer=setTimeout(()=>this.updateParticipants(),o-n))}updateDevices(e){var t=arguments,n=this;return w(function*(){var i,o=t.length>1&&t[1]!==void 0?t[1]:!1,s=Date.now(),a=n.client.getUserId(),l=n.getMemberStateEvents(a),c=(i=l==null?void 0:l.getContent())!==null&&i!==void 0?i:{},u=Array.isArray(c["m.calls"])?c["m.calls"]:[],d=null,f=[];for(var p of u)p["m.call_id"]===n.groupCallId?d=p:f.push(p);d===null&&(d={});var h=Array.isArray(d["m.devices"])?d["m.devices"]:[],m=h.filter(R=>typeof R.device_id=="string"&&typeof R.session_id=="string"&&typeof R.expires_ts=="number"&&R.expires_ts>s&&Array.isArray(R.feeds)),E=e(m);if(E!==null){var y=[...f];E.length>0&&y.push(mh(mh({},d),{},{"m.call_id":n.groupCallId,"m.devices":E}));var S={"m.calls":y};yield n.client.sendStateEvent(n.room.roomId,V.GroupCallMemberPrefix,S,a,{keepAlive:o})}})()}addDeviceToMemberState(){var e=this;return w(function*(){yield e.updateDevices(t=>[...t.filter(n=>n.device_id!==e.client.getDeviceId()),{device_id:e.client.getDeviceId(),session_id:e.client.getSessionId(),expires_ts:Date.now()+HC,feeds:e.getLocalFeeds().map(n=>({purpose:n.purpose}))}])})()}updateMemberState(){var e=this;return w(function*(){e.resendMemberStateTimer!==null&&(clearInterval(e.resendMemberStateTimer),e.resendMemberStateTimer=null),e.state===Dt.Entered?(yield e.addDeviceToMemberState(),e.resendMemberStateTimer=setInterval(w(function*(){b.log("GroupCall ".concat(e.groupCallId,' updateMemberState() resending call member state"'));try{yield e.addDeviceToMemberState()}catch(t){b.error("GroupCall ".concat(e.groupCallId," updateMemberState() failed to resend call member state"),t)}}),HC*3/4)):yield e.updateDevices(t=>t.filter(n=>n.device_id!==e.client.getDeviceId()),!0)})()}cleanMemberState(){var e=this;return w(function*(){var{devices:t}=yield e.client.getDevices(),n=new Map(t.map(i=>[i.device_id,i]));yield e.updateDevices(i=>{var o=i.filter(s=>{var a=n.get(s.device_id);return(a==null?void 0:a.last_seen_ts)!==void 0&&!(s.device_id===e.client.getDeviceId()&&e.state!==Dt.Entered&&!e.enteredViaAnotherSession)});return o.length===i.length?null:o})})()}getGroupCallStats(){if(this.stats===void 0){var e=this.client.getUserId()||"unknown";this.stats=new l8(this.groupCallId,e,this.statsCollectIntervalTime),this.stats.reports.on(Ro.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(Ro.BYTE_SENT_STATS,this.onByteSentStats),this.stats.reports.on(Ro.SUMMARY_STATS,this.onSummaryStats),this.stats.reports.on(Ro.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 zC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function yh(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?zC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):zC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Fe=function(r){return r.Fledgling="fledgling",r.InviteSent="invite_sent",r.WaitLocalMedia="wait_local_media",r.CreateOffer="create_offer",r.CreateAnswer="create_answer",r.Connecting="connecting",r.Connected="connected",r.Ringing="ringing",r.Ended="ended",r}({}),YC=function(r){return r.Voice="voice",r.Video="video",r}({}),ts=function(r){return r.Inbound="inbound",r.Outbound="outbound",r}({}),$t=function(r){return r.Local="local",r.Remote="remote",r}({}),Ye=function(r){return r.Hangup="hangup",r.State="state",r.Error="error",r.Replaced="replaced",r.LocalHoldUnhold="local_hold_unhold",r.RemoteHoldUnhold="remote_hold_unhold",r.HoldUnhold="hold_unhold",r.FeedsChanged="feeds_changed",r.AssertedIdentityChanged="asserted_identity_changed",r.LengthChanged="length_changed",r.DataChannel="datachannel",r.SendVoipEvent="send_voip_event",r.PeerConnectionCreated="peer_connection_created",r}({}),qe=function(r){return r.UserHangup="user_hangup",r.LocalOfferFailed="local_offer_failed",r.NoUserMedia="no_user_media",r.UnknownDevices="unknown_devices",r.SendInvite="send_invite",r.CreateAnswer="create_answer",r.CreateOffer="create_offer",r.SendAnswer="send_answer",r.SetRemoteDescription="set_remote_description",r.SetLocalDescription="set_local_description",r.AnsweredElsewhere="answered_elsewhere",r.IceFailed="ice_failed",r.InviteTimeout="invite_timeout",r.Replaced="replaced",r.SignallingFailed="signalling_timeout",r.UserBusy="user_busy",r.Transferred="transferred",r.NewSession="new_session",r}({}),u8="1",d8="stun:turn.matrix.org",ay=60*1e3,f8=1e3,h8=30*1e3,p8=2*1e3;class mo extends Error{constructor(e,t,n){super(t+": "+n),v(this,"code",void 0),this.code=e}}function ha(){return Date.now().toString()+Ei(16)}function JC(r){var e=[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:r?12e3:void 0}];return e}function si(r,e){return r+":"+e}class v8 extends Tt{constructor(e){var t,n;if(super(),t=this,v(this,"roomId",void 0),v(this,"callId",void 0),v(this,"invitee",void 0),v(this,"hangupParty",void 0),v(this,"hangupReason",void 0),v(this,"direction",void 0),v(this,"ourPartyId",void 0),v(this,"peerConn",void 0),v(this,"toDeviceSeq",0),v(this,"isPtt",!1),v(this,"_state",Fe.Fledgling),v(this,"client",void 0),v(this,"forceTURN",void 0),v(this,"turnServers",void 0),v(this,"candidateSendQueue",[]),v(this,"candidateSendTries",0),v(this,"candidatesEnded",!1),v(this,"feeds",[]),v(this,"transceivers",new Map),v(this,"inviteOrAnswerSent",!1),v(this,"waitForLocalAVStream",!1),v(this,"successor",void 0),v(this,"opponentMember",void 0),v(this,"opponentVersion",void 0),v(this,"opponentPartyId",void 0),v(this,"opponentCaps",void 0),v(this,"iceDisconnectedTimeout",void 0),v(this,"iceReconnectionTimeOut",void 0),v(this,"inviteTimeout",void 0),v(this,"removeTrackListeners",new Map),v(this,"remoteOnHold",!1),v(this,"callStatsAtEnd",void 0),v(this,"makingOffer",!1),v(this,"ignoreOffer",!1),v(this,"isSettingRemoteAnswerPending",!1),v(this,"responsePromiseChain",void 0),v(this,"remoteCandidateBuffer",new Map),v(this,"remoteAssertedIdentity",void 0),v(this,"remoteSDPStreamMetadata",void 0),v(this,"callLengthInterval",void 0),v(this,"callStartTime",void 0),v(this,"opponentDeviceId",void 0),v(this,"opponentDeviceInfo",void 0),v(this,"opponentSessionId",void 0),v(this,"groupCallId",void 0),v(this,"stopVideoTrackTimer",void 0),v(this,"isOnlyDataChannelAllowed",void 0),v(this,"stats",void 0),v(this,"gotLocalIceCandidate",o=>{if(o.candidate){if(this.candidatesEnded&&b.warn("Call ".concat(this.callId," gotLocalIceCandidate() got candidate after candidates have ended!")),b.debug("Call ".concat(this.callId," got local ICE ").concat(o.candidate.sdpMid," ").concat(o.candidate.candidate)),this.callHasEnded())return;o.candidate.candidate===""?this.queueCandidate(null):this.queueCandidate(o.candidate)}}),v(this,"onIceGatheringStateChange",o=>{var s;b.debug("Call ".concat(this.callId," onIceGatheringStateChange() ice gathering state changed to ").concat(this.peerConn.iceGatheringState)),((s=this.peerConn)===null||s===void 0?void 0:s.iceGatheringState)==="complete"&&(this.queueCandidate(null),b.debug("Call ".concat(this.callId," onIceGatheringStateChange() ice gathering state complete, set candidates have ended")))}),v(this,"getLocalOfferFailed",o=>{b.error("Call ".concat(this.callId," getLocalOfferFailed() running"),o),this.emit(Ye.Error,new mo(qe.LocalOfferFailed,"Failed to get local offer!",o),this),this.terminate($t.Local,qe.LocalOfferFailed,!1)}),v(this,"getUserMediaFailed",o=>{if(this.successor){this.successor.getUserMediaFailed(o);return}b.warn("Call ".concat(this.callId," getUserMediaFailed() failed to get user media - ending call"),o),this.emit(Ye.Error,new mo(qe.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",o),this),this.terminate($t.Local,qe.NoUserMedia,!1)}),v(this,"placeCallFailed",o=>{if(this.successor){this.successor.placeCallFailed(o);return}b.warn("Call ".concat(this.callId," placeCallWithCallFeeds() failed - ending call"),o),this.emit(Ye.Error,new mo(qe.IceFailed,"Couldn't start call! Invalid ICE server configuration.",o),this),this.terminate($t.Local,qe.IceFailed,!1)}),v(this,"onIceConnectionStateChanged",()=>{var o,s,a,l,c,u;if(!this.callHasEnded()){if(b.debug("Call ".concat(this.callId," onIceConnectionStateChanged() running (state=").concat((o=this.peerConn)===null||o===void 0?void 0:o.iceConnectionState,", conn=").concat((s=this.peerConn)===null||s===void 0?void 0:s.connectionState,")")),["connected","completed"].includes((a=(l=this.peerConn)===null||l===void 0?void 0:l.iceConnectionState)!==null&&a!==void 0?a:""))clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.iceReconnectionTimeOut&&clearTimeout(this.iceReconnectionTimeOut),this.state=Fe.Connected,!this.callLengthInterval&&!this.callStartTime&&(this.callStartTime=Date.now(),this.callLengthInterval=setInterval(()=>{this.emit(Ye.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3),this)},f8));else if(((c=this.peerConn)===null||c===void 0?void 0:c.iceConnectionState)=="failed"){var d;if(this.candidatesEnded=!1,(d=this.peerConn)!==null&&d!==void 0&&d.restartIce){var f;this.candidatesEnded=!1,b.debug("Call ".concat(this.callId," onIceConnectionStateChanged() ice restart (state=").concat((f=this.peerConn)===null||f===void 0?void 0:f.iceConnectionState,")")),this.peerConn.restartIce()}else b.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)")),this.hangup(qe.IceFailed,!1)}else((u=this.peerConn)===null||u===void 0?void 0:u.iceConnectionState)=="disconnected"&&(this.candidatesEnded=!1,this.iceReconnectionTimeOut=setTimeout(()=>{var h,m,E;b.info("Call ".concat(this.callId," onIceConnectionStateChanged() ICE restarting because of ICE disconnected, (state=").concat((h=this.peerConn)===null||h===void 0?void 0:h.iceConnectionState,", conn=").concat((m=this.peerConn)===null||m===void 0?void 0:m.connectionState,")")),(E=this.peerConn)!==null&&E!==void 0&&E.restartIce&&(this.candidatesEnded=!1,this.peerConn.restartIce()),this.iceReconnectionTimeOut=void 0},p8),this.iceDisconnectedTimeout=setTimeout(()=>{b.info("Call ".concat(this.callId," onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)")),this.hangup(qe.IceFailed,!1)},h8),this.state=Fe.Connecting);if(this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState))for(var p of this.getRemoteFeeds())p.setAudioVideoMuted(!0,!0)}}),v(this,"onSignallingStateChanged",()=>{var o;b.debug("Call ".concat(this.callId," onSignallingStateChanged() running (state=").concat((o=this.peerConn)===null||o===void 0?void 0:o.signalingState,")"))}),v(this,"onTrack",o=>{if(o.streams.length===0){b.warn("Call ".concat(this.callId," onTrack() called with streamless track streamless (kind=").concat(o.track.kind,")"));return}var s=o.streams[0];if(this.pushRemoteFeed(s),!this.removeTrackListeners.has(s)){var a=()=>{s.getTracks().length===0&&(b.info("Call ".concat(this.callId," onTrack() removing track (streamId=").concat(s.id,")")),this.deleteFeedByStream(s),s.removeEventListener("removetrack",a),this.removeTrackListeners.delete(s))};s.addEventListener("removetrack",a),this.removeTrackListeners.set(s,a)}}),v(this,"onDataChannel",o=>{this.emit(Ye.DataChannel,o.channel,this)}),v(this,"onNegotiationNeeded",w(function*(){if(b.info("Call ".concat(t.callId," onNegotiationNeeded() negotiation is needed!")),t.state!==Fe.CreateOffer&&t.opponentVersion===0){b.info("Call ".concat(t.callId," onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event"));return}t.queueGotLocalOffer()})),v(this,"onHangupReceived",o=>{b.debug("Call ".concat(this.callId," onHangupReceived() running")),this.partyIdMatches(o)||this.state===Fe.Ringing?this.terminate($t.Remote,o.reason||qe.UserHangup,!0):b.info("Call ".concat(this.callId," onHangupReceived() ignoring message from party ID ").concat(o.party_id,": our partner is ").concat(this.opponentPartyId))}),v(this,"onRejectReceived",o=>{b.debug("Call ".concat(this.callId," onRejectReceived() running"));var s=[Fe.InviteSent,Fe.Ringing].includes(this.state)||this.state===Fe.Fledgling&&this.direction===ts.Inbound;s?this.terminate($t.Remote,o.reason||qe.UserHangup,!0):b.debug("Call ".concat(this.callId," onRejectReceived() called in wrong state (state=").concat(this.state,")"))}),v(this,"onAnsweredElsewhere",o=>{b.debug("Call ".concat(this.callId," onAnsweredElsewhere() running")),this.terminate($t.Remote,qe.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=(n=e.forceTURN)!==null&&n!==void 0?n:!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:[d8]});for(var i of this.turnServers)SD(i,["urls"]);this.callId=ha(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}placeVoiceCall(){var e=this;return w(function*(){yield e.placeCall(!0,!1)})()}placeVideoCall(){var e=this;return w(function*(){yield e.placeCall(!0,!0)})()}createDataChannel(e,t){var n=this.peerConn.createDataChannel(e,t);return this.emit(Ye.DataChannel,n,this),n}getOpponentMember(){return this.opponentMember}getOpponentDeviceId(){return this.opponentDeviceId}getOpponentSessionId(){return this.opponentSessionId}opponentCanBeTransferred(){return!!(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return!!(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get state(){return this._state}set state(e){var t=this._state;this._state=e,this.emit(Ye.State,e,t,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?YC.Video:YC.Voice}get hasLocalUserMediaVideoTrack(){var e;return!!((e=this.localUsermediaStream)!==null&&e!==void 0&&e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===St.Usermedia&&((t=e.stream)===null||t===void 0?void 0:t.getVideoTracks().length)})}get hasLocalUserMediaAudioTrack(){var e;return!!((e=this.localUsermediaStream)!==null&&e!==void 0&&e.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some(e=>{var t;return e.purpose===St.Usermedia&&!!((t=e.stream)!==null&&t!==void 0&&t.getAudioTracks().length)})}get hasUserMediaAudioSender(){var e;return!!(!((e=this.transceivers.get(si(St.Usermedia,"audio")))===null||e===void 0)&&e.sender)}get hasUserMediaVideoSender(){var e;return!!(!((e=this.transceivers.get(si(St.Usermedia,"video")))===null||e===void 0)&&e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find(e=>e.purpose===St.Usermedia)}get localScreensharingFeed(){return this.getLocalFeeds().find(e=>e.purpose===St.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===St.Usermedia)}get remoteScreensharingFeed(){return this.getRemoteFeeds().find(e=>e.purpose===St.Screenshare)}get remoteUsermediaStream(){var e;return(e=this.remoteUsermediaFeed)===null||e===void 0?void 0:e.stream}get remoteScreensharingStream(){var e;return(e=this.remoteScreensharingFeed)===null||e===void 0?void 0:e.stream}getFeedByStreamId(e){return this.getFeeds().find(t=>t.stream.id===e)}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter(e=>e.isLocal())}getRemoteFeeds(){return this.feeds.filter(e=>!e.isLocal())}initOpponentCrypto(){var e=this;return w(function*(){var t,n;if(e.opponentDeviceId&&e.client.getUseE2eForGroupCall()){if(!e.client.isCryptoEnabled()){e.opponentDeviceInfo=new rn(e.opponentDeviceId);return}if(!e.client.crypto)throw new Error("Crypto is not initialised.");var i=e.invitee||((t=e.getOpponentMember())===null||t===void 0?void 0:t.userId);if(!i)throw new Error("Couldn't find opponent user ID to init crypto");var o=yield e.client.crypto.deviceList.downloadKeys([i],!1);if(e.opponentDeviceInfo=(n=o.get(i))===null||n===void 0?void 0:n.get(e.opponentDeviceId),e.opponentDeviceInfo===void 0)throw new TN(i)}})()}getLocalSDPStreamMetadata(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t={};for(var n of this.getLocalFeeds())e&&(n.sdpMetadataStreamId=n.stream.id),t[n.sdpMetadataStreamId]={purpose:n.purpose,audio_muted:n.isAudioMuted(),video_muted:n.isVideoMuted()};return t}noIncomingFeeds(){return!this.feeds.some(e=>!e.isLocal())}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata()){this.pushRemoteFeedWithoutMetadata(e);return}var t=this.getOpponentMember().userId,n=this.remoteSDPStreamMetadata[e.id].purpose,i=this.remoteSDPStreamMetadata[e.id].audio_muted,o=this.remoteSDPStreamMetadata[e.id].video_muted;if(!n){b.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)){b.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 bo({client:this.client,call:this,roomId:this.roomId,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:n,audioMuted:i,videoMuted:o})),this.emit(Ye.FeedsChanged,this.feeds,this),b.info("Call ".concat(this.callId," pushRemoteFeed() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,", purpose=").concat(n,")"))}pushRemoteFeedWithoutMetadata(e){var t,n=this.getOpponentMember().userId,i=St.Usermedia,o=(t=this.feeds.find(s=>!s.isLocal()))===null||t===void 0?void 0:t.stream;if(o&&e.id!==o.id){b.warn("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=").concat(e.id,")"));return}if(this.getFeedByStreamId(e.id)){b.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 bo({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:n,deviceId:this.getOpponentDeviceId(),stream:e,purpose:i})),this.emit(Ye.FeedsChanged,this.feeds,this),b.info("Call ".concat(this.callId," pushRemoteFeedWithoutMetadata() pushed stream (streamId=").concat(e.id,", active=").concat(e.active,")"))}pushNewLocalFeed(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=this.client.getUserId();if(tr(e.getAudioTracks(),!0),tr(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)){b.warn("Call ".concat(this.callId," pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=").concat(e.id,")"));return}this.pushLocalFeed(new bo({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:t}),n)}pushLocalFeed(e){var t=this,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(this.feeds.some(s=>e.stream.id===s.stream.id)){b.info("Call ".concat(this.callId," pushLocalFeed() ignoring duplicate local stream (streamId=").concat(e.stream.id,")"));return}if(this.feeds.push(e),n){var i=function(){b.info("Call ".concat(t.callId," pushLocalFeed() adding track to peer connection (id=").concat(o.id,", kind=").concat(o.kind,", streamId=").concat(e.stream.id,", streamPurpose=").concat(e.purpose,", enabled=").concat(o.enabled,")"));var a=si(e.purpose,o.kind);if(t.transceivers.has(a)){var l=t.transceivers.get(a);l.sender.replaceTrack(o),l.direction=l.direction==="inactive"?"sendonly":"sendrecv"}else{var c=t.peerConn.addTrack(o,e.stream),u=t.peerConn.getTransceivers().find(d=>d.sender===c);u?t.transceivers.set(a,u):b.warn("Call ".concat(t.callId," pushLocalFeed() didn't find a matching transceiver after adding track!"))}};for(var o of e.stream.getTracks())i()}b.info("Call ".concat(this.callId," pushLocalFeed() pushed stream (id=").concat(e.stream.id,", active=").concat(e.stream.active,", purpose=").concat(e.purpose,")")),this.emit(Ye.FeedsChanged,this.feeds,this)}removeLocalFeed(e){var t=si(e.purpose,"audio"),n=si(e.purpose,"video");for(var i of[t,n])if(this.transceivers.has(i)){var o=this.transceivers.get(i);o.sender&&this.peerConn.removeTrack(o.sender)}e.purpose===St.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(Ye.FeedsChanged,this.feeds,this)}deleteFeedByStream(e){var t=this.getFeedByStreamId(e.id);if(!t){b.warn("Call ".concat(this.callId," deleteFeedByStream() didn't find the feed to delete (streamId=").concat(e.id,")"));return}this.deleteFeed(t)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit(Ye.FeedsChanged,this.feeds,this)}getCurrentCallStats(){var e=this;return w(function*(){return e.callHasEnded()?e.callStatsAtEnd:e.collectCallStats()})()}collectCallStats(){var e=this;return w(function*(){if(e.peerConn){var t=yield e.peerConn.getStats(),n=[];return t.forEach(i=>{n.push(i)}),n}})()}initWithInvite(e){var t=this;return w(function*(){var n,i=e.getContent();t.direction=ts.Inbound;var o=yield t.client.checkTurnServers();o||b.warn("Call ".concat(t.callId," initWithInvite() failed to get TURN credentials! Proceeding with call anyway..."));var s=i[Jo];s?t.updateRemoteSDPStreamMetadata(s):b.debug("Call ".concat(t.callId," initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams")),t.peerConn=t.createPeerConnection(),t.emit(Ye.PeerConnectionCreated,t.peerConn,t),t.chooseOpponent(e),yield t.initOpponentCrypto();try{yield t.peerConn.setRemoteDescription(i.offer),b.debug("Call ".concat(t.callId," initWithInvite() set remote description: ").concat(i.offer.type)),yield t.addBufferedIceCandidates()}catch(u){b.debug("Call ".concat(t.callId," initWithInvite() failed to set remote description"),u),t.terminate($t.Local,qe.SetRemoteDescription,!1);return}var a=(n=t.feeds.find(u=>!u.isLocal()))===null||n===void 0?void 0:n.stream;if(!t.isOnlyDataChannelAllowed&&(!a||a.getTracks().length===0)){b.error("Call ".concat(t.callId," initWithInvite() no remote stream or no tracks after setting remote description!")),t.terminate($t.Local,qe.SetRemoteDescription,!1);return}if(t.state=Fe.Ringing,e.getLocalAge()){var l=setTimeout(()=>{if(t.state==Fe.Ringing){var u;b.debug("Call ".concat(t.callId," initWithInvite() invite has expired. Hanging up.")),t.hangupParty=$t.Remote,t.state=Fe.Ended,t.stopAllMedia(),t.peerConn.signalingState!="closed"&&t.peerConn.close(),(u=t.stats)===null||u===void 0||u.removeStatsReportGatherer(t.callId),t.emit(Ye.Hangup,t)}},i.lifetime-e.getLocalAge()),c=u=>{u!==Fe.Ringing&&(clearTimeout(l),t.off(Ye.State,c))};t.on(Ye.State,c)}})()}initWithHangup(e){this.state=Fe.Ended}shouldAnswerWithMediaType(e,t,n){return e&&!t?(b.warn("Call ".concat(this.callId," shouldAnswerWithMediaType() unable to answer with ").concat(n," because the other side isn't sending it either.")),!1):!ED(e)&&e!==t&&!this.opponentSupportsSDPStreamMetadata()?(b.warn("Call ".concat(this.callId," shouldAnswerWithMediaType() unable to answer with ").concat(n,"=").concat(e," because the other side doesn't support it. Answering with ").concat(n,"=").concat(t,".")),t):e??t}answer(e,t){var n=this;return w(function*(){if(!n.inviteOrAnswerSent){if(e===!1&&t===!1)throw new Error("You CANNOT answer a call without media");if(!n.localUsermediaStream&&!n.waitForLocalAVStream){var i=n.state,o=n.shouldAnswerWithMediaType(e,n.hasRemoteUserMediaAudioTrack,"audio"),s=n.shouldAnswerWithMediaType(t,n.hasRemoteUserMediaVideoTrack,"video");n.state=Fe.WaitLocalMedia,n.waitForLocalAVStream=!0;try{var a,l=yield n.client.getMediaHandler().getUserMediaStream(o,s);n.waitForLocalAVStream=!1;var c=new bo({client:n.client,roomId:n.roomId,userId:n.client.getUserId(),deviceId:(a=n.client.getDeviceId())!==null&&a!==void 0?a:void 0,stream:l,purpose:St.Usermedia,audioMuted:!1,videoMuted:!1}),u=[c];n.localScreensharingFeed&&u.push(n.localScreensharingFeed),n.answerWithCallFeeds(u)}catch(d){if(s)b.warn("Call ".concat(n.callId," answer() failed to getUserMedia(), trying to getUserMedia() without video")),n.state=i,n.waitForLocalAVStream=!1,yield n.answer(o,!1);else{n.getUserMediaFailed(d);return}}}else n.waitForLocalAVStream&&(n.state=Fe.WaitLocalMedia)}})()}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){b.debug("Call ".concat(this.callId," replacedBy() running (newCallId=").concat(e.callId,")")),this.state===Fe.WaitLocalMedia?(b.debug("Call ".concat(this.callId," replacedBy() telling new call to wait for local media (newCallId=").concat(e.callId,")")),e.waitForLocalAVStream=!0):[Fe.CreateOffer,Fe.InviteSent].includes(this.state)&&(e.direction===ts.Outbound?e.queueGotCallFeedsForAnswer([]):(b.debug("Call ".concat(this.callId," replacedBy() handing local stream to new call(newCallId=").concat(e.callId,")")),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(t=>t.clone())))),this.successor=e,this.emit(Ye.Replaced,e,this),this.hangup(qe.Replaced,!0)}hangup(e,t){if(!this.callHasEnded()&&(b.debug("Call ".concat(this.callId," hangup() ending call (reason=").concat(e,")")),this.terminate($t.Local,e,!t),![Fe.Fledgling,Fe.WaitLocalMedia].includes(this.state))){var n={};(this.opponentVersion&&this.opponentVersion!==0||e!==qe.UserHangup)&&(n.reason=e),this.sendVoipEvent(V.CallHangup,n)}}reject(){if(this.state!==Fe.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(this.opponentVersion===0){b.info("Call ".concat(this.callId," reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=").concat(this.opponentVersion,")")),this.hangup(qe.UserHangup,!0);return}b.debug("Rejecting call: "+this.callId),this.terminate($t.Local,qe.UserHangup,!0),this.sendVoipEvent(V.CallReject,{})}upgradeCall(e,t){var n=this;return w(function*(){if(!(!e&&!t)&&n.opponentSupportsSDPStreamMetadata())try{b.debug("Call ".concat(n.callId," upgradeCall() upgrading call (audio=").concat(e,", video=").concat(t,")"));var i=e||n.hasLocalUserMediaAudioTrack,o=t||n.hasLocalUserMediaVideoTrack,s=yield n.client.getMediaHandler().getUserMediaStream(i,o,!1);yield n.updateLocalUsermediaStream(s,e,t)}catch(a){b.error("Call ".concat(n.callId," upgradeCall() failed to upgrade the call"),a),n.emit(Ye.Error,new mo(qe.NoUserMedia,"Failed to get camera access: ",a),n)}})()}opponentSupportsSDPStreamMetadata(){return!!this.remoteSDPStreamMetadata}isScreensharing(){return!!this.localScreensharingStream}setScreensharingEnabled(e,t){var n=this;return w(function*(){if(e&&n.isScreensharing())return b.warn("Call ".concat(n.callId," setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!")),!0;if(!e&&!n.isScreensharing())return b.warn("Call ".concat(n.callId," setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!")),!1;if(!n.opponentSupportsSDPStreamMetadata())return n.setScreensharingEnabledWithoutMetadataSupport(e,t);if(b.debug("Call ".concat(n.callId," setScreensharingEnabled() running (enabled=").concat(e,")")),e)try{var i=yield n.client.getMediaHandler().getScreensharingStream(t);return i?(n.pushNewLocalFeed(i,St.Screenshare),!0):!1}catch(l){return b.error("Call ".concat(n.callId," setScreensharingEnabled() failed to get screen-sharing stream:"),l),!1}else{var o=n.transceivers.get(si(St.Screenshare,"audio")),s=n.transceivers.get(si(St.Screenshare,"video"));for(var a of[o,s])a&&a.sender&&n.peerConn.removeTrack(a.sender);return n.client.getMediaHandler().stopScreensharingStream(n.localScreensharingStream),n.deleteFeedByStream(n.localScreensharingStream),!1}})()}setScreensharingEnabledWithoutMetadataSupport(e,t){var n=this;return w(function*(){if(b.debug("Call ".concat(n.callId," setScreensharingEnabledWithoutMetadataSupport() running (enabled=").concat(e,")")),e)try{var i,o=yield n.client.getMediaHandler().getScreensharingStream(t);if(!o)return!1;var s=o.getTracks().find(f=>f.kind==="video"),a=(i=n.transceivers.get(si(St.Usermedia,"video")))===null||i===void 0?void 0:i.sender;return a==null||a.replaceTrack(s??null),n.pushNewLocalFeed(o,St.Screenshare,!1),!0}catch(f){return b.error("Call ".concat(n.callId," setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:"),f),!1}else{var l,c,u=(l=n.localUsermediaStream)===null||l===void 0?void 0:l.getTracks().find(f=>f.kind==="video"),d=(c=n.transceivers.get(si(St.Usermedia,"video")))===null||c===void 0?void 0:c.sender;return d==null||d.replaceTrack(u??null),n.client.getMediaHandler().stopScreensharingStream(n.localScreensharingStream),n.deleteFeedByStream(n.localScreensharingStream),!1}})()}updateLocalUsermediaStream(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2&&t[2]!==void 0?t[2]:!1,s=n.localUsermediaFeed,a=i||!s.isAudioMuted()&&!n.remoteOnHold,l=o||!s.isVideoMuted()&&!n.remoteOnHold;b.log("Call ".concat(n.callId," updateLocalUsermediaStream() running (streamId=").concat(e.id,", audio=").concat(a,", video=").concat(l,")")),tr(e.getAudioTracks(),a),tr(e.getVideoTracks(),l);for(var c of n.localUsermediaStream.getTracks())n.localUsermediaStream.removeTrack(c),c.stop();for(var u of e.getTracks())n.localUsermediaStream.addTrack(u);var d=function*(){var h=si(St.Usermedia,f.kind),m=n.transceivers.get(h),E=m==null?void 0:m.sender,y=!1;if(E)try{b.info("Call ".concat(n.callId," updateLocalUsermediaStream() replacing track (id=").concat(f.id,", kind=").concat(f.kind,", streamId=").concat(e.id,", streamPurpose=").concat(s.purpose,")")),yield E.replaceTrack(f),m.direction=m.direction==="inactive"?"sendonly":"sendrecv",y=!0}catch(k){b.warn("Call ".concat(n.callId," updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead"),k)}if(!y){b.info("Call ".concat(n.callId," updateLocalUsermediaStream() adding track to peer connection (id=").concat(f.id,", kind=").concat(f.kind,", streamId=").concat(e.id,", streamPurpose=").concat(s.purpose,")"));var S=n.peerConn.addTrack(f,n.localUsermediaStream),R=n.peerConn.getTransceivers().find(k=>k.sender===S);R?n.transceivers.set(h,R):b.warn("Call ".concat(n.callId," updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!"))}};for(var f of e.getTracks())yield*d()})()}setLocalVideoMuted(e){var t=this;return w(function*(){var n;if(b.log("Call ".concat(t.callId," setLocalVideoMuted() running ").concat(e)),!e&&t.stopVideoTrackTimer!==void 0&&(clearTimeout(t.stopVideoTrackTimer),t.stopVideoTrackTimer=void 0),!(yield t.client.getMediaHandler().hasVideoDevice()))return t.isLocalVideoMuted();if(!t.hasUserMediaVideoSender&&!e){var i;return(i=t.localUsermediaFeed)===null||i===void 0||i.setAudioVideoMuted(null,e),yield t.upgradeCall(!1,!0),t.isLocalVideoMuted()}if(!e&&t.localUsermediaStream.getVideoTracks().length===0){var o=yield t.client.getMediaHandler().getUserMediaStream(!0,!0);yield t.updateLocalUsermediaStream(o)}return(n=t.localUsermediaFeed)===null||n===void 0||n.setAudioVideoMuted(null,e),t.updateMuteStatus(),yield t.sendMetadataUpdate(),e&&(t.stopVideoTrackTimer=setTimeout(()=>{for(var s of t.localUsermediaStream.getVideoTracks())s.stop(),t.localUsermediaStream.removeTrack(s)},120)),t.isLocalVideoMuted()})()}isLocalVideoMuted(){var e,t;return(e=(t=this.localUsermediaFeed)===null||t===void 0?void 0:t.isVideoMuted())!==null&&e!==void 0?e:!1}setMicrophoneMuted(e){var t=this;return w(function*(){var n;return b.log("Call ".concat(t.callId," setMicrophoneMuted() running ").concat(e)),(yield t.client.getMediaHandler().hasAudioDevice())?!e&&(!t.hasUserMediaAudioSender||!t.hasLocalUserMediaAudioTrack)?(yield t.upgradeCall(!0,!1),t.isMicrophoneMuted()):((n=t.localUsermediaFeed)===null||n===void 0||n.setAudioVideoMuted(e,null),t.updateMuteStatus(),yield t.sendMetadataUpdate(),t.isMicrophoneMuted()):t.isMicrophoneMuted()})()}isMicrophoneMuted(){var e,t;return(e=(t=this.localUsermediaFeed)===null||t===void 0?void 0:t.isAudioMuted())!==null&&e!==void 0?e:!1}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(var t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit(Ye.RemoteHoldUnhold,this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!==Fe.Connected)return!1;var e=!0;for(var t of this.peerConn.getTransceivers()){var n=["inactive","recvonly"].includes(t.currentDirection);n||(e=!1)}return e}sendDtmfDigit(e){for(var t of this.peerConn.getSenders()){var n;if(((n=t.track)===null||n===void 0?void 0:n.kind)==="audio"&&t.dtmf){t.dtmf.insertDTMF(e);return}}throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){var e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;b.log("Call ".concat(this.callId," updateMuteStatus stream ").concat(this.localUsermediaStream.id," micShouldBeMuted ").concat(e," vidShouldBeMuted ").concat(t)),tr(this.localUsermediaStream.getAudioTracks(),!e),tr(this.localUsermediaStream.getVideoTracks(),!t)}sendMetadataUpdate(){var e=this;return w(function*(){yield e.sendVoipEvent(V.CallSDPStreamMetadataChangedPrefix,{[Jo]:e.getLocalSDPStreamMetadata()})})()}gotCallFeedsForInvite(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(this.successor){this.successor.queueGotCallFeedsForAnswer(e);return}if(this.callHasEnded()){this.stopAllMedia();return}for(var n of e)this.pushLocalFeed(n);t&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=Fe.CreateOffer,b.debug("Call ".concat(this.callId," gotUserMediaForInvite() run"))}sendAnswer(){var e=this;return w(function*(){var t={answer:{sdp:e.peerConn.localDescription.sdp,type:e.peerConn.localDescription.type},[Jo]:e.getLocalSDPStreamMetadata(!0)};t.capabilities={"m.call.transferee":e.client.supportsCallTransfer,"m.call.dtmf":!1};var n=e.discardDuplicateCandidates();b.info("Call ".concat(e.callId," sendAnswer() discarding ").concat(n," candidates that will be sent in answer"));try{yield e.sendVoipEvent(V.CallAnswer,t),e.inviteOrAnswerSent=!0}catch(s){e.state=Fe.Ringing,s instanceof hr&&s.event&&e.client.cancelPendingEvent(s.event);var i=qe.SendAnswer,o="Failed to send answer";throw s.name=="UnknownDeviceError"&&(i=qe.UnknownDevices,o="Unknown devices present in the room"),e.emit(Ye.Error,new mo(i,o,s),e),s}e.sendCandidateQueue()})()}queueGotCallFeedsForAnswer(e){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.gotCallFeedsForAnswer(e)):this.responsePromiseChain=this.gotCallFeedsForAnswer(e)}mungeSdp(e,t){var n=bN(e.sdp);n.media.forEach(i=>{var o=new Map,s=new Map;for(var a of i.rtp)o.set(a.payload,a.codec),s.set(a.codec,a.payload);for(var l of t)if(l.mediaType===i.type){if(!s.has(l.codec)){b.info("Call ".concat(this.callId," mungeSdp() ignoring SDP modifications for ").concat(l.codec," as it's not present."));continue}var c=[];l.enableDtx!==void 0&&c.push("usedtx=".concat(l.enableDtx?"1":"0")),l.maxAverageBitrate!==void 0&&c.push("maxaveragebitrate=".concat(l.maxAverageBitrate));var u=!1;for(var d of i.fmtp)o.get(d.payload)===l.codec&&(u=!0,d.config+=";"+c.join(";"));u||i.fmtp.push({payload:s.get(l.codec),config:c.join(";")})}}),e.sdp=Bz(n)}createOffer(){var e=this;return w(function*(){var t=yield e.peerConn.createOffer();return e.mungeSdp(t,JC(e.isPtt)),t})()}createAnswer(){var e=this;return w(function*(){var t=yield e.peerConn.createAnswer();return e.mungeSdp(t,JC(e.isPtt)),t})()}gotCallFeedsForAnswer(e){var t=this;return w(function*(){if(!t.callHasEnded()){t.waitForLocalAVStream=!1;for(var n of e)t.pushLocalFeed(n);t.state=Fe.CreateAnswer;var i;try{t.getRidOfRTXCodecs(),i=yield t.createAnswer()}catch(o){b.debug("Call ".concat(t.callId," gotCallFeedsForAnswer() failed to create answer: "),o),t.terminate($t.Local,qe.CreateAnswer,!0);return}try{if(yield t.peerConn.setLocalDescription(i),t.callHasEnded()||(t.state=Fe.Connecting,yield new Promise(o=>{setTimeout(o,200)}),t.callHasEnded()))return;t.sendAnswer()}catch(o){b.debug("Call ".concat(t.callId," gotCallFeedsForAnswer() error setting local description!"),o),t.terminate($t.Local,qe.SetLocalDescription,!0);return}}})()}onRemoteIceCandidatesReceived(e){var t=this;return w(function*(){if(!t.callHasEnded()){var n=e.getContent(),i=n.candidates;if(!i){b.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!"));return}var o=n.version===0?null:n.party_id||null;if(t.opponentPartyId===void 0){if(o){b.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() buffering ").concat(i.length," candidates until we pick an opponent"));var s=t.remoteCandidateBuffer.get(o)||[];s.push(...i),t.remoteCandidateBuffer.set(o,s)}return}if(!t.partyIdMatches(n)){b.info("Call ".concat(t.callId," onRemoteIceCandidatesReceived() ignoring candidates from party ID ").concat(n.party_id,": we have chosen party ID ").concat(t.opponentPartyId));return}yield t.addIceCandidates(i)}})()}onAnswerReceived(e){var t=this;return w(function*(){var n=e.getContent();if(b.debug("Call ".concat(t.callId," onAnswerReceived() running (hangupParty=").concat(n.party_id,")")),t.callHasEnded()){b.debug("Call ".concat(t.callId," onAnswerReceived() ignoring answer because call has ended"));return}if(t.opponentPartyId!==void 0){b.info("Call ".concat(t.callId," onAnswerReceived() ignoring answer from party ID ").concat(n.party_id,": we already have an answer/reject from ").concat(t.opponentPartyId));return}t.chooseOpponent(e),yield t.addBufferedIceCandidates(),t.state=Fe.Connecting;var i=n[Jo];i?t.updateRemoteSDPStreamMetadata(i):b.warn("Call ".concat(t.callId," onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams"));try{t.isSettingRemoteAnswerPending=!0,yield t.peerConn.setRemoteDescription(n.answer),t.isSettingRemoteAnswerPending=!1,b.debug("Call ".concat(t.callId," onAnswerReceived() set remote description: ").concat(n.answer.type))}catch(o){t.isSettingRemoteAnswerPending=!1,b.debug("Call ".concat(t.callId," onAnswerReceived() failed to set remote description"),o),t.terminate($t.Local,qe.SetRemoteDescription,!1);return}if(t.opponentPartyId!==null)try{yield t.sendVoipEvent(V.CallSelectAnswer,{selected_party_id:t.opponentPartyId})}catch(o){b.warn("Call ".concat(t.callId," onAnswerReceived() failed to send select_answer event"),o)}})()}onSelectAnswerReceived(e){var t=this;return w(function*(){if(t.direction!==ts.Inbound){b.warn("Call ".concat(t.callId," onSelectAnswerReceived() got select_answer for an outbound call: ignoring"));return}var n=e.getContent().selected_party_id;if(n==null){b.warn("Call ".concat(t.callId," onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring"));return}n!==t.ourPartyId&&(b.info("Call ".concat(t.callId," onSelectAnswerReceived() got select_answer for party ID ").concat(n,": we are party ID ").concat(t.ourPartyId,".")),yield t.terminate($t.Remote,qe.AnsweredElsewhere,!0))})()}onNegotiateReceived(e){var t=this;return w(function*(){var n=e.getContent(),i=n.description;if(!i||!i.sdp||!i.type){b.info("Call ".concat(t.callId," onNegotiateReceived() ignoring invalid m.call.negotiate event"));return}var o=t.direction===ts.Inbound,s=!t.makingOffer&&(t.peerConn.signalingState==="stable"||t.isSettingRemoteAnswerPending),a=i.type==="offer"&&!s;if(t.ignoreOffer=!o&&a,t.ignoreOffer){b.info("Call ".concat(t.callId," onNegotiateReceived() ignoring colliding negotiate event because we're impolite"));return}var l=t.isLocalOnHold(),c=n[Jo];c?t.updateRemoteSDPStreamMetadata(c):b.warn("Call ".concat(t.callId," onNegotiateReceived() received negotiation event without SDPStreamMetadata!"));try{if(t.isSettingRemoteAnswerPending=i.type=="answer",yield t.peerConn.setRemoteDescription(i),t.isSettingRemoteAnswerPending=!1,b.debug("Call ".concat(t.callId," onNegotiateReceived() set remote description: ").concat(i.type)),i.type==="offer"){var u,d;try{t.getRidOfRTXCodecs(),d=yield t.createAnswer()}catch(p){b.debug("Call ".concat(t.callId," onNegotiateReceived() failed to create answer: "),p),t.terminate($t.Local,qe.CreateAnswer,!0);return}yield t.peerConn.setLocalDescription(d),b.debug("Call ".concat(t.callId," onNegotiateReceived() create an answer")),t.sendVoipEvent(V.CallNegotiate,{lifetime:ay,description:(u=t.peerConn.localDescription)===null||u===void 0?void 0:u.toJSON(),[Jo]:t.getLocalSDPStreamMetadata(!0)})}}catch(p){t.isSettingRemoteAnswerPending=!1,b.warn("Call ".concat(t.callId," onNegotiateReceived() failed to complete negotiation"),p)}var f=t.isLocalOnHold();l!==f&&(t.emit(Ye.LocalHoldUnhold,f,t),t.emit(Ye.HoldUnhold,f))})()}updateRemoteSDPStreamMetadata(e){this.remoteSDPStreamMetadata=wD(this.remoteSDPStreamMetadata||{},e,!0);for(var t of this.getRemoteFeeds()){var n,i=t.stream.id,o=this.remoteSDPStreamMetadata[i];t.setAudioVideoMuted(o==null?void 0:o.audio_muted,o==null?void 0:o.video_muted),t.purpose=(n=this.remoteSDPStreamMetadata[i])===null||n===void 0?void 0:n.purpose}}onSDPStreamMetadataChangedReceived(e){var t=e.getContent(),n=t[Jo];this.updateRemoteSDPStreamMetadata(n)}onAssertedIdentityReceived(e){var t=this;return w(function*(){var n=e.getContent();n.asserted_identity&&(t.remoteAssertedIdentity={id:n.asserted_identity.id,displayName:n.asserted_identity.display_name},t.emit(Ye.AssertedIdentityChanged,t))})()}callHasEnded(){return this.state===Fe.Ended}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then(()=>this.wrappedGotLocalOffer()):this.responsePromiseChain=this.wrappedGotLocalOffer()}wrappedGotLocalOffer(){var e=this;return w(function*(){e.makingOffer=!0;try{yield e.gotLocalOffer()}catch(t){e.getLocalOfferFailed(t);return}finally{e.makingOffer=!1}})()}gotLocalOffer(){var e=this;return w(function*(){if(b.debug("Call ".concat(e.callId," gotLocalOffer() running")),e.callHasEnded()){b.debug("Call ".concat(e.callId,' gotLocalOffer() ignoring newly created offer because the call has ended"'));return}var t;try{e.getRidOfRTXCodecs(),t=yield e.createOffer()}catch(u){b.debug("Call ".concat(e.callId," gotLocalOffer() failed to create offer: "),u),e.terminate($t.Local,qe.CreateOffer,!0);return}try{yield e.peerConn.setLocalDescription(t)}catch(u){b.debug("Call ".concat(e.callId," gotLocalOffer() error setting local description!"),u),e.terminate($t.Local,qe.SetLocalDescription,!0);return}if(e.peerConn.iceGatheringState==="gathering"&&(yield new Promise(u=>{setTimeout(u,200)})),!e.callHasEnded()){var n=e.state===Fe.CreateOffer?V.CallInvite:V.CallNegotiate,i={lifetime:ay};if(n===V.CallInvite&&e.invitee&&(i.invitee=e.invitee),e.state===Fe.CreateOffer){var o;i.offer=(o=e.peerConn.localDescription)===null||o===void 0?void 0:o.toJSON()}else{var s;i.description=(s=e.peerConn.localDescription)===null||s===void 0?void 0:s.toJSON()}i.capabilities={"m.call.transferee":e.client.supportsCallTransfer,"m.call.dtmf":!1},i[Jo]=e.getLocalSDPStreamMetadata(!0);var a=e.discardDuplicateCandidates();b.info("Call ".concat(e.callId," gotLocalOffer() discarding ").concat(a," candidates that will be sent in offer"));try{yield e.sendVoipEvent(n,i)}catch(u){b.error("Call ".concat(e.callId," gotLocalOffer() failed to send invite"),u),u instanceof hr&&u.event&&e.client.cancelPendingEvent(u.event);var l=qe.SignallingFailed,c="Signalling failed";e.state===Fe.CreateOffer&&(l=qe.SendInvite,c="Failed to send invite"),u.name=="UnknownDeviceError"&&(l=qe.UnknownDevices,c="Unknown devices present in the room"),e.emit(Ye.Error,new mo(l,c,u),e),e.terminate($t.Local,l,!1);return}e.sendCandidateQueue(),e.state===Fe.CreateOffer&&(e.inviteOrAnswerSent=!0,e.state=Fe.InviteSent,e.inviteTimeout=setTimeout(()=>{e.inviteTimeout=void 0,e.state===Fe.InviteSent&&e.hangup(qe.InviteTimeout,!1)},ay))}})()}getRidOfRTXCodecs(){if(!(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)){var e=this.transceivers.get(si(St.Screenshare,"video"));if(!(!e||!e.setCodecPreferences)){var t=RTCRtpReceiver.getCapabilities("video").codecs,n=RTCRtpSender.getCapabilities("video").codecs,i=[];for(var o of[...t,...n])if(o.mimeType!=="video/rtx"){i.push(o);try{e.setCodecPreferences(i)}catch(s){b.info("Working around buggy WebRTC impl: claimed to support codec but threw when setting codec preferences",o,s),i.pop()}}}}}sendVoipEvent(e,t){var n=this;return w(function*(){var i=yh(yh({},t),{},{version:u8,call_id:n.callId,party_id:n.ourPartyId,conf_id:n.groupCallId});if(n.opponentDeviceId){var o,s=n.toDeviceSeq++,a=yh(yh({},i),{},{device_id:n.client.deviceId,sender_session_id:n.client.getSessionId(),dest_session_id:n.opponentSessionId,seq:s,[tn]:_i()});n.emit(Ye.SendVoipEvent,{type:"toDevice",eventType:e,userId:n.invitee||((o=n.getOpponentMember())===null||o===void 0?void 0:o.userId),opponentDeviceId:n.opponentDeviceId,content:a},n);var l=n.invitee||n.getOpponentMember().userId;if(n.client.getUseE2eForGroupCall()){if(!n.opponentDeviceInfo){b.warn("Call ".concat(n.callId," sendVoipEvent() failed: we do not have opponentDeviceInfo"));return}yield n.client.encryptAndSendToDevices([{userId:l,deviceInfo:n.opponentDeviceInfo}],{type:e,content:a})}else yield n.client.sendToDevice(e,new Map([[l,new Map([[n.opponentDeviceId,a]])]]))}else{var c;n.emit(Ye.SendVoipEvent,{type:"sendEvent",eventType:e,roomId:n.roomId,content:i,userId:n.invitee||((c=n.getOpponentMember())===null||c===void 0?void 0:c.userId)},n),yield n.client.sendEvent(n.roomId,e,i)}})()}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,!(this.state===Fe.Ringing||!this.inviteOrAnswerSent)){var t=this.direction===ts.Inbound?500:2e3;this.candidateSendTries===0&&setTimeout(()=>{this.sendCandidateQueue()},t)}}discardDuplicateCandidates(){for(var e=0,t=[],n=0;n<this.candidateSendQueue.length;n++){var i=this.candidateSendQueue[n];i.candidate===""?t.push(i):e++}return this.candidateSendQueue=t,e}transfer(e){var t=this;return w(function*(){var n=yield t.client.getProfileInfo(e),i=ha(),o={replacement_id:ha(),target_user:{id:e,display_name:n.displayname,avatar_url:n.avatar_url},create_call:i};yield t.sendVoipEvent(V.CallReplaces,o),yield t.terminate($t.Local,qe.Transferred,!0)})()}transferToCall(e){var t=this;return w(function*(){var n,i,o=(n=e.getOpponentMember())===null||n===void 0?void 0:n.userId,s=o?yield t.client.getProfileInfo(o):void 0,a=(i=t.getOpponentMember())===null||i===void 0?void 0:i.userId,l=a?yield t.client.getProfileInfo(a):void 0,c=ha(),u={replacement_id:ha(),target_user:{id:a,display_name:l==null?void 0:l.displayname,avatar_url:l==null?void 0:l.avatar_url},await_call:c};yield e.sendVoipEvent(V.CallReplaces,u);var d={replacement_id:ha(),target_user:{id:o,display_name:s==null?void 0:s.displayname,avatar_url:s==null?void 0:s.avatar_url},create_call:c};yield t.sendVoipEvent(V.CallReplaces,d),yield t.terminate($t.Local,qe.Transferred,!0),yield e.terminate($t.Local,qe.Transferred,!0)})()}terminate(e,t,n){var i=this;return w(function*(){var o;if(!i.callHasEnded()){i.hangupParty=e,i.hangupReason=t,i.state=Fe.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[s,a]of i.removeTrackListeners)s.removeEventListener("removetrack",a);i.removeTrackListeners.clear(),i.callStatsAtEnd=yield i.collectCallStats(),i.stopAllMedia(),i.deleteAllFeeds(),i.peerConn&&i.peerConn.signalingState!=="closed"&&i.peerConn.close(),(o=i.stats)===null||o===void 0||o.removeStatsReportGatherer(i.callId),n&&i.emit(Ye.Hangup,i),i.client.callEventHandler.calls.delete(i.callId)}})()}stopAllMedia(){b.debug("Call ".concat(this.callId," stopAllMedia() running"));for(var e of this.feeds)if(e.isLocal()&&e.purpose===St.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===St.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else if(!e.isLocal()){b.debug("Call ".concat(this.callId," stopAllMedia() stopping stream (streamId=").concat(e.stream.id,")"));for(var t of e.stream.getTracks())t.stop()}}checkForErrorListener(){if(this.listeners(AD.Error).length===0)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}sendCandidateQueue(){var e=this;return w(function*(){if(!(e.candidateSendQueue.length===0||e.callHasEnded())){var t=e.candidateSendQueue;e.candidateSendQueue=[],++e.candidateSendTries;var n={candidates:t.map(a=>a.toJSON())};e.candidatesEnded&&n.candidates.push({candidate:""}),b.debug("Call ".concat(e.callId," sendCandidateQueue() attempting to send ").concat(t.length," candidates"));try{yield e.sendVoipEvent(V.CallCandidates,n),e.candidateSendTries=0,e.sendCandidateQueue()}catch(a){if(a instanceof hr&&a.event&&e.client.cancelPendingEvent(a.event),e.candidateSendQueue.push(...t),e.candidateSendTries>5){b.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates on attempt ").concat(e.candidateSendTries,". Giving up on this call."),a);var i=qe.SignallingFailed,o="Signalling failed";e.emit(Ye.Error,new mo(i,o,a),e),e.hangup(i,!1);return}var s=500*Math.pow(2,e.candidateSendTries);++e.candidateSendTries,b.debug("Call ".concat(e.callId," sendCandidateQueue() failed to send candidates. Retrying in ").concat(s,"ms"),a),setTimeout(()=>{e.sendCandidateQueue()},s)}}})()}placeCall(e,t){var n=this;return w(function*(){if(!e)throw new Error("You CANNOT start a call without audio");n.state=Fe.WaitLocalMedia;var i;try{var o,s=yield n.client.getMediaHandler().getUserMediaStream(e,t);tr(s.getAudioTracks(),!0),tr(s.getVideoTracks(),!0),i=new bo({client:n.client,roomId:n.roomId,userId:n.client.getUserId(),deviceId:(o=n.client.getDeviceId())!==null&&o!==void 0?o:void 0,stream:s,purpose:St.Usermedia,audioMuted:!1,videoMuted:!1})}catch(a){n.getUserMediaFailed(a);return}try{yield n.placeCallWithCallFeeds([i])}catch(a){n.placeCallFailed(a);return}})()}placeCallWithCallFeeds(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;n.checkForErrorListener(),n.direction=ts.Outbound,yield n.initOpponentCrypto(),n.client.callEventHandler.calls.set(n.callId,n);var o=yield n.client.checkTurnServers();o||b.warn("Call ".concat(n.callId," placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...")),n.peerConn=n.createPeerConnection(),n.emit(Ye.PeerConnectionCreated,n.peerConn,n),n.gotCallFeedsForInvite(e,i)})()}createPeerConnection(){var e,t=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers.length?this.turnServers:void 0,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),t.addEventListener("signalingstatechange",this.onSignallingStateChanged),t.addEventListener("icecandidate",this.gotLocalIceCandidate),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t.addEventListener("track",this.onTrack),t.addEventListener("negotiationneeded",this.onNegotiationNeeded),t.addEventListener("datachannel",this.onDataChannel);var n=this.getOpponentMember(),i=n?n.userId:"unknown";return(e=this.stats)===null||e===void 0||e.addStatsReportGatherer(this.callId,i,t),t}partyIdMatches(e){var t=e.version===0?null:e.party_id||null;return t===this.opponentPartyId}chooseOpponent(e){var t,n=e.getContent();if(b.debug("Call ".concat(this.callId," chooseOpponent() running (partyId=").concat(n.party_id,")")),this.opponentVersion=n.version,this.opponentVersion===0?this.opponentPartyId=null:this.opponentPartyId=n.party_id||null,this.opponentCaps=n.capabilities||{},this.opponentMember=(t=this.client.getRoom(this.roomId).getMember(e.getSender()))!==null&&t!==void 0?t:void 0,this.opponentMember){var i;(i=this.stats)===null||i===void 0||i.updateOpponentMember(this.callId,this.opponentMember.userId)}}addBufferedIceCandidates(){var e=this;return w(function*(){var t=e.remoteCandidateBuffer.get(e.opponentPartyId);t&&(b.info("Call ".concat(e.callId," addBufferedIceCandidates() adding ").concat(t.length," buffered candidates for opponent ").concat(e.opponentPartyId)),yield e.addIceCandidates(t)),e.remoteCandidateBuffer.clear()})()}addIceCandidates(e){var t=this;return w(function*(){for(var n of e){(n.sdpMid===null||n.sdpMid===void 0)&&(n.sdpMLineIndex===null||n.sdpMLineIndex===void 0)?b.debug("Call ".concat(t.callId," addIceCandidates() got remote ICE end-of-candidates")):b.debug("Call ".concat(t.callId," addIceCandidates() got remote ICE candidate (sdpMid=").concat(n.sdpMid,", candidate=").concat(n.candidate,")"));try{yield t.peerConn.addIceCandidate(n)}catch(i){t.ignoreOffer?b.debug("Call ".concat(t.callId," addIceCandidates() failed to add remote ICE candidate because ignoring offer"),i):b.info("Call ".concat(t.callId," addIceCandidates() failed to add remote ICE candidate"),i)}}})()}get hasPeerConnection(){return!!this.peerConn}initStats(e){this.stats=e,this.stats.start()}}function tr(r,e){for(var t of r)t.enabled=e}function qb(){if(typeof window>"u"||typeof document>"u")return!1;try{var r=!!(window.RTCPeerConnection||window.RTCSessionDescription||window.RTCIceCandidate||navigator.mediaDevices);if(!r)return b.error("WebRTC is not supported in this browser / environment"),!1}catch(e){return b.error("Exception thrown when trying to access WebRTC",e),!1}return!0}function Kd(r,e,t){if(!qb())return null;var n=t?t.forceTURN:!1,i={client:r,roomId:e,invitee:t==null?void 0:t.invitee,turnServers:r.getTurnServers(),forceTURN:r.forceTURN||n,opponentDeviceId:t==null?void 0:t.opponentDeviceId,opponentSessionId:t==null?void 0:t.opponentSessionId,groupCallId:t==null?void 0:t.groupCallId},o=new v8(i);return r.reEmitter.reEmit(o,Object.values(Ye)),o}var ks=function(r){return r.DontNotify="dont_notify",r.Notify="notify",r.Coalesce="coalesce",r}({}),Uw=function(r){return r.Highlight="highlight",r.Sound="sound",r}({}),m8=function(r){return r.ExactEquals="==",r.LessThan="<",r.GreaterThan=">",r.GreaterThanOrEqual=">=",r.LessThanOrEqual="<=",r}({}),g8="2";function y8(r){return r==="==2"||r==="2"}var rr=function(r){return r.EventMatch="event_match",r.EventPropertyIs="event_property_is",r.EventPropertyContains="event_property_contains",r.ContainsDisplayName="contains_display_name",r.RoomMemberCount="room_member_count",r.SenderNotificationPermission="sender_notification_permission",r.CallStarted="call_started",r.CallStartedPrefix="org.matrix.msc3914.call_started",r}({}),Er=function(r){return r.Override="override",r.ContentSpecific="content",r.RoomSpecific="room",r.SenderSpecific="sender",r.Underride="underride",r}({}),br=function(r){return r.Master=".m.rule.master",r.IsUserMention=".m.rule.is_user_mention",r.IsRoomMention=".m.rule.is_room_mention",r.ContainsDisplayName=".m.rule.contains_display_name",r.ContainsUserName=".m.rule.contains_user_name",r.AtRoomNotification=".m.rule.roomnotif",r.DM=".m.rule.room_one_to_one",r.EncryptedDM=".m.rule.encrypted_room_one_to_one",r.Message=".m.rule.message",r.EncryptedMessage=".m.rule.encrypted",r.InviteToSelf=".m.rule.invite_for_me",r.MemberEvent=".m.rule.member_event",r.IncomingCall=".m.rule.call",r.SuppressNotices=".m.rule.suppress_notices",r.Tombstone=".m.rule.tombstone",r.PollStart=".m.rule.poll_start",r.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",r.PollEnd=".m.rule.poll_end",r.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",r.PollStartOneToOne=".m.rule.poll_start_one_to_one",r.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",r.PollEndOneToOne=".m.rule.poll_end_one_to_one",r.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one",r}({});function XC(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function QC(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?XC(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):XC(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var ZC=[Er.Override,Er.ContentSpecific,Er.RoomSpecific,Er.SenderSpecific,Er.Underride],S8={".m.rule.is_room_mention":{rule_id:".m.rule.is_room_mention",default:!0,enabled:!0,conditions:[{kind:rr.EventPropertyIs,key:"content.m\\.mentions.room",value:!0},{kind:rr.SenderNotificationPermission,key:"room"}],actions:[ks.Notify,{set_tweak:Uw.Highlight}]},".m.rule.reaction":{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:rr.EventMatch,key:"type",pattern:"m.reaction"}],actions:[ks.DontNotify]},".org.matrix.msc3786.rule.room.server_acl":{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:rr.EventMatch,key:"type",pattern:V.RoomServerAcl},{kind:rr.EventMatch,key:"state_key",pattern:""}],actions:[]}},jw=Symbol("UserDefinedRules"),b8=[br.Master,jw,br.SuppressNotices,br.InviteToSelf,br.MemberEvent,br.IsUserMention,br.ContainsDisplayName,br.IsRoomMention,br.AtRoomNotification,br.Tombstone,".m.rule.reaction",".m.rule.room.server_acl",".org.matrix.msc3786.rule.room.server_acl",".m.rule.suppress_edits"],_8={".org.matrix.msc3914.rule.room.call":{rule_id:".org.matrix.msc3914.rule.room.call",default:!0,enabled:!0,conditions:[{kind:rr.EventMatch,key:"type",pattern:"org.matrix.msc3401.call"},{kind:rr.CallStarted}],actions:[ks.Notify,{set_tweak:Uw.Sound,value:"default"}]}},E8=[jw,br.IncomingCall,".org.matrix.msc3914.rule.room.call",br.EncryptedDM,br.DM,br.Message,br.EncryptedMessage];function ek(r,e,t,n){var i=e.filter(p=>p.default),o=e.filter(p=>!p.default);function s(p){p===jw?l.push(...o):p in t?(b.warn("Adding default global ".concat(r," push rule ").concat(p)),l.push(t[p])):b.warn("Missing default global ".concat(r," push rule ").concat(p))}var a=0,l=[];for(var c of i){var u=n.indexOf(c.rule_id);if(u===-1){l.push(c);continue}for(;u>a;){var d=n[a];s(d),a+=1}l.push(c),a+=1}for(var f of n.slice(a))s(f);return l}class hi{constructor(e){this.client=e,v(this,"parsedKeys",new Map)}static actionListToActionsObject(e){var t={notify:!1,tweaks:{}};for(var n of e)n===ks.Notify?t.notify=!0:typeof n=="object"&&(n.value===void 0&&(n.value=!0),t.tweaks[n.set_tweak]=n.value);return t}static rewriteDefaultRules(e){var t=JSON.parse(JSON.stringify(e));return t||(t={}),t.global||(t.global={}),t.global.override||(t.global.override=[]),t.global.underride||(t.global.underride=[]),t.global.override=ek(Er.Override,t.global.override,S8,b8),t.global.underride=ek(Er.Underride,t.global.underride,_8,E8),t}updateCachedPushRuleKeys(e){e||(e={}),e.global||(e.global={}),e.global.override||(e.global.override=[]),e.global.room||(e.global.room=[]),e.global.sender||(e.global.sender=[]),e.global.underride||(e.global.underride=[]);var t=new Set(this.parsedKeys.keys());for(var n of[e.global.override,e.global.room,e.global.sender,e.global.underride])for(var i of n)if(i.conditions)for(var o of i.conditions)o.kind===rr.EventMatch&&(t.delete(o.key),this.parsedKeys.set(o.key,hi.partsForDottedKey(o.key)));t.forEach(s=>this.parsedKeys.delete(s))}matchingRuleFromKindSet(e,t){for(var n of ZC){var i=t[n];if(i){for(var o of i)if(o.enabled){var s=this.templateRuleToRaw(n,o);if(s&&this.ruleMatchesEvent(s,e))return QC(QC({},o),{},{kind:n})}}}return null}templateRuleToRaw(e,t){var n={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case Er.Underride:case Er.Override:n.conditions=t.conditions;break;case Er.RoomSpecific:if(!t.rule_id)return null;n.conditions.push({kind:rr.EventMatch,key:"room_id",value:t.rule_id});break;case Er.SenderSpecific:if(!t.rule_id)return null;n.conditions.push({kind:rr.EventMatch,key:"user_id",value:t.rule_id});break;case Er.ContentSpecific:if(!t.pattern)return null;n.conditions.push({kind:rr.EventMatch,key:"content.body",pattern:t.pattern});break}return n}eventFulfillsCondition(e,t){switch(e.kind){case rr.EventMatch:return this.eventFulfillsEventMatchCondition(e,t);case rr.EventPropertyIs:return this.eventFulfillsEventPropertyIsCondition(e,t);case rr.EventPropertyContains:return this.eventFulfillsEventPropertyContains(e,t);case rr.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,t);case rr.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,t);case rr.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,t);case rr.CallStarted:case rr.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(e,t)}return!1}eventFulfillsSenderNotifPermCondition(e,t){var n=e.key;if(!n)return!1;var i=this.client.getRoom(t.getRoomId());return i!=null&&i.currentState?i.currentState.mayTriggerNotifOfType(n,t.getSender()):!1}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;var n=this.client.getRoom(t.getRoomId());if(!n||!n.currentState||!n.currentState.members)return!1;var i=n.currentState.getJoinedMemberCount(),o=e.is.match(/^([=<>]*)(\d*)$/);if(!o)return!1;var s=o[1],a=parseInt(o[2]);if(isNaN(a))return!1;switch(s){case"":case"==":return i==a;case"<":return i<a;case">":return i>a;case"<=":return i<=a;case">=":return i>=a;default:return!1}}eventFulfillsDisplayNameCondition(e,t){var n,i=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(i=t.getClearContent()),!i||!i.body||typeof i.body!="string")return!1;var o=this.client.getRoom(t.getRoomId()),s=o==null||(n=o.currentState)===null||n===void 0?void 0:n.getMember(this.client.credentials.userId);if(!s)return!1;var a=s.name,l=new RegExp("(^|\\W)"+bD(a)+"(\\W|$)","i");return i.body.search(l)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;var n=this.valueForDottedKey(e.key,t);if(typeof n!="string")return!1;if(e.value)return e.value===n;if(typeof e.pattern!="string")return!1;var i=e.key==="content.body"?this.createCachedRegex("(^|\\W)",e.pattern,"(\\W|$)"):this.createCachedRegex("^",e.pattern,"$");return!!n.match(i)}eventFulfillsEventPropertyIsCondition(e,t){return!e.key||e.value===void 0?!1:e.value===this.valueForDottedKey(e.key,t)}eventFulfillsEventPropertyContains(e,t){if(!e.key||e.value===void 0)return!1;var n=this.valueForDottedKey(e.key,t);return Array.isArray(n)?n.includes(e.value):!1}eventFulfillsCallStartedCondition(e,t){return["m.ring","m.prompt"].includes(t.getContent()["m.intent"])&&!("m.terminated"in t.getContent())&&(t.getPrevContent()["m.terminated"]!==t.getContent()["m.terminated"]||Va(t.getPrevContent(),{}))}createCachedRegex(e,t,n){return hi.cachedGlobToRegex[t]||(hi.cachedGlobToRegex[t]=new RegExp(e+_D(t)+n,"i")),hi.cachedGlobToRegex[t]}static partsForDottedKey(e){var t=[],n="",i=!1;for(var o of e){if(i){o==="\\"||o==="."?n+=o:n+="\\"+o,i=!1;continue}o=="."?(t.push(n),n=""):o=="\\"?i=!0:n+=o}return i&&(n+="\\"),t.push(n),t}valueForDottedKey(e,t){var n=this.parsedKeys.get(e);n===void 0&&(n=hi.partsForDottedKey(e),this.parsedKeys.set(e,n));var i,o=n[0],s=0;for(o==="content"?(i=t.getContent(),++s):o==="type"?(i=t.getType(),++s):i=t.event;s<n.length;++s){if(ED(i))return;var a=n[s];i=i[a]}return i}matchingRuleForEventWithRulesets(e,t){return!t||e.getSender()===this.client.getSafeUserId()?null:this.matchingRuleFromKindSet(e,t.global)}pushActionsForEventAndRulesets(e,t){var n=this.matchingRuleForEventWithRulesets(e,t);if(!n)return{};var i=hi.actionListToActionsObject(n.actions);return i.tweaks.highlight===void 0&&(i.tweaks.highlight=n.kind==Er.ContentSpecific),{actions:i,rule:n}}ruleMatchesEvent(e,t){var n;return this.client.supportsIntentionalMentions()&&t.getContent()["m.mentions"]!==void 0&&(e.rule_id===br.ContainsUserName||e.rule_id===br.ContainsDisplayName||e.rule_id===br.AtRoomNotification)?!1:!((n=e.conditions)!==null&&n!==void 0&&n.some(i=>!this.eventFulfillsCondition(i,t)))}actionsForEvent(e){var{actions:t}=this.pushActionsForEventAndRulesets(e,this.client.pushRules);return t||{}}actionsAndRuleForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){var t,n=this.getPushRuleAndKindById(e);return(t=n==null?void 0:n.rule)!==null&&t!==void 0?t:null}getPushRuleAndKindById(e){for(var t of["global"]){var n;if(((n=this.client.pushRules)===null||n===void 0?void 0:n[t])!==void 0){for(var i of ZC)if(this.client.pushRules[t][i]!==void 0){for(var o of this.client.pushRules[t][i])if(o.rule_id===e)return{rule:o,kind:i}}}}return null}}v(hi,"cachedGlobToRegex",{});var fv=["v1.1","v1.2","v1.3","v1.4","v1.5","v1.6","v1.7","v1.8","v1.9"];fv[0];fv[fv.length-1];var Nn=function(r){return r.SUCCESS="SUCCESS",r.IGNORE="IGNORE",r.PROMPT="PROMPT",r.FAIL_PROMPT="FAIL_PROMPT",r.FAIL_ERROR="FAIL_ERROR",r}({}),ni=function(r){return r.Invalid="Invalid homeserver discovery response",r.GenericFailure="Failed to get autodiscovery configuration from server",r.InvalidHsBaseUrl="Invalid base_url for m.homeserver",r.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",r.InvalidIsBaseUrl="Invalid base_url for m.identity_server",r.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",r.InvalidIs="Invalid identity server discovery response",r.MissingWellknown="No .well-known JSON file found",r.InvalidJson="Invalid JSON",r.UnsupportedHomeserverSpecVersion="The homeserver does not meet the version requirements",r}({});class Ke{static fromDiscoveryConfig(e){var t=this;return w(function*(){var n,i={"m.homeserver":{state:Ke.FAIL_ERROR,error:Ke.ERROR_INVALID,base_url:null},"m.identity_server":{state:Ke.PROMPT,error:null,base_url:null}};if(!(e!=null&&e["m.homeserver"]))return b.error("No m.homeserver key in config"),i["m.homeserver"].state=Ke.FAIL_PROMPT,i["m.homeserver"].error=Ke.ERROR_INVALID,Promise.resolve(i);if(!e["m.homeserver"].base_url)return b.error("No m.homeserver base_url in config"),i["m.homeserver"].state=Ke.FAIL_PROMPT,i["m.homeserver"].error=Ke.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var o=t.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!o)return b.error("Invalid base_url for m.homeserver"),i["m.homeserver"].error=Ke.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);var s=yield t.fetchWellKnownObject("".concat(o,"/_matrix/client/versions"));if(!s||!Array.isArray((n=s.raw)===null||n===void 0?void 0:n.versions))return b.error("Invalid /versions response"),i["m.homeserver"].error=Ke.ERROR_INVALID_HOMESERVER,i["m.homeserver"].base_url=o,Promise.resolve(i);var a=new Set(s.raw.versions),l=!1;for(var c of fv)if(a.has(c)){l=!0;break}if(!l)return b.error("Homeserver does not meet version requirements"),i["m.homeserver"].error=Ke.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION,i["m.homeserver"].base_url=o,Promise.resolve(i);i["m.homeserver"]={state:Ke.SUCCESS,error:null,base_url:o};var u="";if(e["m.identity_server"]){var d={"m.homeserver":i["m.homeserver"],"m.identity_server":{state:Ke.FAIL_PROMPT,error:Ke.ERROR_INVALID_IS,base_url:null}};if(u=t.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!u)return b.error("Invalid base_url for m.identity_server"),d["m.identity_server"].error=Ke.ERROR_INVALID_IS_BASE_URL,Promise.resolve(d);var f=yield t.fetchWellKnownObject("".concat(u,"/_matrix/identity/v2"));if(!(f!=null&&f.raw)||f.action!==Nn.SUCCESS)return b.error("Invalid /v2 response"),d["m.identity_server"].error=Ke.ERROR_INVALID_IDENTITY_SERVER,d["m.identity_server"].base_url=u,Promise.resolve(d)}return u&&u.toString().length>0&&(i["m.identity_server"]={state:Ke.SUCCESS,error:null,base_url:u}),Object.keys(e).forEach(p=>{if(p==="m.homeserver"||p==="m.identity_server"){var h=["error","state","base_url"];for(var m of Object.keys(e[p]))h.includes(m)||(i[p][m]=e[p][m])}else i[p]=e[p]}),Promise.resolve(i)})()}static findClientConfig(e){var t=this;return w(function*(){if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");var n={"m.homeserver":{state:Ke.FAIL_ERROR,error:Ke.ERROR_INVALID,base_url:null},"m.identity_server":{state:Ke.PROMPT,error:null,base_url:null}},i=e.includes("://")?e:"https://".concat(e),o=yield t.fetchWellKnownObject("".concat(i,"/.well-known/matrix/client"));return!o||o.action!==Nn.SUCCESS?(b.error("No response or error when parsing .well-known"),o.reason&&b.error(o.reason),o.action===Nn.IGNORE?n["m.homeserver"]={state:Ke.PROMPT,error:null,base_url:null}:(n["m.homeserver"].state=Ke.FAIL_PROMPT,n["m.homeserver"].error=Ke.ERROR_INVALID),Promise.resolve(n)):Ke.fromDiscoveryConfig(o.raw)})()}static getRawClientConfig(e){var t=this;return w(function*(){var n;if(!e||typeof e!="string"||e.length===0)throw new Error("'domain' must be a string of non-zero length");var i=yield t.fetchWellKnownObject("https://".concat(e,"/.well-known/matrix/client"));return i?(n=i.raw)!==null&&n!==void 0?n:{}:{}})()}static sanitizeWellKnownUrl(e){if(!e)return!1;try{var t,n;try{n=new URL(e)}catch(a){b.error("Could not parse url",a)}if(!((t=n)!==null&&t!==void 0&&t.hostname)||n.protocol!=="http:"&&n.protocol!=="https:")return!1;var i=n.port?":".concat(n.port):"",o=n.pathname?n.pathname:"",s="".concat(n.protocol,"//").concat(n.hostname).concat(i).concat(o);return s.endsWith("/")&&(s=s.substring(0,s.length-1)),s}catch(a){return b.error(a),!1}}static fetch(e,t){return this.fetchFn?this.fetchFn(e,t):globalThis.fetch(e,t)}static setFetchFn(e){Ke.fetchFn=e}static fetchWellKnownObject(e){return w(function*(){var t;try{if(t=yield Ke.fetch(e,{method:Z.Get,signal:wm(5e3)}),t.status===404)return{raw:{},action:Nn.IGNORE,reason:Ke.ERROR_MISSING_WELLKNOWN};if(!t.ok)return{raw:{},action:Nn.FAIL_PROMPT,reason:"General failure"}}catch(s){var n=s,i="";return typeof n=="object"&&(i=n==null?void 0:n.message),{error:n,raw:{},action:Nn.FAIL_PROMPT,reason:i||"General failure"}}try{return{raw:yield t.json(),action:Nn.SUCCESS}}catch(s){var o=s;return{error:o,raw:{},action:Nn.FAIL_PROMPT,reason:(o==null?void 0:o.name)==="SyntaxError"?Ke.ERROR_INVALID_JSON:Ke.ERROR_INVALID}}})()}}v(Ke,"ERROR_INVALID",ni.Invalid);v(Ke,"ERROR_GENERIC_FAILURE",ni.GenericFailure);v(Ke,"ERROR_INVALID_HS_BASE_URL",ni.InvalidHsBaseUrl);v(Ke,"ERROR_INVALID_HOMESERVER",ni.InvalidHomeserver);v(Ke,"ERROR_INVALID_IS_BASE_URL",ni.InvalidIsBaseUrl);v(Ke,"ERROR_INVALID_IDENTITY_SERVER",ni.InvalidIdentityServer);v(Ke,"ERROR_INVALID_IS",ni.InvalidIs);v(Ke,"ERROR_MISSING_WELLKNOWN",ni.MissingWellknown);v(Ke,"ERROR_INVALID_JSON",ni.InvalidJson);v(Ke,"ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION",ni.UnsupportedHomeserverSpecVersion);v(Ke,"ALL_ERRORS",Object.keys(ni));v(Ke,"FAIL_ERROR",Nn.FAIL_ERROR);v(Ke,"FAIL_PROMPT",Nn.FAIL_PROMPT);v(Ke,"PROMPT",Nn.PROMPT);v(Ke,"SUCCESS",Nn.SUCCESS);v(Ke,"fetchFn",void 0);var tk=/[\\\"\x00-\x1F]/g,Ko={};for(var Sh=0;Sh<32;++Sh)Ko[String.fromCharCode(Sh)]="\\U"+("0000"+Sh.toString(16)).slice(-4).toUpperCase();Ko["\b"]="\\b";Ko[" "]="\\t";Ko[`
293
- `]="\\n";Ko["\f"]="\\f";Ko["\r"]="\\r";Ko['"']='\\"';Ko["\\"]="\\\\";function RN(r){return tk.lastIndex=0,r.replace(tk,function(e){return Ko[e]})}function Fw(r){switch(typeof r){case"string":return'"'+RN(r)+'"';case"number":return isFinite(r)?r:"null";case"boolean":return r;case"object":return r===null?"null":Array.isArray(r)?w8(r):T8(r);default:throw new Error("Cannot stringify: "+typeof r)}}function w8(r){for(var e="[",t="",n=0;n<r.length;++n)t+=e,e=",",t+=Fw(r[n]);return e!=","?"[]":t+"]"}function T8(r){var e="{",t="",n=Object.keys(r);n.sort();for(var i=0;i<n.length;++i){var o=n[i];t+=e+'"'+RN(o)+'":',e=",",t+=Fw(r[o])}return e!=","?"{}":t+"}"}var R8={stringify:Fw};const Io=qa(R8);function rk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function C8(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?rk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):rk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Im=function(r){return r.Olm="m.olm.v1.curve25519-aes-sha2",r.Megolm="m.megolm.v1.aes-sha2",r.MegolmBackup="m.megolm_backup.v1.curve25519-aes-sha2",r}(Im||{}),wr=Im.Olm,bn=Im.Megolm,k8=Im.MegolmBackup;function Ns(r,e,t,n,i,o,s){return Gb.apply(this,arguments)}function Gb(){return Gb=w(function*(r,e,t,n,i,o,s){var a=o.getIdentityKey(),l=yield n.getSessionIdForDevice(a);if(l===null){b.log("[olmlib.encryptMessageForDevice] Unable to find Olm session for device "+"".concat(i,":").concat(o.deviceId));return}b.log("[olmlib.encryptMessageForDevice] Using Olm session ".concat(l," for device ")+"".concat(i,":").concat(o.deviceId));var c=C8({sender:e,sender_device:t,keys:{ed25519:n.deviceEd25519Key},recipient:i,recipient_keys:{ed25519:o.getFingerprint()}},s);r[a]=yield n.encryptMessage(a,l,JSON.stringify(c))}),Gb.apply(this,arguments)}function CN(r,e,t){return Hb.apply(this,arguments)}function Hb(){return Hb=w(function*(r,e,t){var n=new Gt(()=>[]),i=new Gt(()=>new Map),o=[],s=function*(u){var d=function*(h){var m=h.deviceId,E=h.getIdentityKey();o.push(w(function*(){var y=yield r.getSessionIdForDevice(E,!0);y===null?n.getOrCreate(u).push(h):i.getOrCreate(u).set(m,{device:h,sessionId:y})})())};for(var f of l)yield*d(f)};for(var[a,l]of Object.entries(t))yield*s(a);return yield Promise.all(o),[n,i]}),Hb.apply(this,arguments)}function xo(r,e,t){return zb.apply(this,arguments)}function zb(){return zb=w(function*(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,i=arguments.length>4?arguments[4]:void 0,o=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&arguments[6]!==void 0?arguments[6]:b,a=[],l=new Map,c=new Map;for(var u of t.values()){var d=function*(){var re=f.getIdentityKey();if(re===r.deviceCurve25519Key)return 1;r.sessionsInProgress[re]||(r.sessionsInProgress[re]=new Promise(ae=>{c.set(re,q=>{delete r.sessionsInProgress[re],ae(q)})}))};for(var f of u)yield*d()}for(var[p,h]of t){var m=new Map;l.set(p,m);for(var E of h){var y=E.deviceId,S=E.getIdentityKey();if(S===r.deviceCurve25519Key){s.info("Attempted to start session with ourself! Ignoring"),m.set(y,{device:E,sessionId:null});continue}var R="for ".concat(S," (").concat(p,":").concat(y,")"),k=yield r.getSessionIdForDevice(S,!!c.get(S),s),x=c.get(S);k!==null&&x&&x(),(k===null||n)&&(n?s.info("Forcing new Olm session ".concat(R)):s.info("Making new Olm session ".concat(R)),a.push([p,y])),m.set(y,{device:E,sessionId:k})}}if(a.length===0)return l;var T="signed_curve25519",O,C="one-time keys for ".concat(a.length," devices");try{s.debug("Claiming ".concat(C)),O=yield e.claimOneTimeKeys(a,T,i),s.debug("Claimed ".concat(C))}catch(oe){for(var N of c.values())N();throw s.debug("Failed to claim ".concat(C),oe,a),oe}o&&"failures"in O&&o.push(...Object.keys(O.failures));var F=O.one_time_keys||{},H=[],ie=function*(re){var ae=F[re]||{},q=function*(){var Y,le=Q.deviceId,B=Q.getIdentityKey();if(B===r.deviceCurve25519Key||(Y=l.get(re))!==null&&Y!==void 0&&(Y=Y.get(le))!==null&&Y!==void 0&&Y.sessionId&&!n)return 0;var W=ae[le]||{},A=null;for(var D in W)D.indexOf(T+":")===0&&(A=W[D]);if(!A){var P;return s.warn("No one-time keys (alg=".concat(T,") ")+"for device ".concat(re,":").concat(le)),(P=c.get(B))===null||P===void 0||P(),0}H.push(I8(r,A,re,Q).then(M=>{var I,j;(I=c.get(B))===null||I===void 0||I(M??void 0);var U=(j=l.get(re))===null||j===void 0?void 0:j.get(le);U&&(U.sessionId=M)},M=>{var I;throw(I=c.get(B))===null||I===void 0||I(),M}))},z;for(var Q of X)z=yield*q()};for(var[$,X]of t)yield*ie($);return C="Olm sessions for ".concat(H.length," devices"),s.debug("Starting ".concat(C)),yield Promise.all(H),s.debug("Started ".concat(C)),l}),zb.apply(this,arguments)}function I8(r,e,t,n){return Yb.apply(this,arguments)}function Yb(){return Yb=w(function*(r,e,t,n){var i=n.deviceId;try{yield Ec(r,e,t,i,n.getFingerprint())}catch(s){return b.error("Unable to verify signature on one-time key for device "+t+":"+i+":",s),null}var o;try{o=yield r.createOutboundSession(n.getIdentityKey(),e.key)}catch(s){return b.error("Error starting olm session with device "+t+":"+i+": "+s),null}return b.log("Started new olm sessionid "+o+" for device "+t+":"+i),o}),Yb.apply(this,arguments)}function Ec(r,e,t,n,i){return Jb.apply(this,arguments)}function Jb(){return Jb=w(function*(r,e,t,n,i){var o="ed25519:"+n,s=e.signatures||{},a=s[t]||{},l=a[o];if(!l)throw Error("No signature");var c=Object.assign({},e);"unsigned"in c&&delete c.unsigned,delete c.signatures;var u=Io.stringify(c);r.verifySignature(i,u,l)}),Jb.apply(this,arguments)}function np(r,e,t,n){var i=!1;if(e instanceof Uint8Array){var o=new globalThis.Olm.PkSigning;n=o.init_with_seed(e),e=o,i=!0}var s=r.signatures||{};delete r.signatures;var a=r.unsigned;r.unsigned&&delete r.unsigned;try{var l=s[t]||{};return s[t]=l,l["ed25519:"+n]=e.sign(Io.stringify(r))}finally{r.signatures=s,a&&(r.unsigned=a),i&&e.free()}}function El(r,e,t){var n="ed25519:"+e;if(!(r.signatures&&r.signatures[t]&&r.signatures[t][n]))throw new Error("No signature");var i=r.signatures[t][n],o=new globalThis.Olm.Utility,s=r.signatures;delete r.signatures;var a=r.unsigned;r.unsigned&&delete r.unsigned;try{o.ed25519_verify(e,Io.stringify(r),i)}finally{r.signatures=s,a&&(r.unsigned=a),o.free()}}function Bw(r){return r.getSenderKey()?r.getWireType()!==V.RoomMessageEncrypted||!["m.olm.v1.curve25519-aes-sha2"].includes(r.getWireContent().algorithm)?(b.error("Event was not encrypted using an appropriate algorithm"),!1):!0:(b.error("Event has no sender key (not encrypted?)"),!1)}const x8=Object.freeze(Object.defineProperty({__proto__:null,MEGOLM_ALGORITHM:bn,MEGOLM_BACKUP_ALGORITHM:k8,OLM_ALGORITHM:wr,encryptMessageForDevice:Ns,ensureOlmSessionsForDevices:xo,getExistingOlmSessions:CN,isOlmEncrypted:Bw,pkSign:np,pkVerify:El,verifySignature:Ec},Symbol.toStringTag,{value:"Module"}));var Xb=function(r){return r.IS="SERVICE_TYPE_IS",r.IM="SERVICE_TYPE_IM",r}({}),Rn="crypto.",nk=Rn+"migration",ly=Rn+"account",ik=Rn+"cross_signing_keys",ok=Rn+"notified_error_devices",sk=Rn+"device_data",rs=Rn+"inboundgroupsessions/",O8=Rn+"inboundgroupsessions.withheld/",P8=Rn+"rooms/",ea=Rn+"sessionsneedingbackup";function ta(r){return Rn+"sessions/"+r}function ak(r){return Rn+"session.problems/"+r}function bh(r,e){return rs+r+"/"+e}function lk(r,e){return O8+r+"/"+e}function ck(r){return P8+r}class xm extends Sm{static exists(e){for(var t=e.length,n=0;n<t;n++){var i;if((i=e.key(n))!==null&&i!==void 0&&i.startsWith(Rn))return!0}return!1}constructor(e){super(),this.store=e}containsData(){var e=this;return w(function*(){return xm.exists(e.store)})()}getMigrationState(){var e=this;return w(function*(){var t;return(t=zt(e.store,nk))!==null&&t!==void 0?t:Sc.NOT_STARTED})()}setMigrationState(e){var t=this;return w(function*(){hn(t.store,nk,e)})()}countEndToEndSessions(e,t){for(var n=0,i=0;i<this.store.length;++i){var o=this.store.key(i);if(o!=null&&o.startsWith(ta(""))){var s=zt(this.store,o);n+=Object.keys(s??{}).length}}t(n)}_getEndToEndSessions(e){var t=zt(this.store,ta(e)),n={};for(var[i,o]of Object.entries(t||{}))typeof o=="string"?n[i]={session:o}:n[i]=o;return n}getEndToEndSession(e,t,n,i){var o=this._getEndToEndSessions(e);i(o[t]||{})}getEndToEndSessions(e,t,n){n(this._getEndToEndSessions(e)||{})}getAllEndToEndSessions(e,t){for(var n=0;n<this.store.length;++n){var i;if((i=this.store.key(n))!==null&&i!==void 0&&i.startsWith(ta(""))){var o=this.store.key(n).split("/")[1];for(var s of Object.values(this._getEndToEndSessions(o)))t(s)}}}storeEndToEndSession(e,t,n,i){var o=this._getEndToEndSessions(e)||{};o[t]=n,hn(this.store,ta(e),o)}storeEndToEndSessionProblem(e,t,n){var i=this;return w(function*(){var o=ak(e),s=zt(i.store,o)||[];s.push({type:t,fixed:n,time:Date.now()}),s.sort((a,l)=>a.time-l.time),hn(i.store,o,s)})()}getEndToEndSessionProblem(e,t){var n=this;return w(function*(){var i=ak(e),o=zt(n.store,i)||[];if(!o.length)return null;var s=o[o.length-1];for(var a of o)if(a.time>t)return Object.assign({},a,{fixed:s.fixed});return s.fixed?null:s})()}filterOutNotifiedErrorDevices(e){var t=this;return w(function*(){var n=zt(t.store,ok)||{},i=[];for(var o of e){var{userId:s,deviceInfo:a}=o;s in n?a.deviceId in n[s]||(i.push(o),Qi(n[s],a.deviceId,!0)):(i.push(o),Qi(n,s,{[a.deviceId]:!0}))}return hn(t.store,ok,n),i})()}getEndToEndSessionsBatch(){var e=this;return w(function*(){for(var t=[],n=0;n<e.store.length;++n){var i;if((i=e.store.key(n))!==null&&i!==void 0&&i.startsWith(ta(""))){var o=e.store.key(n).split("/")[1];for(var s of Object.values(e._getEndToEndSessions(o)))if(t.push(s),t.length>=bc)return t}}return t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return w(function*(){for(var{deviceKey:n,sessionId:i}of e){var o=t._getEndToEndSessions(n)||{};delete o[i],Object.keys(o).length===0?t.store.removeItem(ta(n)):hn(t.store,ta(n),o)}})()}getEndToEndInboundGroupSession(e,t,n,i){i(zt(this.store,bh(e,t)),zt(this.store,lk(e,t)))}getAllEndToEndInboundGroupSessions(e,t){for(var n=0;n<this.store.length;++n){var i=this.store.key(n);i!=null&&i.startsWith(rs)&&t({senderKey:i.slice(rs.length,rs.length+43),sessionId:i.slice(rs.length+44),sessionData:zt(this.store,i)})}t(null)}addEndToEndInboundGroupSession(e,t,n,i){var o=zt(this.store,bh(e,t));o||this.storeEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSession(e,t,n,i){hn(this.store,bh(e,t),n)}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){hn(this.store,lk(e,t),n)}countEndToEndInboundGroupSessions(){var e=this;return w(function*(){for(var t=0,n=0;n<e.store.length;++n){var i=e.store.key(n);i!=null&&i.startsWith(rs)&&(t+=1)}return t})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return w(function*(){for(var t=zt(e.store,ea)||{},n=[],i=0;i<e.store.length;++i){var o=e.store.key(i);if(o!=null&&o.startsWith(rs)){var s=o.slice(rs.length);if(n.push({senderKey:s.slice(0,43),sessionId:s.slice(44),sessionData:zt(e.store,o),needsBackup:s in t}),n.length>=bc)return n}}return n.length===0?null:n})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return w(function*(){for(var{senderKey:n,sessionId:i}of e){var o=bh(n,i);t.store.removeItem(o)}})()}getEndToEndDeviceData(e,t){t(zt(this.store,sk))}storeEndToEndDeviceData(e,t){hn(this.store,sk,e)}storeEndToEndRoom(e,t,n){hn(this.store,ck(e),t)}getEndToEndRooms(e,t){for(var n={},i=ck(""),o=0;o<this.store.length;++o){var s=this.store.key(o);if(s!=null&&s.startsWith(i)){var a=s.slice(i.length);n[a]=zt(this.store,s)}}t(n)}getSessionsNeedingBackup(e){var t=this,n=zt(this.store,ea)||{},i=[],o=function(){if(Object.prototype.hasOwnProperty.call(n,s)){var l=s.slice(0,43),c=s.slice(44);if(t.getEndToEndInboundGroupSession(l,c,null,u=>{i.push({senderKey:l,sessionId:c,sessionData:u})}),e&&i.length>=e)return 1}};for(var s in n)if(o())break;return Promise.resolve(i)}countSessionsNeedingBackup(){var e=zt(this.store,ea)||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){var t=zt(this.store,ea)||{};for(var n of e)delete t[n.senderKey+"/"+n.sessionId];return hn(this.store,ea,t),Promise.resolve()}markSessionsNeedingBackup(e){var t=zt(this.store,ea)||{};for(var n of e)t[n.senderKey+"/"+n.sessionId]=!0;return hn(this.store,ea,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(ly),Promise.resolve()}getAccount(e,t){var n=zt(this.store,ly);t(n)}storeAccount(e,t){hn(this.store,ly,t)}getCrossSigningKeys(e,t){var n=zt(this.store,ik);t(n)}getSecretStorePrivateKey(e,t,n){var i=zt(this.store,Rn+"ssss_cache.".concat(n));t(i)}storeCrossSigningKeys(e,t){hn(this.store,ik,t)}storeSecretStorePrivateKey(e,t,n){hn(this.store,Rn+"ssss_cache.".concat(t),n)}doTxn(e,t,n){return Promise.resolve(n(null))}}function zt(r,e){try{return JSON.parse(r.getItem(e))}catch(t){b.log("Error: Failed to get key %s: %s",e,t.message),b.log(t.stack)}return null}function hn(r,e,t){r.setItem(e,JSON.stringify(t))}class M8{constructor(e){this.db=e,v(this,"nextTxnId",0),e.onversionchange=()=>{b.log("versionchange for indexeddb ".concat(this.db.name,": closing")),e.close()}}containsData(){return w(function*(){throw Error("Not implemented for Backend")})()}startup(){var e=this;return w(function*(){return e})()}deleteAllData(){return w(function*(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")})()}getMigrationState(){var e=this;return w(function*(){var t=Sc.NOT_STARTED;return yield e.doTxn("readonly",[_e.STORE_ACCOUNT],n=>{var i=n.objectStore(_e.STORE_ACCOUNT),o=i.get(kb);o.onsuccess=()=>{var s;t=(s=o.result)!==null&&s!==void 0?s:Sc.NOT_STARTED}}),t})()}setMigrationState(e){var t=this;return w(function*(){yield t.doTxn("readwrite",[_e.STORE_ACCOUNT],n=>{var i=n.objectStore(_e.STORE_ACCOUNT);i.put(e,kb)})})()}getOrAddOutgoingRoomKeyRequest(e){var t=e.requestBody;return new Promise((n,i)=>{var o=this.db.transaction("outgoingRoomKeyRequests","readwrite");o.onerror=i,this._getOutgoingRoomKeyRequest(o,t,s=>{if(s){b.log("already have key request outstanding for "+"".concat(t.room_id," / ").concat(t.session_id,": ")+"not sending another"),n(s);return}b.log("enqueueing key request for ".concat(t.room_id," / ")+t.session_id),o.oncomplete=()=>{n(e)};var a=o.objectStore("outgoingRoomKeyRequests");a.add(e)})})}getOutgoingRoomKeyRequest(e){return new Promise((t,n)=>{var i=this.db.transaction("outgoingRoomKeyRequests","readonly");i.onerror=n,this._getOutgoingRoomKeyRequest(i,e,o=>{t(o)})})}_getOutgoingRoomKeyRequest(e,t,n){var i=e.objectStore("outgoingRoomKeyRequests"),o=i.index("session"),s=o.openCursor([t.room_id,t.session_id]);s.onsuccess=()=>{var a=s.result;if(!a){n(null);return}var l=a.value;if(Va(l.requestBody,t)){n(l);return}a.continue()}}getOutgoingRoomKeyRequestByState(e){if(e.length===0)return Promise.resolve(null);var t=0,n;function i(){var c=this.result;if(c){n=c.value;return}if(t++,!(t>=e.length)){var u=e[t],d=this.source.openCursor(u);d.onsuccess=i}}var o=this.db.transaction("outgoingRoomKeyRequests","readonly"),s=o.objectStore("outgoingRoomKeyRequests"),a=e[t],l=s.index("state").openCursor(a);return l.onsuccess=i,ra(o).then(()=>n)}getAllOutgoingRoomKeyRequestsByState(e){return new Promise((t,n)=>{var i=this.db.transaction("outgoingRoomKeyRequests","readonly"),o=i.objectStore("outgoingRoomKeyRequests"),s=o.index("state"),a=s.getAll(e);a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error)})}getOutgoingRoomKeyRequestsByTarget(e,t,n){var i=0,o=[];function s(){var d=this.result;if(d){var f=d.value;f.recipients.some(m=>m.userId===e&&m.deviceId===t)&&o.push(f),d.continue()}else{if(i++,i>=n.length)return;var p=n[i],h=this.source.openCursor(p);h.onsuccess=s}}var a=this.db.transaction("outgoingRoomKeyRequests","readonly"),l=a.objectStore("outgoingRoomKeyRequests"),c=n[i],u=l.index("state").openCursor(c);return u.onsuccess=s,ra(a).then(()=>o)}updateOutgoingRoomKeyRequest(e,t,n){var i=null;function o(){var l=this.result;if(l){var c=l.value;if(c.state!=t){b.warn("Cannot update room key request from ".concat(t," ")+"as it was already updated to ".concat(c.state));return}Object.assign(c,n),l.update(c),i=c}}var s=this.db.transaction("outgoingRoomKeyRequests","readwrite"),a=s.objectStore("outgoingRoomKeyRequests").openCursor(e);return a.onsuccess=o,ra(s).then(()=>i)}deleteOutgoingRoomKeyRequest(e,t){var n=this.db.transaction("outgoingRoomKeyRequests","readwrite"),i=n.objectStore("outgoingRoomKeyRequests").openCursor(e);return i.onsuccess=()=>{var o=i.result;if(o){var s=o.value;if(s.state!=t){b.warn("Cannot delete room key request in state ".concat(s.state," ")+"(expected ".concat(t,")"));return}o.delete()}},ra(n)}getAccount(e,t){var n=e.objectStore("account"),i=n.get("-");i.onsuccess=function(){try{t(i.result||null)}catch(o){yr(e,o)}}}storeAccount(e,t){var n=e.objectStore("account");n.put(t,"-")}getCrossSigningKeys(e,t){var n=e.objectStore("account"),i=n.get("crossSigningKeys");i.onsuccess=function(){try{t(i.result||null)}catch(o){yr(e,o)}}}getSecretStorePrivateKey(e,t,n){var i=e.objectStore("account"),o=i.get("ssss_cache:".concat(n));o.onsuccess=function(){try{t(o.result||null)}catch(s){yr(e,s)}}}storeCrossSigningKeys(e,t){var n=e.objectStore("account");n.put(t,"crossSigningKeys")}storeSecretStorePrivateKey(e,t,n){var i=e.objectStore("account");i.put(n,"ssss_cache:".concat(t))}countEndToEndSessions(e,t){var n=e.objectStore("sessions"),i=n.count();i.onsuccess=function(){try{t(i.result)}catch(o){yr(e,o)}}}getEndToEndSessions(e,t,n){var i=t.objectStore("sessions"),o=i.index("deviceKey"),s=o.openCursor(e),a={};s.onsuccess=function(){var l=s.result;if(l)a[l.value.sessionId]={session:l.value.session,lastReceivedMessageTs:l.value.lastReceivedMessageTs},l.continue();else try{n(a)}catch(c){yr(t,c)}}}getEndToEndSession(e,t,n,i){var o=n.objectStore("sessions"),s=o.get([e,t]);s.onsuccess=function(){try{s.result?i({session:s.result.session,lastReceivedMessageTs:s.result.lastReceivedMessageTs}):i(null)}catch(a){yr(n,a)}}}getAllEndToEndSessions(e,t){var n=e.objectStore("sessions"),i=n.openCursor();i.onsuccess=function(){try{var o=i.result;o?(t(o.value),o.continue()):t(null)}catch(s){yr(e,s)}}}storeEndToEndSession(e,t,n,i){var o=i.objectStore("sessions");o.put({deviceKey:e,sessionId:t,session:n.session,lastReceivedMessageTs:n.lastReceivedMessageTs})}storeEndToEndSessionProblem(e,t,n){var i=this;return w(function*(){var o=i.db.transaction("session_problems","readwrite"),s=o.objectStore("session_problems");s.put({deviceKey:e,type:t,fixed:n,time:Date.now()}),yield ra(o)})()}getEndToEndSessionProblem(e,t){var n=this;return w(function*(){var i=null,o=n.db.transaction("session_problems","readwrite"),s=o.objectStore("session_problems"),a=s.index("deviceKey"),l=a.getAll(e);return l.onsuccess=()=>{var c=l.result;if(!c.length){i=null;return}c.sort((f,p)=>f.time-p.time);var u=c[c.length-1];for(var d of c)if(d.time>t){i=Object.assign({},d,{fixed:u.fixed});return}u.fixed?i=null:i=u},yield ra(o),i})()}filterOutNotifiedErrorDevices(e){var t=this;return w(function*(){var n=t.db.transaction("notified_error_devices","readwrite"),i=n.objectStore("notified_error_devices"),o=[];return yield Promise.all(e.map(s=>new Promise(a=>{var{userId:l,deviceInfo:c}=s,u=i.get([l,c.deviceId]);u.onsuccess=function(){u.result||(i.put({userId:l,deviceId:c.deviceId}),o.push(s)),a()}}))),o})()}getEndToEndSessionsBatch(){var e=this;return w(function*(){var t=[];return yield e.doTxn("readonly",[_e.STORE_SESSIONS],n=>{var i=n.objectStore(_e.STORE_SESSIONS),o=i.openCursor();o.onsuccess=function(){try{var s=o.result;s&&(t.push(s.value),t.length<bc&&s.continue())}catch(a){yr(n,a)}}}),t.length===0?null:t})()}deleteEndToEndSessionsBatch(e){var t=this;return w(function*(){yield t.doTxn("readwrite",[_e.STORE_SESSIONS],function(){var n=w(function*(i){try{var o=i.objectStore(_e.STORE_SESSIONS),s=function*(){var u=o.delete([a,l]);yield new Promise(d=>{u.onsuccess=d})};for(var{deviceKey:a,sessionId:l}of e)yield*s()}catch(c){yr(i,c)}});return function(i){return n.apply(this,arguments)}}())})()}getEndToEndInboundGroupSession(e,t,n,i){var o=!1,s=!1,a=n.objectStore("inbound_group_sessions"),l=a.get([e,t]);l.onsuccess=function(){try{l.result?o=l.result.session:o=null,s!==!1&&i(o,s)}catch(d){yr(n,d)}};var c=n.objectStore("inbound_group_sessions_withheld"),u=c.get([e,t]);u.onsuccess=function(){try{u.result?s=u.result.session:s=null,o!==!1&&i(o,s)}catch(d){yr(n,d)}}}getAllEndToEndInboundGroupSessions(e,t){var n=e.objectStore("inbound_group_sessions"),i=n.openCursor();i.onsuccess=function(){var o=i.result;if(o){try{t({senderKey:o.value.senderCurve25519Key,sessionId:o.value.sessionId,sessionData:o.value.session})}catch(s){yr(e,s)}o.continue()}else try{t(null)}catch(s){yr(e,s)}}}addEndToEndInboundGroupSession(e,t,n,i){var o=i.objectStore("inbound_group_sessions"),s=o.add({senderCurve25519Key:e,sessionId:t,session:n});s.onerror=a=>{var l;((l=s.error)===null||l===void 0?void 0:l.name)==="ConstraintError"?(a.stopPropagation(),a.preventDefault(),b.log("Ignoring duplicate inbound group session: "+e+" / "+t)):yr(i,new Error("Failed to add inbound group session: "+s.error))}}storeEndToEndInboundGroupSession(e,t,n,i){var o=i.objectStore("inbound_group_sessions");o.put({senderCurve25519Key:e,sessionId:t,session:n})}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){var o=i.objectStore("inbound_group_sessions_withheld");o.put({senderCurve25519Key:e,sessionId:t,session:n})}countEndToEndInboundGroupSessions(){var e=this;return w(function*(){var t=0;return yield e.doTxn("readonly",[_e.STORE_INBOUND_GROUP_SESSIONS],n=>{var i=n.objectStore(_e.STORE_INBOUND_GROUP_SESSIONS),o=i.count();o.onsuccess=()=>{t=o.result}}),t})()}getEndToEndInboundGroupSessionsBatch(){var e=this;return w(function*(){var t=[];return yield e.doTxn("readonly",[_e.STORE_INBOUND_GROUP_SESSIONS,_e.STORE_BACKUP],n=>{var i=n.objectStore(_e.STORE_INBOUND_GROUP_SESSIONS),o=n.objectStore(_e.STORE_BACKUP),s=i.openCursor();s.onsuccess=function(){try{var a=s.result;if(a){var l=o.get(a.key);l.onsuccess=()=>{t.push({senderKey:a.value.senderCurve25519Key,sessionId:a.value.sessionId,sessionData:a.value.session,needsBackup:l.result!==void 0}),t.length<bc&&a.continue()}}}catch(c){yr(n,c)}}}),t.length===0?null:t})()}deleteEndToEndInboundGroupSessionsBatch(e){var t=this;return w(function*(){yield t.doTxn("readwrite",[_e.STORE_INBOUND_GROUP_SESSIONS],function(){var n=w(function*(i){try{var o=i.objectStore(_e.STORE_INBOUND_GROUP_SESSIONS),s=function*(){var u=o.delete([a,l]);yield new Promise(d=>{u.onsuccess=d})};for(var{senderKey:a,sessionId:l}of e)yield*s()}catch(c){yr(i,c)}});return function(i){return n.apply(this,arguments)}}())})()}getEndToEndDeviceData(e,t){var n=e.objectStore("device_data"),i=n.get("-");i.onsuccess=function(){try{t(i.result||null)}catch(o){yr(e,o)}}}storeEndToEndDeviceData(e,t){var n=t.objectStore("device_data");n.put(e,"-")}storeEndToEndRoom(e,t,n){var i=n.objectStore("rooms");i.put(t,e)}getEndToEndRooms(e,t){var n={},i=e.objectStore("rooms"),o=i.openCursor();o.onsuccess=function(){var s=o.result;if(s)n[s.key]=s.value,s.continue();else try{t(n)}catch(a){yr(e,a)}}}getSessionsNeedingBackup(e){return new Promise((t,n)=>{var i=[],o=this.db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");o.onerror=n,o.oncomplete=function(){t(i)};var s=o.objectStore("sessions_needing_backup"),a=o.objectStore("inbound_group_sessions"),l=s.openCursor();l.onsuccess=function(){var c=l.result;if(c){var u=a.get(c.key);u.onsuccess=function(){i.push({senderKey:u.result.senderCurve25519Key,sessionId:u.result.sessionId,sessionData:u.result.session})},(!e||i.length<e)&&c.continue()}}})}countSessionsNeedingBackup(e){e||(e=this.db.transaction("sessions_needing_backup","readonly"));var t=e.objectStore("sessions_needing_backup");return new Promise((n,i)=>{var o=t.count();o.onerror=i,o.onsuccess=()=>n(o.result)})}unmarkSessionsNeedingBackup(e,t){var n=this;return w(function*(){t||(t=n.db.transaction("sessions_needing_backup","readwrite"));var i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map(o=>new Promise((s,a)=>{var l=i.delete([o.senderKey,o.sessionId]);l.onsuccess=s,l.onerror=a})))})()}markSessionsNeedingBackup(e,t){var n=this;return w(function*(){t||(t=n.db.transaction("sessions_needing_backup","readwrite"));var i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map(o=>new Promise((s,a)=>{var l=i.put({senderCurve25519Key:o.senderKey,sessionId:o.sessionId});l.onsuccess=s,l.onerror=a})))})()}addSharedHistoryInboundGroupSession(e,t,n,i){i||(i=this.db.transaction("shared_history_inbound_group_sessions","readwrite"));var o=i.objectStore("shared_history_inbound_group_sessions"),s=o.get([e]);s.onsuccess=()=>{var{sessions:a}=s.result||{sessions:[]};a.push([t,n]),o.put({roomId:e,sessions:a})}}getSharedHistoryInboundGroupSessions(e,t){t||(t=this.db.transaction("shared_history_inbound_group_sessions","readonly"));var n=t.objectStore("shared_history_inbound_group_sessions"),i=n.get([e]);return new Promise((o,s)=>{i.onsuccess=()=>{var{sessions:a}=i.result||{sessions:[]};o(a)},i.onerror=s})}addParkedSharedHistory(e,t,n){n||(n=this.db.transaction("parked_shared_history","readwrite"));var i=n.objectStore("parked_shared_history"),o=i.get([e]);o.onsuccess=()=>{var{parked:s}=o.result||{parked:[]};s.push(t),i.put({roomId:e,parked:s})}}takeParkedSharedHistory(e,t){t||(t=this.db.transaction("parked_shared_history","readwrite"));var n=t.objectStore("parked_shared_history").openCursor(e);return new Promise((i,o)=>{n.onsuccess=()=>{var s=n.result;if(!s){i([]);return}var a=s.value;s.delete(),i(a)},n.onerror=o})}doTxn(e,t,n){var i=this.db.transaction(t,e),o=ra(i),s=n(i);return o.then(()=>s)}}var kN=[r=>{D8(r)},r=>{r.createObjectStore("account")},r=>{var e=r.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]});e.createIndex("deviceKey","deviceKey")},r=>{r.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},r=>{r.createObjectStore("device_data")},r=>{r.createObjectStore("rooms")},r=>{r.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},r=>{r.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},r=>{var e=r.createObjectStore("session_problems",{keyPath:["deviceKey","time"]});e.createIndex("deviceKey","deviceKey"),r.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},r=>{r.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},r=>{r.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}],IN=kN.length;function A8(r,e){b.log("Upgrading IndexedDBCryptoStore from version ".concat(e)+" to ".concat(IN)),kN.forEach((t,n)=>{e<=n&&t(r)})}function D8(r){var e=r.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});e.createIndex("session",["requestBody.room_id","requestBody.session_id"]),e.createIndex("state","state")}function yr(r,e){r._mx_abortexception=e;try{r.abort()}catch{}}function ra(r){return new Promise((e,t)=>{r.oncomplete=()=>{r._mx_abortexception!==void 0&&t(r._mx_abortexception),e(null)},r.onerror=n=>{r._mx_abortexception!==void 0?t(r._mx_abortexception):(b.log("Error performing indexeddb txn",n),t(r.error))},r.onabort=n=>{r._mx_abortexception!==void 0?t(r._mx_abortexception):(b.log("Error performing indexeddb txn",n),t(r.error))}})}var Kw=function(r){return r.TooNew="TOO_NEW",r}({});class Vw extends Error{constructor(e){var t="Crypto store is invalid because ".concat(e,", ")+"please stop the client, delete all data and start the client again";super(t),this.reason=e,this.name="InvalidCryptoStoreError"}}v(Vw,"TOO_NEW",Kw.TooNew);class Nu extends Error{constructor(e,t){super(e),this.value=t}}class N8 extends Error{constructor(){super("MatrixClient has been stopped")}}function xN(r,e){return new Promise((t,n)=>{var i=!0,o=r.open(e);o.onupgradeneeded=()=>{i=!1},o.onblocked=()=>n(o.error),o.onsuccess=()=>{var s=o.result;s.close(),i||r.deleteDatabase(e),t(i)},o.onerror=()=>n(o.error)})}class _e{static exists(e,t){return xN(e,t)}static existsAndIsNotMigrated(e,t){return new Promise((n,i)=>{var o=!0,s=e.open(t);s.onupgradeneeded=()=>{o=!1},s.onblocked=()=>i(s.error),s.onsuccess=()=>{var a=s.result;if(!o)a.close(),e.deleteDatabase(t),n(!1);else{var l=a.transaction([_e.STORE_ACCOUNT],"readonly"),c=l.objectStore(_e.STORE_ACCOUNT),u=c.get(kb);u.onsuccess=()=>{var d,f=(d=u.result)!==null&&d!==void 0?d:Sc.NOT_STARTED;n(f===Sc.NOT_STARTED)},u.onerror=()=>{i(u.error)},a.close()}},s.onerror=()=>i(s.error)})}constructor(e,t){this.indexedDB=e,this.dbName=t,v(this,"backendPromise",void 0),v(this,"backend",void 0)}containsData(){var e=this;return w(function*(){return _e.exists(e.indexedDB,e.dbName)})()}startup(){return this.backendPromise?this.backendPromise:(this.backendPromise=new Promise((e,t)=>{if(!this.indexedDB){t(new Error("no indexeddb support available"));return}b.log("connecting to indexeddb ".concat(this.dbName));var n=this.indexedDB.open(this.dbName,IN);n.onupgradeneeded=i=>{var o=n.result,s=i.oldVersion;A8(o,s)},n.onblocked=()=>{b.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},n.onerror=i=>{b.log("Error connecting to indexeddb",i),t(n.error)},n.onsuccess=()=>{var i=n.result;b.log("connected to indexeddb ".concat(this.dbName)),e(new M8(i))}}).then(e=>e.doTxn("readonly",[_e.STORE_INBOUND_GROUP_SESSIONS,_e.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],t=>{e.getEndToEndInboundGroupSession("","",t,()=>{})}).then(()=>e)).catch(e=>{if(e.name==="VersionError")throw b.warn("Crypto DB is too new for us to use!",e),new Vw(Kw.TooNew);b.warn("unable to connect to indexeddb ".concat(this.dbName)+": falling back to localStorage store: ".concat(e));try{return new xm(globalThis.localStorage)}catch(t){return b.warn("unable to open localStorage: falling back to in-memory store: ".concat(t)),new Sm}}).then(e=>(this.backend=e,e)),this.backendPromise)}deleteAllData(){return new Promise((e,t)=>{if(!this.indexedDB){t(new Error("no indexeddb support available"));return}b.log("Removing indexeddb instance: ".concat(this.dbName));var n=this.indexedDB.deleteDatabase(this.dbName);n.onblocked=()=>{b.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},n.onerror=i=>{b.log("Error deleting data from indexeddb",i),t(n.error)},n.onsuccess=()=>{b.log("Removed indexeddb instance: ".concat(this.dbName)),e()}}).catch(e=>{b.warn("unable to delete IndexedDBCryptoStore: ".concat(e))})}getMigrationState(){return this.backend.getMigrationState()}setMigrationState(e){return this.backend.setMigrationState(e)}getOrAddOutgoingRoomKeyRequest(e){return this.backend.getOrAddOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequest(e){return this.backend.getOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequestByState(e){return this.backend.getOutgoingRoomKeyRequestByState(e)}getAllOutgoingRoomKeyRequestsByState(e){return this.backend.getAllOutgoingRoomKeyRequestsByState(e)}getOutgoingRoomKeyRequestsByTarget(e,t,n){return this.backend.getOutgoingRoomKeyRequestsByTarget(e,t,n)}updateOutgoingRoomKeyRequest(e,t,n){return this.backend.updateOutgoingRoomKeyRequest(e,t,n)}deleteOutgoingRoomKeyRequest(e,t){return this.backend.deleteOutgoingRoomKeyRequest(e,t)}getAccount(e,t){this.backend.getAccount(e,t)}storeAccount(e,t){this.backend.storeAccount(e,t)}getCrossSigningKeys(e,t){this.backend.getCrossSigningKeys(e,t)}getSecretStorePrivateKey(e,t,n){this.backend.getSecretStorePrivateKey(e,t,n)}storeCrossSigningKeys(e,t){this.backend.storeCrossSigningKeys(e,t)}storeSecretStorePrivateKey(e,t,n){this.backend.storeSecretStorePrivateKey(e,t,n)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,n,i){this.backend.getEndToEndSession(e,t,n,i)}getEndToEndSessions(e,t,n){this.backend.getEndToEndSessions(e,t,n)}getAllEndToEndSessions(e,t){this.backend.getAllEndToEndSessions(e,t)}storeEndToEndSession(e,t,n,i){this.backend.storeEndToEndSession(e,t,n,i)}storeEndToEndSessionProblem(e,t,n){return this.backend.storeEndToEndSessionProblem(e,t,n)}getEndToEndSessionProblem(e,t){return this.backend.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.backend.filterOutNotifiedErrorDevices(e)}countEndToEndInboundGroupSessions(){return this.backend.countEndToEndInboundGroupSessions()}getEndToEndSessionsBatch(){return this.backend.getEndToEndSessionsBatch()}deleteEndToEndSessionsBatch(e){return this.backend.deleteEndToEndSessionsBatch(e)}getEndToEndInboundGroupSession(e,t,n,i){this.backend.getEndToEndInboundGroupSession(e,t,n,i)}getAllEndToEndInboundGroupSessions(e,t){this.backend.getAllEndToEndInboundGroupSessions(e,t)}addEndToEndInboundGroupSession(e,t,n,i){this.backend.addEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSession(e,t,n,i){this.backend.storeEndToEndInboundGroupSession(e,t,n,i)}storeEndToEndInboundGroupSessionWithheld(e,t,n,i){this.backend.storeEndToEndInboundGroupSessionWithheld(e,t,n,i)}getEndToEndInboundGroupSessionsBatch(){return this.backend.getEndToEndInboundGroupSessionsBatch()}deleteEndToEndInboundGroupSessionsBatch(e){return this.backend.deleteEndToEndInboundGroupSessionsBatch(e)}storeEndToEndDeviceData(e,t){this.backend.storeEndToEndDeviceData(e,t)}getEndToEndDeviceData(e,t){this.backend.getEndToEndDeviceData(e,t)}storeEndToEndRoom(e,t,n){this.backend.storeEndToEndRoom(e,t,n)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}getSessionsNeedingBackup(e){return this.backend.getSessionsNeedingBackup(e)}countSessionsNeedingBackup(e){return this.backend.countSessionsNeedingBackup(e)}unmarkSessionsNeedingBackup(e,t){return this.backend.unmarkSessionsNeedingBackup(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}addSharedHistoryInboundGroupSession(e,t,n,i){this.backend.addSharedHistoryInboundGroupSession(e,t,n,i)}getSharedHistoryInboundGroupSessions(e,t){return this.backend.getSharedHistoryInboundGroupSessions(e,t)}addParkedSharedHistory(e,t,n){this.backend.addParkedSharedHistory(e,t,n)}takeParkedSharedHistory(e,t){return this.backend.takeParkedSharedHistory(e,t)}doTxn(e,t,n,i){return this.backend.doTxn(e,t,n,i)}}v(_e,"STORE_ACCOUNT","account");v(_e,"STORE_SESSIONS","sessions");v(_e,"STORE_INBOUND_GROUP_SESSIONS","inbound_group_sessions");v(_e,"STORE_INBOUND_GROUP_SESSIONS_WITHHELD","inbound_group_sessions_withheld");v(_e,"STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","shared_history_inbound_group_sessions");v(_e,"STORE_PARKED_SHARED_HISTORY","parked_shared_history");v(_e,"STORE_DEVICE_DATA","device_data");v(_e,"STORE_ROOMS","rooms");v(_e,"STORE_BACKUP","sessions_needing_backup");var pa=function(r){return r.Change="change",r}({}),zs=function(r){return r[r.Unsent=1]="Unsent",r[r.Requested=2]="Requested",r[r.Ready=3]="Ready",r[r.Started=4]="Started",r[r.Cancelled=5]="Cancelled",r[r.Done=6]="Done",r}({}),Om=function(r){return r.Cancel="cancel",r.ShowSas="show_sas",r.ShowReciprocateQr="show_reciprocate_qr",r}({});function ON(r){return r.phase<zs.Ready&&!r.accepting&&!r.declining}function L8(r){if(r.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<r.length;c++){const u=r.charAt(c),d=u.charCodeAt(0);if(e[d]!==255)throw new TypeError(u+" is ambiguous");e[d]=c}const t=r.length,n=r.charAt(0),i=Math.log(t)/Math.log(256),o=Math.log(256)/Math.log(t);function s(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let u=0,d=0,f=0;const p=c.length;for(;f!==p&&c[f]===0;)f++,u++;const h=(p-f)*o+1>>>0,m=new Uint8Array(h);for(;f!==p;){let S=c[f],R=0;for(let k=h-1;(S!==0||R<d)&&k!==-1;k--,R++)S+=256*m[k]>>>0,m[k]=S%t>>>0,S=S/t>>>0;if(S!==0)throw new Error("Non-zero carry");d=R,f++}let E=h-d;for(;E!==h&&m[E]===0;)E++;let y=n.repeat(u);for(;E<h;++E)y+=r.charAt(m[E]);return y}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let u=0,d=0,f=0;for(;c[u]===n;)d++,u++;const p=(c.length-u)*i+1>>>0,h=new Uint8Array(p);for(;u<c.length;){const S=c.charCodeAt(u);if(S>255)return;let R=e[S];if(R===255)return;let k=0;for(let x=p-1;(R!==0||k<f)&&x!==-1;x--,k++)R+=t*h[x]>>>0,h[x]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");f=k,u++}let m=p-f;for(;m!==p&&h[m]===0;)m++;const E=new Uint8Array(d+(p-m));let y=d;for(;m!==p;)E[y++]=h[m++];return E}function l(c){const u=a(c);if(u)return u;throw new Error("Non-base"+t+" character")}return{encode:s,decodeUnsafe:a,decode:l}}var U8="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const PN=L8(U8);var hs=[139,1],uk=32;function hv(r){var e,t=Buffer.alloc(hs.length+r.length+1);t.set(hs,0),t.set(r,hs.length);for(var n=0,i=0;i<t.length-1;++i)n^=t[i];t[t.length-1]=n;var o=PN.encode(t);return(e=o.match(/.{1,4}/g))===null||e===void 0?void 0:e.join(" ")}function od(r){var e=PN.decode(r.replace(/ /g,"")),t=0;for(var n of e)t^=n;if(t!==0)throw new Error("Incorrect parity");for(var i=0;i<hs.length;++i)if(e[i]!==hs[i])throw new Error("Incorrect prefix");if(e.length!==hs.length+uk+1)throw new Error("Incorrect length");return Uint8Array.from(e.slice(hs.length,hs.length+uk))}var j8=256;function $w(r,e,t){return Qb.apply(this,arguments)}function Qb(){return Qb=w(function*(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:j8;if(!globalThis.crypto.subtle||!TextEncoder)throw new Error("Password-based backup is not available on this platform");var i=yield globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(r),{name:"PBKDF2"},!1,["deriveBits"]),o=yield globalThis.crypto.subtle.deriveBits({name:"PBKDF2",salt:new TextEncoder().encode(e),iterations:t,hash:"SHA-512"},i,n);return new Uint8Array(o)}),Qb.apply(this,arguments)}var Yt=function(r){return r.UserTrustStatusChanged="userTrustStatusChanged",r.KeyBackupStatus="crypto.keyBackupStatus",r.KeyBackupFailed="crypto.keyBackupFailed",r.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",r.KeyBackupDecryptionKeyCached="crypto.keyBackupDecryptionKeyCached",r.VerificationRequestReceived="crypto.verificationRequestReceived",r.WillUpdateDevices="crypto.willUpdateDevices",r.DevicesUpdated="crypto.devicesUpdated",r.KeysChanged="crossSigning.keysChanged",r.LegacyCryptoStoreMigrationProgress="crypto.legacyCryptoStoreMigrationProgress",r}({}),Lt=function(r){return r.MEGOLM_UNKNOWN_INBOUND_SESSION_ID="MEGOLM_UNKNOWN_INBOUND_SESSION_ID",r.MEGOLM_KEY_WITHHELD="MEGOLM_KEY_WITHHELD",r.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE="MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE",r.OLM_UNKNOWN_MESSAGE_INDEX="OLM_UNKNOWN_MESSAGE_INDEX",r.HISTORICAL_MESSAGE_NO_KEY_BACKUP="HISTORICAL_MESSAGE_NO_KEY_BACKUP",r.HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED="HISTORICAL_MESSAGE_BACKUP_UNCONFIGURED",r.HISTORICAL_MESSAGE_WORKING_BACKUP="HISTORICAL_MESSAGE_WORKING_BACKUP",r.HISTORICAL_MESSAGE_USER_NOT_JOINED="HISTORICAL_MESSAGE_USER_NOT_JOINED",r.SENDER_IDENTITY_PREVIOUSLY_VERIFIED="SENDER_IDENTITY_PREVIOUSLY_VERIFIED",r.UNSIGNED_SENDER_DEVICE="UNSIGNED_SENDER_DEVICE",r.UNKNOWN_SENDER_DEVICE="UNKNOWN_SENDER_DEVICE",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.MEGOLM_BAD_ROOM="MEGOLM_BAD_ROOM",r.MEGOLM_MISSING_FIELDS="MEGOLM_MISSING_FIELDS",r.OLM_DECRYPT_GROUP_MESSAGE_ERROR="OLM_DECRYPT_GROUP_MESSAGE_ERROR",r.OLM_BAD_ENCRYPTED_MESSAGE="OLM_BAD_ENCRYPTED_MESSAGE",r.OLM_BAD_RECIPIENT="OLM_BAD_RECIPIENT",r.OLM_BAD_RECIPIENT_KEY="OLM_BAD_RECIPIENT_KEY",r.OLM_BAD_ROOM="OLM_BAD_ROOM",r.OLM_BAD_SENDER_CHECK_FAILED="OLM_BAD_SENDER_CHECK_FAILED",r.OLM_BAD_SENDER="OLM_BAD_SENDER",r.OLM_FORWARDED_MESSAGE="OLM_FORWARDED_MESSAGE",r.OLM_MISSING_CIPHERTEXT="OLM_MISSING_CIPHERTEXT",r.OLM_NOT_INCLUDED_IN_RECIPIENTS="OLM_NOT_INCLUDED_IN_RECIPIENTS",r.UNKNOWN_ENCRYPTION_ALGORITHM="UNKNOWN_ENCRYPTION_ALGORITHM",r}({}),Ww=function(r){return r[r.AllDevicesIsolationMode=0]="AllDevicesIsolationMode",r[r.OnlySignedDevicesIsolationMode=1]="OnlySignedDevicesIsolationMode",r}({});class F8{constructor(e){this.errorOnVerifiedUserProblems=e,v(this,"kind",Ww.AllDevicesIsolationMode)}}class B8{constructor(){v(this,"kind",Ww.OnlySignedDevicesIsolationMode)}}class sd{constructor(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=n,v(this,"needsUserApproval",void 0),this.needsUserApproval=i}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}class MN{constructor(e){var t,n,i,o,s;v(this,"signedByOwner",void 0),v(this,"crossSigningVerified",void 0),v(this,"tofu",void 0),v(this,"localVerified",void 0),v(this,"trustCrossSignedDevices",void 0),this.signedByOwner=(t=e.signedByOwner)!==null&&t!==void 0?t:!1,this.crossSigningVerified=(n=e.crossSigningVerified)!==null&&n!==void 0?n:!1,this.tofu=(i=e.tofu)!==null&&i!==void 0?i:!1,this.localVerified=(o=e.localVerified)!==null&&o!==void 0?o:!1,this.trustCrossSignedDevices=(s=e.trustCrossSignedDevices)!==null&&s!==void 0?s:!1}isVerified(){return this.localVerified||this.trustCrossSignedDevices&&this.crossSigningVerified}}var qw=function(r){return r.Master="master",r.SelfSigning="self_signing",r.UserSigning="user_signing",r}({}),ns=function(r){return r[r.NONE=0]="NONE",r[r.GREY=1]="GREY",r[r.RED=2]="RED",r}({}),wl=function(r){return r[r.UNKNOWN=0]="UNKNOWN",r[r.UNVERIFIED_IDENTITY=1]="UNVERIFIED_IDENTITY",r[r.UNSIGNED_DEVICE=2]="UNSIGNED_DEVICE",r[r.UNKNOWN_DEVICE=3]="UNKNOWN_DEVICE",r[r.AUTHENTICITY_NOT_GUARANTEED=4]="AUTHENTICITY_NOT_GUARANTEED",r[r.MISMATCHED_SENDER_KEY=5]="MISMATCHED_SENDER_KEY",r}({});const K8=Object.freeze(Object.defineProperty({__proto__:null,AllDevicesIsolationMode:F8,CrossSigningKey:qw,CryptoEvent:Yt,DecryptionFailureCode:Lt,DeviceIsolationModeKind:Ww,DeviceVerificationStatus:MN,EventShieldColour:ns,EventShieldReason:wl,OnlySignedDevicesIsolationMode:B8,UserVerificationStatus:sd,VerificationPhase:zs,VerificationRequestEvent:pa,VerifierEvent:Om,canAcceptVerificationRequest:ON,decodeRecoveryKey:od,deriveRecoveryKeyFromPassphrase:$w,encodeRecoveryKey:hv},Symbol.toStringTag,{value:"Module"}));class cr extends Error{constructor(e,t,n){super(t),this.code=e,v(this,"detailedString",void 0),this.name="DecryptionError",this.detailedString=V8(this,n)}}function V8(r,e){var t=r.name+"[msg: "+r.message;return e&&(t+=", "+Object.keys(e).map(n=>n+": "+e[n]).join(", ")),t+="]",t}var dk=65536*3/4;class $8 extends Error{constructor(){super(...arguments),v(this,"data",{errcode:"M_TOO_LARGE",error:"Payload too large for encrypted message"})}}function fk(r){if(r===void 0)throw new Error("payloadString undefined");if(r.length>dk)throw new $8("Message too long (".concat(r.length," bytes). ")+"The maximum for an encrypted message is ".concat(dk," bytes."))}class hk{constructor(e){this.cryptoStore=e,v(this,"pickleKey","DEFAULT_KEY"),v(this,"deviceCurve25519Key",null),v(this,"deviceEd25519Key",null),v(this,"maxOneTimeKeys",null),v(this,"outboundGroupSessionStore",{}),v(this,"inboundGroupSessionMessageIndexes",{}),v(this,"sessionsInProgress",{}),v(this,"olmPrekeyPromise",Promise.resolve())}static getOlmVersion(){return globalThis.Olm.get_library_version()}init(){var e=arguments,t=this;return w(function*(){var{pickleKey:n,fromExportedDevice:i}=e.length>0&&e[0]!==void 0?e[0]:{},o,s=new globalThis.Olm.Account;try{i?(n&&b.warn("ignoring opts.pickleKey because opts.fromExportedDevice is present."),t.pickleKey=i.pickleKey,yield t.initialiseFromExportedDevice(i,s)):(n&&(t.pickleKey=n),yield t.initialiseAccount(s)),o=JSON.parse(s.identity_keys()),t.maxOneTimeKeys=s.max_number_of_one_time_keys()}finally{s.free()}t.deviceCurve25519Key=o.curve25519,t.deviceEd25519Key=o.ed25519})()}initialiseFromExportedDevice(e,t){var n=this;return w(function*(){yield n.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT,_e.STORE_SESSIONS],i=>{n.cryptoStore.storeAccount(i,e.pickledAccount),e.sessions.forEach(o=>{var{deviceKey:s,sessionId:a}=o,l={session:o.session,lastReceivedMessageTs:o.lastReceivedMessageTs};n.cryptoStore.storeEndToEndSession(s,a,l,i)})}),t.unpickle(n.pickleKey,e.pickledAccount)})()}initialiseAccount(e){var t=this;return w(function*(){yield t.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],n=>{t.cryptoStore.getAccount(n,i=>{i!==null?e.unpickle(t.pickleKey,i):(e.create(),i=e.pickle(t.pickleKey),t.cryptoStore.storeAccount(n,i))})})})()}getAccount(e,t){this.cryptoStore.getAccount(e,n=>{var i=new globalThis.Olm.Account;try{i.unpickle(this.pickleKey,n),t(i)}finally{i.free()}})}storeAccount(e,t){this.cryptoStore.storeAccount(e,t.pickle(this.pickleKey))}export(){var e=this;return w(function*(){var t={pickleKey:e.pickleKey};return yield e.cryptoStore.doTxn("readonly",[_e.STORE_ACCOUNT,_e.STORE_SESSIONS],n=>{e.cryptoStore.getAccount(n,i=>{t.pickledAccount=i}),t.sessions=[],e.cryptoStore.getAllEndToEndSessions(n,i=>{t.sessions.push(i)})}),t})()}getSession(e,t,n,i){this.cryptoStore.getEndToEndSession(e,t,n,o=>{this.unpickleSession(o,i)})}unpickleSession(e,t){var n=new globalThis.Olm.Session;try{n.unpickle(this.pickleKey,e.session);var i=Object.assign({},e,{session:n});t(i)}finally{n.free()}}saveSession(e,t,n){var i=t.session.session_id();b.debug("Saving Olm session ".concat(i," with device ").concat(e,": ").concat(t.session.describe()));var o=Object.assign(t,{session:t.session.pickle(this.pickleKey)});this.cryptoStore.storeEndToEndSession(e,i,o,n)}getUtility(e){var t=new globalThis.Olm.Utility;try{return e(t)}finally{t.free()}}sign(e){var t=this;return w(function*(){var n;return yield t.cryptoStore.doTxn("readonly",[_e.STORE_ACCOUNT],i=>{t.getAccount(i,o=>{n=o.sign(e)})}),n})()}getOneTimeKeys(){var e=this;return w(function*(){var t;return yield e.cryptoStore.doTxn("readonly",[_e.STORE_ACCOUNT],n=>{e.getAccount(n,i=>{t=JSON.parse(i.one_time_keys())})}),t})()}maxNumberOfOneTimeKeys(){var e;return(e=this.maxOneTimeKeys)!==null&&e!==void 0?e:-1}markKeysAsPublished(){var e=this;return w(function*(){yield e.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],t=>{e.getAccount(t,n=>{n.mark_keys_as_published(),e.storeAccount(t,n)})})})()}generateOneTimeKeys(e){return this.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],t=>{this.getAccount(t,n=>{n.generate_one_time_keys(e),this.storeAccount(t,n)})})}generateFallbackKey(){var e=this;return w(function*(){yield e.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],t=>{e.getAccount(t,n=>{n.generate_fallback_key(),e.storeAccount(t,n)})})})()}getFallbackKey(){var e=this;return w(function*(){var t;return yield e.cryptoStore.doTxn("readonly",[_e.STORE_ACCOUNT],n=>{e.getAccount(n,i=>{t=JSON.parse(i.unpublished_fallback_key())})}),t})()}forgetOldFallbackKey(){var e=this;return w(function*(){yield e.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],t=>{e.getAccount(t,n=>{n.forget_old_fallback_key(),e.storeAccount(t,n)})})})()}createOutboundSession(e,t){var n=this;return w(function*(){var i;return yield n.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT,_e.STORE_SESSIONS],o=>{n.getAccount(o,s=>{var a=new globalThis.Olm.Session;try{a.create_outbound(s,e,t),i=a.session_id(),n.storeAccount(o,s);var l={session:a,lastReceivedMessageTs:Date.now()};n.saveSession(e,l,o)}finally{a.free()}})},b.getChild("[createOutboundSession]")),i})()}createInboundSession(e,t,n){var i=this;return w(function*(){if(t!==0)throw new Error("Need messageType == 0 to create inbound session");var o;return yield i.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT,_e.STORE_SESSIONS],s=>{i.getAccount(s,a=>{var l=new globalThis.Olm.Session;try{l.create_inbound_from(a,e,n),a.remove_one_time_keys(l),i.storeAccount(s,a);var c=l.decrypt(t,n),u={session:l,lastReceivedMessageTs:Date.now()};i.saveSession(e,u,s),o={payload:c,session_id:l.session_id()}}finally{l.free()}})},b.getChild("[createInboundSession]")),o})()}getSessionIdsForDevice(e){var t=this;return w(function*(){var n=b.getChild("[getSessionIdsForDevice]");if(e in t.sessionsInProgress){n.debug("Waiting for Olm session for ".concat(e," to be created"));try{yield t.sessionsInProgress[e]}catch{}}var i;return yield t.cryptoStore.doTxn("readonly",[_e.STORE_SESSIONS],o=>{t.cryptoStore.getEndToEndSessions(e,o,s=>{i=Object.keys(s)})},n),i})()}getSessionIdForDevice(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2?t[2]:void 0,s=yield n.getSessionInfoForDevice(e,i,o);if(s.length===0)return null;for(var a=0,l=1;l<s.length;l++){var c=s[l],u=c.lastReceivedMessageTs===void 0?0:c.lastReceivedMessageTs,d=s[a],f=d.lastReceivedMessageTs===void 0?0:d.lastReceivedMessageTs;(u>f||u===f&&c.sessionId<d.sessionId)&&(a=l)}return s[a].sessionId})()}getSessionInfoForDevice(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2&&t[2]!==void 0?t[2]:b;if(o=o.getChild("[getSessionInfoForDevice]"),e in n.sessionsInProgress&&!i){o.debug("Waiting for Olm session for ".concat(e," to be created"));try{yield n.sessionsInProgress[e]}catch{}}var s=[];return yield n.cryptoStore.doTxn("readonly",[_e.STORE_SESSIONS],a=>{n.cryptoStore.getEndToEndSessions(e,a,l=>{var c=Object.keys(l).sort(),u=function(p){n.unpickleSession(l[p],h=>{s.push({lastReceivedMessageTs:h.lastReceivedMessageTs,hasReceivedMessage:h.session.has_received_message(),sessionId:p})})};for(var d of c)u(d)})},o),s})()}encryptMessage(e,t,n){var i=this;return w(function*(){fk(n);var o;return yield i.cryptoStore.doTxn("readwrite",[_e.STORE_SESSIONS],s=>{i.getSession(e,t,s,a=>{var l=a.session.describe();b.log("encryptMessage: Olm Session ID "+t+" to "+e+": "+l),o=a.session.encrypt(n),i.saveSession(e,a,s)})},b.getChild("[encryptMessage]")),o})()}decryptMessage(e,t,n,i){var o=this;return w(function*(){var s;return yield o.cryptoStore.doTxn("readwrite",[_e.STORE_SESSIONS],a=>{o.getSession(e,t,a,l=>{var c=l.session.describe();b.log("decryptMessage: Olm Session ID "+t+" from "+e+": "+c),s=l.session.decrypt(n,i),l.lastReceivedMessageTs=Date.now(),o.saveSession(e,l,a)})},b.getChild("[decryptMessage]")),s})()}matchesSession(e,t,n,i){var o=this;return w(function*(){if(n!==0)return!1;var s;return yield o.cryptoStore.doTxn("readonly",[_e.STORE_SESSIONS],a=>{o.getSession(e,t,a,l=>{s=l.session.matches_inbound(i)})},b.getChild("[matchesSession]")),s})()}recordSessionProblem(e,t,n){var i=this;return w(function*(){b.info("Recording problem on olm session with ".concat(e," of type ").concat(t,". Recreating: ").concat(n)),yield i.cryptoStore.storeEndToEndSessionProblem(e,t,n)})()}sessionMayHaveProblems(e,t){return this.cryptoStore.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.cryptoStore.filterOutNotifiedErrorDevices(e)}saveOutboundGroupSession(e){this.outboundGroupSessionStore[e.session_id()]=e.pickle(this.pickleKey)}getOutboundGroupSession(e,t){var n=this.outboundGroupSessionStore[e];if(n===void 0)throw new Error("Unknown outbound group session "+e);var i=new globalThis.Olm.OutboundGroupSession;try{return i.unpickle(this.pickleKey,n),t(i)}finally{i.free()}}createOutboundGroupSession(){var e=new globalThis.Olm.OutboundGroupSession;try{return e.create(),this.saveOutboundGroupSession(e),e.session_id()}finally{e.free()}}encryptGroupMessage(e,t){return b.log("encrypting msg with megolm session ".concat(e)),fk(t),this.getOutboundGroupSession(e,n=>{var i=n.encrypt(t);return this.saveOutboundGroupSession(n),i})}getOutboundGroupSessionKey(e){return this.getOutboundGroupSession(e,function(t){return{chain_index:t.message_index(),key:t.session_key()}})}unpickleInboundGroupSession(e,t){var n=new globalThis.Olm.InboundGroupSession;try{return n.unpickle(this.pickleKey,e.session),t(n)}finally{n.free()}}getInboundGroupSession(e,t,n,i,o){this.cryptoStore.getEndToEndInboundGroupSession(t,n,i,(s,a)=>{if(s===null){o(null,null,a);return}if(e!==null&&e!==s.room_id)throw new Error("Mismatched room_id for inbound group session (expected "+s.room_id+", was "+e+")");this.unpickleInboundGroupSession(s,l=>{o(l,s,a)})})}addInboundGroupSession(e,t,n,i,o,s,a){var l=arguments,c=this;return w(function*(){var u=l.length>7&&l[7]!==void 0?l[7]:{};yield c.cryptoStore.doTxn("readwrite",[_e.STORE_INBOUND_GROUP_SESSIONS,_e.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,_e.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],d=>{c.getInboundGroupSession(e,t,i,d,(f,p)=>{var h=new globalThis.Olm.InboundGroupSession;try{if(a?h.import_session(o):h.create(o),i!=h.session_id())throw new Error("Mismatched group session ID from senderKey: "+t);if(f&&(b.log("Update for megolm session ".concat(t,"|").concat(i)),f.first_known_index()<=h.first_known_index())){if(!p.untrusted||u.untrusted){b.log("Keeping existing megolm session ".concat(t,"|").concat(i));return}if(f.first_known_index()<h.first_known_index()){f.export_session(h.first_known_index())===h.export_session(h.first_known_index())?(b.info("Upgrading trust of existing megolm session "+"".concat(t,"|").concat(i," based on newly-received trusted session")),p.untrusted=!1,c.cryptoStore.storeEndToEndInboundGroupSession(t,i,p,d)):b.warn("Newly-received megolm session ".concat(t,"|$sessionId}")+" does not match existing session! Keeping existing session");return}}b.debug("Storing megolm session ".concat(t,"|").concat(i," with first index ")+h.first_known_index());var m=Object.assign({},u,{room_id:e,session:h.pickle(c.pickleKey),keysClaimed:s,forwardingCurve25519KeyChain:n});c.cryptoStore.storeEndToEndInboundGroupSession(t,i,m,d),!f&&u.sharedHistory&&c.cryptoStore.addSharedHistoryInboundGroupSession(e,t,i,d)}finally{h.free()}})},b.getChild("[addInboundGroupSession]"))})()}addInboundGroupSessionWithheld(e,t,n,i,o){var s=this;return w(function*(){yield s.cryptoStore.doTxn("readwrite",[_e.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],a=>{s.cryptoStore.storeEndToEndInboundGroupSessionWithheld(t,n,{room_id:e,code:i,reason:o},a)})})()}decryptGroupMessage(e,t,n,i,o,s){var a=this;return w(function*(){var l=null,c;if(yield a.cryptoStore.doTxn("readwrite",[_e.STORE_INBOUND_GROUP_SESSIONS,_e.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],u=>{a.getInboundGroupSession(e,t,n,u,(d,f,p)=>{if(d===null||f===null){if(p){var h=p.code==="m.unverified"?Lt.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:Lt.MEGOLM_KEY_WITHHELD;c=new cr(h,pk(p),{session:t+"|"+n})}l=null;return}var m;try{m=d.decrypt(i)}catch(k){if((k==null?void 0:k.message)==="OLM.UNKNOWN_MESSAGE_INDEX"&&p){var E=p.code==="m.unverified"?Lt.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE:Lt.MEGOLM_KEY_WITHHELD;c=new cr(E,pk(p),{session:t+"|"+n})}else c=k;return}var y=m.plaintext;if(y===void 0)y=m;else{var S=t+"|"+n+"|"+m.message_index;if(S in a.inboundGroupSessionMessageIndexes){var R=a.inboundGroupSessionMessageIndexes[S];if(R.id!==o||R.timestamp!==s){c=new Error("Duplicate message index, possible replay attack: "+S);return}}a.inboundGroupSessionMessageIndexes[S]={id:o,timestamp:s}}f.session=d.pickle(a.pickleKey),a.cryptoStore.storeEndToEndInboundGroupSession(t,n,f,u),l={result:y,keysClaimed:f.keysClaimed||{},senderKey:t,forwardingCurve25519KeyChain:f.forwardingCurve25519KeyChain||[],untrusted:!!f.untrusted}})},b.getChild("[decryptGroupMessage]")),c)throw c;return l})()}hasInboundSessionKeys(e,t,n){var i=this;return w(function*(){var o;return yield i.cryptoStore.doTxn("readonly",[_e.STORE_INBOUND_GROUP_SESSIONS,_e.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],s=>{i.cryptoStore.getEndToEndInboundGroupSession(t,n,s,a=>{if(a===null){o=!1;return}e!==a.room_id?(b.warn("requested keys for inbound group session ".concat(t,"|")+"".concat(n,", with incorrect room_id ")+"(expected ".concat(a.room_id,", ")+"was ".concat(e,")")),o=!1):o=!0})},b.getChild("[hasInboundSessionKeys]")),o})()}getInboundGroupSessionKey(e,t,n,i){var o=this;return w(function*(){var s=null;return yield o.cryptoStore.doTxn("readonly",[_e.STORE_INBOUND_GROUP_SESSIONS,_e.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],a=>{o.getInboundGroupSession(e,t,n,a,(l,c)=>{if(l===null||c===null){s=null;return}i===void 0&&(i=l.first_known_index());var u=l.export_session(i),d=c.keysClaimed||{},f=d.ed25519||null,p=c.forwardingCurve25519KeyChain||[],h="untrusted"in c?c.untrusted:p.length>0;s={chain_index:i,key:u,forwarding_curve25519_key_chain:p,sender_claimed_ed25519_key:f,shared_history:c.sharedHistory||!1,untrusted:h}})},b.getChild("[getInboundGroupSessionKey]")),s})()}exportInboundGroupSession(e,t,n){return this.unpickleInboundGroupSession(n,i=>{var o=i.first_known_index();return{sender_key:e,sender_claimed_keys:n.keysClaimed,room_id:n.room_id,session_id:t,session_key:i.export_session(o),forwarding_curve25519_key_chain:n.forwardingCurve25519KeyChain||[],first_known_index:i.first_known_index(),"org.matrix.msc3061.shared_history":n.sharedHistory||!1}})}getSharedHistoryInboundGroupSessions(e){var t=this;return w(function*(){var n;return yield t.cryptoStore.doTxn("readonly",[_e.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],i=>{n=t.cryptoStore.getSharedHistoryInboundGroupSessions(e,i)},b.getChild("[getSharedHistoryInboundGroupSessionsForRoom]")),n})()}verifySignature(e,t,n){this.getUtility(function(i){i.ed25519_verify(e,t,n)})}}var pv={"m.unverified":"The sender has disabled encrypting to unverified devices.","m.blacklisted":"The sender has blocked you.","m.unauthorised":"You are not authorised to read the message.","m.no_olm":"Unable to establish a secure channel."};function pk(r){return r.code&&r.code in pv?pv[r.code]:r.reason?r.reason:"decryption key withheld"}var W8=new Uint8Array(8);function AN(r,e){return Zb.apply(this,arguments)}function Zb(){return Zb=w(function*(r,e){var t=yield globalThis.crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),n=yield globalThis.crypto.subtle.deriveBits({name:"HKDF",salt:W8,info:new TextEncoder().encode(e),hash:"SHA-256"},t,512),i=n.slice(0,32),o=n.slice(32),s=globalThis.crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["encrypt","decrypt"]),a=globalThis.crypto.subtle.importKey("raw",o,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([s,a])}),Zb.apply(this,arguments)}function $c(r,e,t,n){return e_.apply(this,arguments)}function e_(){return e_=w(function*(r,e,t,n){var i;n?i=Dr(n):(i=new Uint8Array(16),globalThis.crypto.getRandomValues(i),i[8]&=127);var[o,s]=yield AN(e,t),a=new TextEncoder().encode(r),l=yield globalThis.crypto.subtle.encrypt({name:"AES-CTR",counter:i,length:64},o,a),c=yield globalThis.crypto.subtle.sign({name:"HMAC"},s,l);return{iv:Zr(i),ciphertext:Zr(l),mac:Zr(c)}}),e_.apply(this,arguments)}function Cf(r,e,t){return t_.apply(this,arguments)}function t_(){return t_=w(function*(r,e,t){var[n,i]=yield AN(e,t),o=Dr(r.ciphertext);if(!(yield globalThis.crypto.subtle.verify({name:"HMAC"},i,Dr(r.mac),o)))throw new Error("Error decrypting secret ".concat(t,": bad MAC"));var s=yield globalThis.crypto.subtle.decrypt({name:"AES-CTR",counter:Dr(r.iv),length:64},n,o);return new TextDecoder().decode(new Uint8Array(s))}),t_.apply(this,arguments)}var q8=1e3*60;function _h(r){return Object.values(r.keys)[0]}class gi{constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.userId=e,this.callbacks=t,this.cacheCallbacks=n,v(this,"keys",{}),v(this,"firstUse",!0),v(this,"crossSigningVerifiedBefore",!1)}static fromStorage(e,t){var n=new gi(t);for(var i in e)e.hasOwnProperty(i)&&(n[i]=e[i]);return n}toStorage(){return{keys:this.keys,firstUse:this.firstUse,crossSigningVerifiedBefore:this.crossSigningVerifiedBefore}}getCrossSigningKey(e,t){var n=this;return w(function*(){var i=["master","self_signing","user_signing"].indexOf(e)>=0;if(!n.callbacks.getCrossSigningKey)throw new Error("No getCrossSigningKey callback supplied");t===void 0&&(t=n.getId(e));function o(c){if(c){var u=new globalThis.Olm.PkSigning,d=u.init_with_seed(c);if(d===t)return[d,u];u.free()}}var s=null;n.cacheCallbacks.getCrossSigningKeyCache&&i&&(s=yield n.cacheCallbacks.getCrossSigningKeyCache(e,t));var a=o(s);if(a)return a;s=yield n.callbacks.getCrossSigningKey(e,t);var l=o(s);if(l)return n.cacheCallbacks.storeCrossSigningKeyCache&&i&&(yield n.cacheCallbacks.storeCrossSigningKeyCache(e,s)),l;throw s?new Error("Key type "+e+" from getCrossSigningKey callback did not match"):new Error("getCrossSigningKey callback for "+e+" returned falsey")})()}isStoredInSecretStorage(e){return w(function*(){var t=(yield e.isStored("m.cross_signing.master"))||{};function n(o){for(var s of Object.keys(t))o[s]||delete t[s]}for(var i of["self_signing","user_signing"])n((yield e.isStored("m.cross_signing.".concat(i)))||{});return Object.keys(t).length?t:null})()}static storeInSecretStorage(e,t){return w(function*(){for(var[n,i]of e){var o=Zr(i);yield t.store("m.cross_signing.".concat(n),o)}})()}static getFromSecretStorage(e,t){return w(function*(){var n=yield t.get("m.cross_signing.".concat(e));return n?Dr(n):null})()}isStoredInKeyCache(e){var t=this;return w(function*(){var n=t.cacheCallbacks;if(!n)return!1;var i=e?[e]:["master","self_signing","user_signing"];for(var o of i){var s;if(!(yield(s=n.getCrossSigningKeyCache)===null||s===void 0?void 0:s.call(n,o)))return!1}return!0})()}getCrossSigningKeysFromCache(){var e=this;return w(function*(){var t=new Map,n=e.cacheCallbacks;if(!n)return t;for(var i of["master","self_signing","user_signing"]){var o,s=yield(o=n.getCrossSigningKeyCache)===null||o===void 0?void 0:o.call(n,i);s&&t.set(i,s)}return t})()}getId(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"master";if(!this.keys[e])return null;var t=this.keys[e];return _h(t)}resetKeys(e){var t=this;return w(function*(){if(!t.callbacks.saveCrossSigningKeys)throw new Error("No saveCrossSigningKeys callback supplied");if(e===void 0||e&na.MASTER||!t.keys.master)e=na.MASTER|na.USER_SIGNING|na.SELF_SIGNING;else if(e===0)return;var n={},i={},o,s;try{if(e&na.MASTER?(o=new globalThis.Olm.PkSigning,n.master=o.generate_seed(),s=o.init_with_seed(n.master),i.master={user_id:t.userId,usage:["master"],keys:{["ed25519:"+s]:s}}):[s,o]=yield t.getCrossSigningKey("master"),e&na.SELF_SIGNING){var a=new globalThis.Olm.PkSigning;try{n.self_signing=a.generate_seed();var l=a.init_with_seed(n.self_signing);i.self_signing={user_id:t.userId,usage:["self_signing"],keys:{["ed25519:"+l]:l}},np(i.self_signing,o,t.userId,s)}finally{a.free()}}if(e&na.USER_SIGNING){var c=new globalThis.Olm.PkSigning;try{n.user_signing=c.generate_seed();var u=c.init_with_seed(n.user_signing);i.user_signing={user_id:t.userId,usage:["user_signing"],keys:{["ed25519:"+u]:u}},np(i.user_signing,o,t.userId,s)}finally{c.free()}}Object.assign(t.keys,i),t.callbacks.saveCrossSigningKeys(n)}finally{o&&o.free()}})()}clearKeys(){this.keys={}}setKeys(e){var t={};if(e.master){if(e.master.user_id!==this.userId){var n="Mismatched user ID "+e.master.user_id+" in master key from "+this.userId;throw b.error(n),new Error(n)}this.keys.master?_h(e.master)!==this.getId()&&(this.firstUse=!1):this.firstUse=!0,t.master=e.master}else if(this.keys.master)t.master=this.keys.master;else throw new Error("Tried to set cross-signing keys without a master key");var i=_h(t.master);if(e.user_signing){if(e.user_signing.user_id!==this.userId){var o="Mismatched user ID "+e.master.user_id+" in user_signing key from "+this.userId;throw b.error(o),new Error(o)}try{El(e.user_signing,i,this.userId)}catch(a){throw b.error("invalid signature on user-signing key"),a}}if(e.self_signing){if(e.self_signing.user_id!==this.userId){var s="Mismatched user ID "+e.master.user_id+" in self_signing key from "+this.userId;throw b.error(s),new Error(s)}try{El(e.self_signing,i,this.userId)}catch(a){throw b.error("invalid signature on self-signing key"),a}}e.master&&(this.keys.master=e.master,delete this.keys.self_signing,delete this.keys.user_signing),e.self_signing&&(this.keys.self_signing=e.self_signing),e.user_signing&&(this.keys.user_signing=e.user_signing)}updateCrossSigningVerifiedBefore(e){!this.crossSigningVerifiedBefore&&e&&(this.crossSigningVerifiedBefore=!0)}signObject(e,t){var n=this;return w(function*(){if(!n.keys[t])throw new Error("Attempted to sign with "+t+" key but no such key present");var[i,o]=yield n.getCrossSigningKey(t);try{return np(e,o,n.userId,i),e}finally{o.free()}})()}signUser(e){var t=this;return w(function*(){if(!t.keys.user_signing){b.info("No user signing key: not signing user");return}return t.signObject(e.keys.master,"user_signing")})()}signDevice(e,t){var n=this;return w(function*(){if(e!==n.userId)throw new Error("Trying to sign ".concat(e,"'s device; can only sign our own device"));if(!n.keys.self_signing){b.info("No self signing key: not signing device");return}return n.signObject({algorithms:t.algorithms,keys:t.keys,device_id:t.deviceId,user_id:e},"self_signing")})()}checkUserTrust(e){if(this.userId===e.userId&&this.getId()&&this.getId()===e.getId()&&this.getId("self_signing")&&this.getId("self_signing")===e.getId("self_signing"))return new sd(!0,!0,this.firstUse);if(!this.keys.user_signing)return new sd(!1,!1,e.firstUse);var t,n=e.keys.master,i=this.getId("user_signing");try{El(n,i,this.userId),t=!0}catch{t=!1}return new sd(t,e.crossSigningVerifiedBefore,e.firstUse)}checkDeviceTrust(e,t,n,i){var o=this.checkUserTrust(e),s=e.keys.self_signing;if(!s)return new ec(!1,!1,n,i);var a=G8(t,e.userId);try{return El(s,e.getId(),e.userId),El(a,_h(s),e.userId),ec.fromUserTrustLevel(o,n,i)}catch{return new ec(!1,!1,n,i)}}getCacheCallbacks(){return this.cacheCallbacks}}function G8(r,e){return{algorithms:r.algorithms,keys:r.keys,device_id:r.deviceId,user_id:e,signatures:r.signatures}}var na=function(r){return r[r.MASTER=4]="MASTER",r[r.USER_SIGNING=2]="USER_SIGNING",r[r.SELF_SIGNING=1]="SELF_SIGNING",r}({});class ec extends MN{constructor(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;super({crossSigningVerified:e,tofu:t,localVerified:n,trustCrossSignedDevices:i,signedByOwner:o})}static fromUserTrustLevel(e,t,n){return new ec(e.isCrossSigningVerified(),e.isTofu(),t,n,!0)}isCrossSigningVerified(){return this.crossSigningVerified}isLocallyVerified(){return this.localVerified}isTofu(){return this.tofu}}function DN(r,e){return{getCrossSigningKeyCache:function(){var t=w(function*(i,o){var s=yield new Promise(c=>{r.doTxn("readonly",[_e.STORE_ACCOUNT],u=>{r.getSecretStorePrivateKey(u,c,i)})});if(s&&s.ciphertext){var a=Buffer.from(e.pickleKey),l=yield Cf(s,a,i);return Dr(l)}else return s});function n(i,o){return t.apply(this,arguments)}return n}(),storeCrossSigningKeyCache:function(){var t=w(function*(i,o){if(!(o instanceof Uint8Array))throw new Error("storeCrossSigningKeyCache expects Uint8Array, got ".concat(o));var s=Buffer.from(e.pickleKey),a=yield $c(Zr(o),s,i);return r.doTxn("readwrite",[_e.STORE_ACCOUNT],l=>{r.storeSecretStorePrivateKey(l,i,a)})});function n(i,o){return t.apply(this,arguments)}return n}()}}function H8(r,e,t){return r_.apply(this,arguments)}function r_(){return r_=w(function*(r,e,t){if(r.getUserId()===e)return b.log("Cross-signing: Self-verification done; requesting keys"),new Promise((n,i)=>{var o=r,s=o.crypto.crossSigningInfo,a=new gi(s.userId,{getCrossSigningKey:function(){var u=w(function*(f){b.debug("Cross-signing: requesting secret",f,t);var{promise:p}=o.requestSecret("m.cross_signing.".concat(f),[t]),h=yield p,m=Dr(h);return Uint8Array.from(m)});function d(f){return u.apply(this,arguments)}return d}()},s.getCacheCallbacks());a.keys=s.keys;var l=new Promise(u=>{setTimeout(u,q8,new Error("Timeout"))}),c=w(function*(){var u=yield o.crypto.getSessionBackupPrivateKey();if(!u){b.info("No cached backup key found. Requesting...");var d=o.requestSecret("m.megolm_backup.v1",[t]),f=yield d.promise;b.info("Got key backup key, decoding...");var p=Dr(f);b.info("Decoded backup key, storing..."),yield o.crypto.storeSessionBackupPrivateKey(Uint8Array.from(p)),b.info("Backup key stored. Starting backup restore...");var h=yield o.getKeyBackupVersion();o.restoreKeyBackupWithCache(void 0,void 0,h).then(()=>{b.info("Backup restored.")})}})();Promise.race([Promise.all([a.getCrossSigningKey("master"),a.getCrossSigningKey("self_signing"),a.getCrossSigningKey("user_signing"),c]),l]).then(n,i)}).catch(n=>{b.warn("Cross-signing: failure while requesting keys:",n)})}),r_.apply(this,arguments)}var In=function(r){return r[r.NotTracked=0]="NotTracked",r[r.PendingDownload=1]="PendingDownload",r[r.DownloadInProgress=2]="DownloadInProgress",r[r.UpToDate=3]="UpToDate",r}({});class z8 extends Tt{constructor(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:250;super(),this.cryptoStore=t,this.keyDownloadChunkSize=i,v(this,"devices",{}),v(this,"crossSigningInfo",{}),v(this,"userByIdentityKey",{}),v(this,"deviceTrackingStatus",{}),v(this,"syncToken",null),v(this,"keyDownloadsInProgressByUser",new Map),v(this,"dirty",!1),v(this,"savePromise",null),v(this,"resolveSavePromise",null),v(this,"savePromiseTime",null),v(this,"saveTimer",null),v(this,"hasFetched",null),v(this,"serialiser",void 0),this.serialiser=new Y8(e,n,this)}load(){var e=this;return w(function*(){yield e.cryptoStore.doTxn("readonly",[_e.STORE_DEVICE_DATA],n=>{e.cryptoStore.getEndToEndDeviceData(n,i=>{var o;e.hasFetched=!!(i!=null&&i.devices),e.devices=i?i.devices:{},e.crossSigningInfo=i?i.crossSigningInfo||{}:{},e.deviceTrackingStatus=i?i.trackingStatus:{},e.syncToken=(o=i==null?void 0:i.syncToken)!==null&&o!==void 0?o:null,e.userByIdentityKey={};for(var s of Object.keys(e.devices)){var a=e.devices[s];for(var l of Object.keys(a)){var c=a[l].keys["curve25519:"+l];c!==void 0&&(e.userByIdentityKey[c]=s)}}})});for(var t of Object.keys(e.deviceTrackingStatus))e.deviceTrackingStatus[t]==In.DownloadInProgress&&(e.deviceTrackingStatus[t]=In.PendingDownload)})()}stop(){this.saveTimer!==null&&clearTimeout(this.saveTimer)}saveIfDirty(){var e=arguments,t=this;return w(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:500;if(!t.dirty)return Promise.resolve(!1);var i=Date.now()+n;t.savePromiseTime&&i<t.savePromiseTime&&(clearTimeout(t.saveTimer),t.saveTimer=null,t.savePromiseTime=null);var o=t.savePromise;if(o===null&&(o=new Promise(a=>{t.resolveSavePromise=a}),t.savePromise=o),t.saveTimer===null){var s=t.resolveSavePromise;t.savePromiseTime=i,t.saveTimer=setTimeout(()=>{b.log("Saving device tracking data",t.syncToken),t.savePromiseTime=null,t.saveTimer=null,t.savePromise=null,t.resolveSavePromise=null,t.cryptoStore.doTxn("readwrite",[_e.STORE_DEVICE_DATA],a=>{var l;t.cryptoStore.storeEndToEndDeviceData({devices:t.devices,crossSigningInfo:t.crossSigningInfo,trackingStatus:t.deviceTrackingStatus,syncToken:(l=t.syncToken)!==null&&l!==void 0?l:void 0},a)}).then(()=>{t.dirty=!1,s==null||s(!0)},a=>{b.error("Failed to save device tracking data",t.syncToken),b.error(a)})},n)}return o})()}getSyncToken(){return this.syncToken}setSyncToken(e){this.syncToken=e}downloadKeys(e,t){var n=[],i=[];if(e.forEach(s=>{var a=this.deviceTrackingStatus[s];this.keyDownloadsInProgressByUser.has(s)?(b.log("downloadKeys: already have a download in progress for "+"".concat(s,": awaiting its result")),i.push(this.keyDownloadsInProgressByUser.get(s))):(t||a!=In.UpToDate)&&n.push(s)}),n.length!=0){b.log("downloadKeys: downloading for",n);var o=this.doKeyDownload(n);i.push(o)}return i.length===0&&b.log("downloadKeys: already have all necessary keys"),Promise.all(i).then(()=>this.getDevicesFromStore(e))}getDevicesFromStore(e){var t=new Map;return e.forEach(n=>{var i,o=new Map;(i=this.getStoredDevicesForUser(n))===null||i===void 0||i.forEach(function(s){o.set(s.deviceId,s)}),t.set(n,o)}),t}getKnownUserIds(){return Object.keys(this.devices)}getStoredDevicesForUser(e){var t=this.devices[e];if(!t)return null;var n=[];for(var i in t)t.hasOwnProperty(i)&&n.push(rn.fromStorage(t[i],i));return n}getRawStoredDevicesForUser(e){return this.devices[e]}getStoredCrossSigningForUser(e){return this.crossSigningInfo[e]?gi.fromStorage(this.crossSigningInfo[e],e):null}storeCrossSigningForUser(e,t){this.crossSigningInfo[e]=t,this.dirty=!0}getStoredDevice(e,t){var n=this.devices[e];if(n!=null&&n[t])return rn.fromStorage(n[t],t)}getUserByIdentityKey(e,t){return e!==wr&&e!==bn?null:this.userByIdentityKey[t]}getDeviceByIdentityKey(e,t){var n=this.getUserByIdentityKey(e,t);if(!n)return null;var i=this.devices[n];if(!i)return null;for(var o in i)if(i.hasOwnProperty(o)){var s=i[o];for(var a in s.keys)if(s.keys.hasOwnProperty(a)&&a.indexOf("curve25519:")===0){var l=s.keys[a];if(l==t)return rn.fromStorage(s,o)}}return null}storeDevicesForUser(e,t){this.setRawStoredDevicesForUser(e,t),this.dirty=!0}startTrackingDeviceList(e){if(typeof e!="string")throw new Error("userId must be a string; was "+e);this.deviceTrackingStatus[e]||(b.log("Now tracking device list for "+e),this.deviceTrackingStatus[e]=In.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(e){this.deviceTrackingStatus[e]&&(b.log("No longer tracking device list for "+e),this.deviceTrackingStatus[e]=In.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(var e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]=In.NotTracked;this.dirty=!0}invalidateUserDeviceList(e){this.deviceTrackingStatus[e]&&(b.log("Marking device list outdated for",e),this.deviceTrackingStatus[e]=In.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();var e=[];for(var t of Object.keys(this.deviceTrackingStatus)){var n=this.deviceTrackingStatus[t];n==In.PendingDownload&&e.push(t)}return this.doKeyDownload(e)}setRawStoredDevicesForUser(e,t){if(this.devices[e]!==void 0)for(var[n,i]of Object.entries(this.devices[e])){var o=i.keys["curve25519:"+n];delete this.userByIdentityKey[o]}this.devices[e]=t;for(var[s,a]of Object.entries(t)){var l=a.keys["curve25519:"+s];this.userByIdentityKey[l]=e}}setRawStoredCrossSigningForUser(e,t){this.crossSigningInfo[e]=t}doKeyDownload(e){if(e.length===0)return Promise.resolve();var t=this.serialiser.updateDevicesForUsers(e,this.syncToken).then(()=>{n(!0)},i=>{throw b.error("Error downloading keys for "+e+":",i),n(!1),i});e.forEach(i=>{this.keyDownloadsInProgressByUser.set(i,t);var o=this.deviceTrackingStatus[i];o==In.PendingDownload&&(this.deviceTrackingStatus[i]=In.DownloadInProgress)});var n=i=>{this.emit(et.WillUpdateDevices,e,!this.hasFetched),e.forEach(o=>{if(this.dirty=!0,this.keyDownloadsInProgressByUser.get(o)!==t){b.log("Another update in the queue for",o,"- not marking up-to-date");return}this.keyDownloadsInProgressByUser.delete(o);var s=this.deviceTrackingStatus[o];s==In.DownloadInProgress&&(i?(this.deviceTrackingStatus[o]=In.UpToDate,b.log("Device list for",o,"now up to date")):this.deviceTrackingStatus[o]=In.PendingDownload)}),this.saveIfDirty(),this.emit(et.DevicesUpdated,e,!this.hasFetched),this.hasFetched=!0};return t}}class Y8{constructor(e,t,n){this.baseApis=e,this.olmDevice=t,this.deviceList=n,v(this,"downloadInProgress",!1),v(this,"keyDownloadsQueuedByUser",{}),v(this,"queuedQueryDeferred",void 0),v(this,"syncToken",void 0)}updateDevicesForUsers(e,t){return e.forEach(n=>{this.keyDownloadsQueuedByUser[n]=!0}),this.queuedQueryDeferred||(this.queuedQueryDeferred=Hs()),this.syncToken=t,this.downloadInProgress?(b.log("Queued key download for",e),this.queuedQueryDeferred.promise):this.doQueuedQueries()}doQueuedQueries(){var e=this;if(this.downloadInProgress)throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active");var t=Object.keys(this.keyDownloadsQueuedByUser);this.keyDownloadsQueuedByUser={};var n=this.queuedQueryDeferred;this.queuedQueryDeferred=void 0,b.log("Starting key download for",t),this.downloadInProgress=!0;var i={};this.syncToken&&(i.token=this.syncToken);for(var o=[],s=function(){var c=t.slice(a,a+e.deviceList.keyDownloadChunkSize);o.push(()=>e.baseApis.downloadKeysForUsers(c,i))},a=0;a<t.length;a+=this.deviceList.keyDownloadChunkSize)s();return vH(o,3).then(function(){var l=w(function*(c){var u=Object.assign({},...c.map(m=>m.device_keys||{})),d=Object.assign({},...c.map(m=>m.master_keys||{})),f=Object.assign({},...c.map(m=>m.self_signing_keys||{})),p=Object.assign({},...c.map(m=>m.user_signing_keys||{}));for(var h of t){yield As(5);try{yield e.processQueryResponseForUser(h,u[h],{master:d==null?void 0:d[h],self_signing:f==null?void 0:f[h],user_signing:p==null?void 0:p[h]})}catch(m){b.error("Error processing keys for ".concat(h,":"),m)}}});return function(c){return l.apply(this,arguments)}}()).then(()=>{b.log("Completed key download for "+t),this.downloadInProgress=!1,n==null||n.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()},l=>{b.warn("Error downloading keys for "+t+":",l),this.downloadInProgress=!1,n==null||n.reject(l)}),n.promise}processQueryResponseForUser(e,t,n){var i=this;return w(function*(){b.log("got device keys for "+e+":",t),b.log("got cross-signing keys for "+e+":",n);{var o={},s=i.deviceList.getRawStoredDevicesForUser(e);s&&Object.keys(s).forEach(c=>{var u=rn.fromStorage(s[c],c);o[c]=u}),yield J8(i.olmDevice,e,o,t||{},i.baseApis.getUserId(),i.baseApis.deviceId);var a={};Object.keys(o).forEach(c=>{a[c]=o[c].toStorage()}),i.deviceList.setRawStoredDevicesForUser(e,a)}if(n&&(n.master||n.self_signing||n.user_signing)){var l=i.deviceList.getStoredCrossSigningForUser(e)||new gi(e);l.setKeys(n),i.deviceList.setRawStoredCrossSigningForUser(e,l.toStorage()),i.deviceList.emit(et.UserCrossSigningUpdated,e)}})()}}function J8(r,e,t,n,i,o){return n_.apply(this,arguments)}function n_(){return n_=w(function*(r,e,t,n,i,o){var s=!1;for(var a in t)if(t.hasOwnProperty(a)&&!(a in n)){if(e===i&&a===o){b.warn("Local device ".concat(a," missing from sync, skipping removal"));continue}b.log("Device "+e+":"+a+" has been removed"),delete t[a],s=!0}for(var l in n)if(n.hasOwnProperty(l)){var c=n[l];if(c.user_id!==e){b.warn("Mismatched user_id "+c.user_id+" in keys from "+e+":"+l);continue}if(c.device_id!==l){b.warn("Mismatched device_id "+c.device_id+" in keys from "+e+":"+l);continue}(yield X8(r,t,c))&&(s=!0)}return s}),n_.apply(this,arguments)}function X8(r,e,t){return i_.apply(this,arguments)}function i_(){return i_=w(function*(r,e,t){if(!t.keys)return!1;var n=t.device_id,i=t.user_id,o="ed25519:"+n,s=t.keys[o];if(!s)return b.warn("Device "+i+":"+n+" has no ed25519 key"),!1;var a=t.unsigned||{},l=t.signatures||{};try{yield Ec(r,t,i,n,s)}catch(u){return b.warn("Unable to verify signature on device "+i+":"+n+":"+u),!1}var c;if(n in e){if(c=e[n],c.getFingerprint()!=s)return b.warn("Ed25519 key for device "+i+":"+n+" has changed"),!1}else e[n]=c=new rn(n);return c.keys=t.keys||{},c.algorithms=t.algorithms||[],c.unsigned=a,c.signatures=l,!0}),i_.apply(this,arguments)}var NN=new Map,o_=new Map;class LN{constructor(e){v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"crypto",void 0),v(this,"olmDevice",void 0),v(this,"baseApis",void 0),this.userId=e.userId,this.deviceId=e.deviceId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis}prepareToEncrypt(e){}onRoomMembership(e,t,n){}}class UN{constructor(e){v(this,"userId",void 0),v(this,"crypto",void 0),v(this,"olmDevice",void 0),v(this,"baseApis",void 0),this.userId=e.userId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis}onRoomKeyEvent(e){return w(function*(){})()}importRoomKey(e,t){return w(function*(){})()}hasKeysForKeyRequest(e){return Promise.resolve(!1)}shareKeysWithDevice(e){throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm")}retryDecryptionFromSender(e){return w(function*(){return!1})()}}class Q8 extends Error{constructor(e,t,n){super(e),this.devices=t,this.event=n,this.name="UnknownDeviceError",this.devices=t}}function jN(r,e,t){NN.set(r,e),o_.set(r,t)}var Z8=rn.DeviceVerification;class e9 extends LN{constructor(){super(...arguments),v(this,"sessionPrepared",!1),v(this,"prepPromise",null)}ensureSession(e){return this.prepPromise?this.prepPromise:this.sessionPrepared?Promise.resolve():(this.prepPromise=this.crypto.downloadKeys(e).then(()=>this.crypto.ensureOlmSessionsForUsers(e)).then(()=>{this.sessionPrepared=!0}).finally(()=>{this.prepPromise=null}),this.prepPromise)}encryptMessage(e,t,n){var i=this;return w(function*(){var o=yield e.getEncryptionTargetMembers(),s=o.map(function(h){return h.userId});yield i.ensureSession(s);var a={room_id:e.roomId,type:t,content:n},l={algorithm:wr,sender_key:i.olmDevice.deviceCurve25519Key,ciphertext:{}},c=[];for(var u of s){var d=i.crypto.getStoredDevicesForUser(u)||[];for(var f of d){var p=f.getIdentityKey();p!=i.olmDevice.deviceCurve25519Key&&f.verified!=Z8.BLOCKED&&c.push(Ns(l.ciphertext,i.userId,i.deviceId,i.olmDevice,u,f,a))}}return Promise.all(c).then(()=>l)})()}}class t9 extends UN{decryptEvent(e){var t=this;return w(function*(){var n=e.getWireContent(),i=n.sender_key,o=n.ciphertext;if(!o)throw new cr(Lt.OLM_MISSING_CIPHERTEXT,"Missing ciphertext");if(!(t.olmDevice.deviceCurve25519Key in o))throw new cr(Lt.OLM_NOT_INCLUDED_IN_RECIPIENTS,"Not included in recipients");var s=o[t.olmDevice.deviceCurve25519Key],a;try{a=yield t.decryptMessage(i,s)}catch(d){throw new cr(Lt.OLM_BAD_ENCRYPTED_MESSAGE,"Bad Encrypted Message",{sender:i,err:d})}var l=JSON.parse(a);if(l.recipient!=t.userId)throw new cr(Lt.OLM_BAD_RECIPIENT,"Message was intended for "+l.recipient);if(l.recipient_keys.ed25519!=t.olmDevice.deviceEd25519Key)throw new cr(Lt.OLM_BAD_RECIPIENT_KEY,"Message not intended for this device",{intended:l.recipient_keys.ed25519,our_key:t.olmDevice.deviceEd25519Key});var c=t.crypto.deviceList.getUserByIdentityKey(wr,i);if(c==null){try{yield t.crypto.deviceList.downloadKeys([e.getSender()],!1)}catch(d){throw new cr(Lt.OLM_BAD_SENDER_CHECK_FAILED,"Could not verify sender identity",{sender:i,err:d})}c=t.crypto.deviceList.getUserByIdentityKey(wr,i)}if(c!==e.getSender()&&c!==void 0&&c!==null)throw new cr(Lt.OLM_BAD_SENDER,"Message claimed to be from "+e.getSender(),{real_sender:c});if(l.sender!=e.getSender())throw new cr(Lt.OLM_FORWARDED_MESSAGE,"Message forwarded from "+l.sender,{reported_sender:e.getSender()});if(l.room_id!==e.getRoomId())throw new cr(Lt.OLM_BAD_ROOM,"Message intended for room "+l.room_id,{reported_room:e.getRoomId()||"ROOM_ID_UNDEFINED"});var u=l.keys||{};return{clearEvent:l,senderCurve25519Key:i,claimedEd25519Key:u.ed25519||null}})()}decryptMessage(e,t){if(t.type!==0)return this.reallyDecryptMessage(e,t);var n=this.olmDevice.olmPrekeyPromise.then(()=>this.reallyDecryptMessage(e,t));return this.olmDevice.olmPrekeyPromise=n.catch(()=>{}),n}reallyDecryptMessage(e,t){var n=this;return w(function*(){var i=yield n.olmDevice.getSessionIdsForDevice(e),o={};for(var s of i)try{var a=yield n.olmDevice.decryptMessage(e,s,t.type,t.body);return b.log("Decrypted Olm message from "+e+" with session "+s),a}catch(u){var l=yield n.olmDevice.matchesSession(e,s,t.type,t.body);if(l)throw new Error("Error decrypting prekey message with existing session id "+s+": "+u.message);o[s]=u.message}if(t.type!==0)throw i.length===0?new Error("No existing sessions"):new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(o));var c;try{c=yield n.olmDevice.createInboundSession(e,t.type,t.body)}catch(u){throw o["(new)"]=u.message,new Error("Error decrypting prekey message: "+JSON.stringify(o))}return b.log("created new inbound Olm session ID "+c.session_id+" with "+e),c.payload})()}}jN(wr,e9,t9);function vk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function mk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?vk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):vk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var r9=500,lt=function(r){return r[r.Unsent=0]="Unsent",r[r.Sent=1]="Sent",r[r.CancellationPending=2]="CancellationPending",r[r.CancellationPendingAndWillResend=3]="CancellationPendingAndWillResend",r}({});class n9{constructor(e,t,n){this.baseApis=e,this.deviceId=t,this.cryptoStore=n,v(this,"sendOutgoingRoomKeyRequestsTimer",void 0),v(this,"sendOutgoingRoomKeyRequestsRunning",!1),v(this,"clientRunning",!0)}stop(){b.log("stopping OutgoingRoomKeyRequestManager"),this.clientRunning=!1}sendQueuedRequests(){this.startTimer()}queueRoomKeyRequest(e,t){var n=arguments,i=this;return w(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!1,s=yield i.cryptoStore.getOutgoingRoomKeyRequest(e);if(!s)yield i.cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:e,recipients:t,requestId:i.baseApis.makeTxnId(),state:lt.Unsent});else switch(s.state){case lt.CancellationPendingAndWillResend:case lt.Unsent:return;case lt.CancellationPending:{var a=o?lt.CancellationPendingAndWillResend:lt.Sent;yield i.cryptoStore.updateOutgoingRoomKeyRequest(s.requestId,lt.CancellationPending,{state:a,cancellationTxnId:i.baseApis.makeTxnId()});break}case lt.Sent:{if(o){var l=lt.CancellationPendingAndWillResend,c=yield i.cryptoStore.updateOutgoingRoomKeyRequest(s.requestId,lt.Sent,{state:l,cancellationTxnId:i.baseApis.makeTxnId(),requestTxnId:i.baseApis.makeTxnId()});if(!c)return i.queueRoomKeyRequest(e,t,o);try{yield i.sendOutgoingRoomKeyRequestCancellation(c,!0)}catch(u){b.error("Error sending room key request cancellation; will retry later.",u)}}break}default:throw new Error("unhandled state: "+s.state)}})()}cancelRoomKeyRequest(e){return this.cryptoStore.getOutgoingRoomKeyRequest(e).then(t=>{if(t)switch(t.state){case lt.CancellationPending:case lt.CancellationPendingAndWillResend:return;case lt.Unsent:return b.log("deleting unnecessary room key request for "+Eh(e)),this.cryptoStore.deleteOutgoingRoomKeyRequest(t.requestId,lt.Unsent);case lt.Sent:return this.cryptoStore.updateOutgoingRoomKeyRequest(t.requestId,lt.Sent,{state:lt.CancellationPending,cancellationTxnId:this.baseApis.makeTxnId()}).then(n=>{if(!n){b.log("Tried to cancel room key request for "+Eh(e)+" but it was already cancelled in another tab");return}this.sendOutgoingRoomKeyRequestCancellation(n).catch(i=>{b.error("Error sending room key request cancellation; will retry later.",i),this.startTimer()})});default:throw new Error("unhandled state: "+t.state)}})}getOutgoingSentRoomKeyRequest(e,t){return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e,t,[lt.Sent])}cancelAndResendAllOutgoingRequests(){var e=this;return w(function*(){var t=yield e.cryptoStore.getAllOutgoingRoomKeyRequestsByState(lt.Sent);return Promise.all(t.map(n=>{var{requestBody:i,recipients:o}=n;return e.queueRoomKeyRequest(i,o,!0)}))})()}startTimer(){if(!this.sendOutgoingRoomKeyRequestsTimer){var e=()=>{if(this.sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");this.sendOutgoingRoomKeyRequestsRunning=!0,this.sendOutgoingRoomKeyRequests().finally(()=>{this.sendOutgoingRoomKeyRequestsRunning=!1}).catch(t=>{b.warn("error in OutgoingRoomKeyRequestManager: ".concat(t))})};this.sendOutgoingRoomKeyRequestsTimer=setTimeout(e,r9)}}sendOutgoingRoomKeyRequests(){var e=this;return w(function*(){if(!e.clientRunning){e.sendOutgoingRoomKeyRequestsTimer=void 0;return}var t=yield e.cryptoStore.getOutgoingRoomKeyRequestByState([lt.CancellationPending,lt.CancellationPendingAndWillResend,lt.Unsent]);if(!t){e.sendOutgoingRoomKeyRequestsTimer=void 0;return}try{switch(t.state){case lt.Unsent:yield e.sendOutgoingRoomKeyRequest(t);break;case lt.CancellationPending:yield e.sendOutgoingRoomKeyRequestCancellation(t);break;case lt.CancellationPendingAndWillResend:yield e.sendOutgoingRoomKeyRequestCancellation(t,!0);break}return e.sendOutgoingRoomKeyRequests()}catch(n){b.error("Error sending room key request; will retry later.",n),e.sendOutgoingRoomKeyRequestsTimer=void 0}})()}sendOutgoingRoomKeyRequest(e){b.log("Requesting keys for ".concat(Eh(e.requestBody))+" from ".concat(gk(e.recipients))+"(id ".concat(e.requestId,")"));var t={action:"request",requesting_device_id:this.deviceId,request_id:e.requestId,body:e.requestBody};return this.sendMessageToDevices(t,e.recipients,e.requestTxnId||e.requestId).then(()=>this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,lt.Unsent,{state:lt.Sent}))}sendOutgoingRoomKeyRequestCancellation(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;b.log("Sending cancellation for key request for "+"".concat(Eh(e.requestBody)," to ")+"".concat(gk(e.recipients)," ")+"(cancellation id ".concat(e.cancellationTxnId,")"));var n={action:"request_cancellation",requesting_device_id:this.deviceId,request_id:e.requestId};return this.sendMessageToDevices(n,e.recipients,e.cancellationTxnId).then(()=>t?this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,lt.CancellationPendingAndWillResend,{state:lt.Unsent}):this.cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,lt.CancellationPending))}sendMessageToDevices(e,t,n){var i=new Gt(()=>new Map);for(var o of t){var s=i.getOrCreate(o.userId);s.set(o.deviceId,mk(mk({},e),{},{[tn]:_i()}))}return this.baseApis.sendToDevice(V.RoomKeyRequest,i,n)}}function Eh(r){return r.room_id+" / "+r.session_id}function gk(r){return"[".concat(r.map(e=>"".concat(e.userId,":").concat(e.deviceId)).join(","),"]")}function yk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Sk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?yk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):yk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function i9(r){var e,t,n=r==null||(e=r.currentState)===null||e===void 0?void 0:e.getStateEvents("m.room.history_visibility",""),i=n==null||(t=n.getContent())===null||t===void 0?void 0:t.history_visibility;return["world_readable","shared"].includes(i)}var o9=r=>typeof r.ciphertext=="string"?!!r.ciphertext.length:!!Object.keys(r.ciphertext).length;class s9{constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.sessionId=e,this.sharedHistory=t,v(this,"useCount",0),v(this,"creationTime",void 0),v(this,"sharedWithDevices",new Gt(()=>new Map)),v(this,"blockedDevicesNotified",new Gt(()=>new Map)),this.creationTime=new Date().getTime()}needsRotation(e,t){var n=new Date().getTime()-this.creationTime;return this.useCount>=e||n>=t?(b.log("Rotating megolm session after "+this.useCount+" messages, "+n+"ms"),!0):!1}markSharedWithDevice(e,t,n,i){this.sharedWithDevices.getOrCreate(e).set(t,{deviceKey:n,messageIndex:i})}markNotifiedBlockedDevice(e,t){this.blockedDevicesNotified.getOrCreate(e).set(t,!0)}sharedWithTooManyDevices(e){for(var[t,n]of this.sharedWithDevices){if(!e.has(t))return b.log("Starting new megolm session because we shared with "+t),!0;for(var[i]of n){var o;if(!((o=e.get(t))!==null&&o!==void 0&&o.get(i)))return b.log("Starting new megolm session because we shared with "+t+":"+i),!0}}return!1}}class a9 extends LN{constructor(e){var t,n,i,o;super(e),v(this,"setupPromise",Promise.resolve(null)),v(this,"outboundSessions",{}),v(this,"sessionRotationPeriodMsgs",void 0),v(this,"sessionRotationPeriodMs",void 0),v(this,"encryptionPreparation",void 0),v(this,"roomId",void 0),v(this,"prefixedLogger",void 0),this.roomId=e.roomId,this.prefixedLogger=b.getChild("[".concat(this.roomId," encryption]")),this.sessionRotationPeriodMsgs=(t=(n=e.config)===null||n===void 0?void 0:n.rotation_period_msgs)!==null&&t!==void 0?t:100,this.sessionRotationPeriodMs=(i=(o=e.config)===null||o===void 0?void 0:o.rotation_period_ms)!==null&&i!==void 0?i:7*24*3600*1e3}ensureOutboundSession(e,t,n){var i=arguments,o=this;return w(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!1,a=function(){var c=w(function*(u){var d=i9(e),f=yield o.prepareSession(t,d,u);return yield o.shareSession(t,d,s,n,f),f});return function(d){return c.apply(this,arguments)}}(),l=o.setupPromise.then(a);return o.setupPromise=l.catch(c=>(o.prefixedLogger.error("Failed to setup outbound session",c),null)),l})()}prepareSession(e,t,n){var i=this;return w(function*(){var o,s;return n&&t!==n.sharedHistory&&(n=null),(o=n)!==null&&o!==void 0&&o.needsRotation(i.sessionRotationPeriodMsgs,i.sessionRotationPeriodMs)&&(i.prefixedLogger.debug("Starting new megolm session because we need to rotate."),n=null),(s=n)!==null&&s!==void 0&&s.sharedWithTooManyDevices(e)&&(n=null),n||(i.prefixedLogger.debug("Starting new megolm session"),n=yield i.prepareNewSession(t),i.prefixedLogger.debug("Started new megolm session ".concat(n.sessionId)),i.outboundSessions[n.sessionId]=n),n})()}shareSession(e,t,n,i,o){var s=this;return w(function*(){var a={};for(var[l,c]of e)for(var[u,d]of c){var f,p=d.getIdentityKey();p!=s.olmDevice.deviceCurve25519Key&&((f=o.sharedWithDevices.get(l))!==null&&f!==void 0&&f.get(u)||(a[l]=a[l]||[],a[l].push(d)))}var h=s.olmDevice.getOutboundGroupSessionKey(o.sessionId),m={type:"m.room_key",content:{algorithm:bn,room_id:s.roomId,session_id:o.sessionId,session_key:h.key,chain_index:h.chain_index,"org.matrix.msc3061.shared_history":t}},[E,y]=yield CN(s.olmDevice,s.baseApis,a);yield Promise.all([w(function*(){var S=Array.from(y.entries()).map(R=>{var[k,x]=R;return Array.from(x.entries()).map(T=>{var[O,C]=T;return"".concat(k,"/").concat(O,": ").concat(C.sessionId)})}).flat(1);s.prefixedLogger.debug("Sharing keys with devices with existing Olm sessions:",S),yield s.shareKeyWithOlmSessions(o,h,m,y),s.prefixedLogger.debug("Shared keys with existing Olm sessions")})(),w(function*(){var S=Array.from(E.entries()).map(T=>{var[O,C]=T;return C.map(N=>"".concat(O,"/").concat(N.deviceId))}).flat(1);s.prefixedLogger.debug("Sharing keys (start phase 1) with devices without existing Olm sessions:",S);var R=[],k=Date.now(),x=[];yield s.shareKeyWithDevices(o,h,m,E,R,n?1e4:2e3,x),s.prefixedLogger.debug("Shared keys (end phase 1) with devices without existing Olm sessions"),!n&&Date.now()-k<1e4?w(function*(){var T=new Gt(()=>[]),O=new Set;for(var C of x)O.add(C);var N=[];for(var{userId:F,deviceInfo:H}of R){var ie=F.slice(F.indexOf(":")+1);O.has(ie)?T.getOrCreate(F).push(H):N.push({userId:F,deviceInfo:H})}var $=Array.from(T.entries()).map(X=>{var[oe,re]=X;return re.map(ae=>"".concat(oe,"/").concat(ae.deviceId))}).flat(1);$.length>0&&(s.prefixedLogger.debug("Sharing keys (start phase 2) with devices without existing Olm sessions:",$),yield s.shareKeyWithDevices(o,h,m,T,N,3e4),s.prefixedLogger.debug("Shared keys (end phase 2) with devices without existing Olm sessions")),yield s.notifyFailedOlmDevices(o,h,N)})():yield s.notifyFailedOlmDevices(o,h,R)})(),w(function*(){s.prefixedLogger.debug("There are ".concat(i.size," blocked devices:"),Array.from(i.entries()).map(N=>{var[F,H]=N;return Array.from(H.entries()).map(ie=>{var[$,X]=ie;return"".concat(F,"/").concat($)})}).flat(1));var S=new Gt(()=>new Map),R=0;for(var[k,x]of i)for(var[T,O]of x){var C;((C=o.blockedDevicesNotified.get(k))===null||C===void 0?void 0:C.get(T))===void 0&&(S.getOrCreate(k).set(T,{device:O}),R++)}R&&(s.prefixedLogger.debug("Notifying ".concat(R," newly blocked devices:"),Array.from(S.entries()).map(N=>{var[F,H]=N;return Object.entries(H).map(ie=>{var[$,X]=ie;return"".concat(F,"/").concat($)})}).flat(1)),yield s.notifyBlockedDevices(o,S),s.prefixedLogger.debug("Notified ".concat(R," newly blocked devices")))})()])})()}prepareNewSession(e){var t=this;return w(function*(){var n=t.olmDevice.createOutboundGroupSession(),i=t.olmDevice.getOutboundGroupSessionKey(n);return yield t.olmDevice.addInboundGroupSession(t.roomId,t.olmDevice.deviceCurve25519Key,[],n,i.key,{ed25519:t.olmDevice.deviceEd25519Key},!1,{sharedHistory:e}),t.crypto.backupManager.backupGroupSession(t.olmDevice.deviceCurve25519Key,n),new s9(n,e)})()}getDevicesWithoutSessions(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];for(var[i,o]of t){var s=e.get(i);for(var a of o){var l=a.deviceId,c=s==null?void 0:s.get(l);if(!(c!=null&&c.sessionId)){n.push({userId:i,deviceInfo:a}),s==null||s.delete(l);continue}}}return n}splitDevices(e){var t=20,n=[],i=[n];for(var[o,s]of e){for(var a of s.values())n.push({userId:o,deviceInfo:a.device});n.length>t&&(n=[],i.push(n))}return n.length===0&&i.pop(),i}encryptAndSendKeysToDevices(e,t,n,i){return this.crypto.encryptAndSendToDevices(n,i).then(()=>{for(var o of n)e.markSharedWithDevice(o.userId,o.deviceInfo.deviceId,o.deviceInfo.getIdentityKey(),t)}).catch(o=>{throw this.prefixedLogger.error("failed to encryptAndSendToDevices",o),o})}sendBlockedNotificationsToDevices(e,t,n){var i=this;return w(function*(){var o=new Gt(()=>new Map);for(var s of t){var a=s.userId,l=s.deviceInfo,c=l.deviceInfo,u=c.deviceId,d=Sk(Sk({},n),{},{code:l.code,reason:l.reason,[tn]:_i()});d.code==="m.no_olm"&&(delete d.room_id,delete d.session_id),o.getOrCreate(a).set(u,d)}yield i.baseApis.sendToDevice("m.room_key.withheld",o);for(var[f,p]of o)for(var h of p.keys())e.markNotifiedBlockedDevice(f,h)})()}reshareKeyWithDevice(e,t,n,i){var o=this;return w(function*(){var s,a=o.outboundSessions[t];if(!a){o.prefixedLogger.debug("megolm session ".concat(e,"|").concat(t," not found: not re-sharing keys"));return}if(!a.sharedWithDevices.has(n)){o.prefixedLogger.debug("megolm session ".concat(e,"|").concat(t," never shared with user ").concat(n));return}var l=(s=a.sharedWithDevices.get(n))===null||s===void 0?void 0:s.get(i.deviceId);if(l===void 0){o.prefixedLogger.debug("megolm session ".concat(e,"|").concat(t," never shared with device ").concat(n,":").concat(i.deviceId));return}if(l.deviceKey!==i.getIdentityKey()){o.prefixedLogger.warn("Megolm session ".concat(e,"|").concat(t," has been shared with device ").concat(i.deviceId," but ")+"with identity key ".concat(l.deviceKey,". Key is now ").concat(i.getIdentityKey(),"!"));return}var c=yield o.olmDevice.getInboundGroupSessionKey(o.roomId,e,t,l.messageIndex);if(!c){o.prefixedLogger.warn("No inbound session key found for megolm session ".concat(e,"|").concat(t,": not re-sharing keys"));return}yield xo(o.olmDevice,o.baseApis,new Map([[n,[i]]]));var u={type:"m.forwarded_room_key",content:{algorithm:bn,room_id:o.roomId,session_id:t,session_key:c.key,chain_index:c.chain_index,sender_key:e,sender_claimed_ed25519_key:c.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:c.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":c.shared_history||!1}},d={algorithm:wr,sender_key:o.olmDevice.deviceCurve25519Key,ciphertext:{},[tn]:_i()};yield Ns(d.ciphertext,o.userId,o.deviceId,o.olmDevice,n,i,u),yield o.baseApis.sendToDevice("m.room.encrypted",new Map([[n,new Map([[i.deviceId,d]])]])),o.prefixedLogger.debug("Re-shared key for megolm session ".concat(e,"|").concat(t," with ").concat(n,":").concat(i.deviceId))})()}shareKeyWithDevices(e,t,n,i,o,s,a){var l=this;return w(function*(){var c=yield xo(l.olmDevice,l.baseApis,i,!1,s,a,l.prefixedLogger);l.getDevicesWithoutSessions(c,i,o),yield l.shareKeyWithOlmSessions(e,t,n,c)})()}shareKeyWithOlmSessions(e,t,n,i){var o=this;return w(function*(){for(var s=o.splitDevices(i),a=0;a<s.length;a++){var l="megolm keys for ".concat(e.sessionId," (slice ").concat(a+1,"/").concat(s.length,")");try{o.prefixedLogger.debug("Sharing ".concat(l),s[a].map(c=>"".concat(c.userId,"/").concat(c.deviceInfo.deviceId))),yield o.encryptAndSendKeysToDevices(e,t.chain_index,s[a],n),o.prefixedLogger.debug("Shared ".concat(l))}catch(c){throw o.prefixedLogger.error("Failed to share ".concat(l)),c}}})()}notifyFailedOlmDevices(e,t,n){var i=this;return w(function*(){i.prefixedLogger.debug("Notifying ".concat(n.length," devices we failed to create Olm sessions"));for(var{userId:o,deviceInfo:s}of n){var a=s.deviceId;e.markSharedWithDevice(o,a,s.getIdentityKey(),t.chain_index)}var l=yield i.olmDevice.filterOutNotifiedErrorDevices(n);i.prefixedLogger.debug("Need to notify ".concat(l.length," failed devices which haven't been notified before"));var c=new Gt(()=>new Map);for(var{userId:u,deviceInfo:d}of l)c.getOrCreate(u).set(d.deviceId,{device:{code:"m.no_olm",reason:pv["m.no_olm"],deviceInfo:d}});yield i.notifyBlockedDevices(e,c),i.prefixedLogger.debug("Notified ".concat(l.length," devices we failed to create Olm sessions"))})()}notifyBlockedDevices(e,t){var n=this;return w(function*(){for(var i={room_id:n.roomId,session_id:e.sessionId,algorithm:bn,sender_key:n.olmDevice.deviceCurve25519Key},o=n.splitDevices(t),s=0;s<o.length;s++)try{yield n.sendBlockedNotificationsToDevices(e,o[s],i),n.prefixedLogger.debug("Completed blacklist notification for ".concat(e.sessionId," ")+"(slice ".concat(s+1,"/").concat(o.length,")"))}catch(a){throw n.prefixedLogger.debug("blacklist notification for ".concat(e.sessionId," ")+"(slice ".concat(s+1,"/").concat(o.length,") failed")),a}})()}prepareToEncrypt(e){var t=this;if(e.roomId!==this.roomId)throw new Error("MegolmEncryption.prepareToEncrypt called on unexpected room");if(this.encryptionPreparation!=null){var n=Date.now()-this.encryptionPreparation.startTime;return this.prefixedLogger.debug("Already started preparing to encrypt for this room ".concat(n,"ms ago, skipping")),this.encryptionPreparation.cancel}this.prefixedLogger.debug("Preparing to encrypt events");var i=!1,o=()=>i;return this.encryptionPreparation={startTime:Date.now(),promise:w(function*(){try{var s=yield t.getDevicesInRoom(e,!1,o);if(s===null)return;var[a,l]=s;t.crypto.globalErrorOnUnknownDevices&&t.removeUnknownDevices(a),t.prefixedLogger.debug("Ensuring outbound megolm session"),yield t.ensureOutboundSession(e,a,l,!0),t.prefixedLogger.debug("Ready to encrypt events")}catch(c){t.prefixedLogger.error("Failed to prepare to encrypt events",c)}finally{delete t.encryptionPreparation}})(),cancel:()=>{i=!0,delete this.encryptionPreparation}},this.encryptionPreparation.cancel}encryptMessage(e,t,n){var i=this;return w(function*(){if(i.prefixedLogger.debug("Starting to encrypt event"),i.encryptionPreparation!=null)try{yield i.encryptionPreparation.promise}catch{}var o=i.isVerificationEvent(t,n),[s,a]=yield i.getDevicesInRoom(e,o);i.crypto.globalErrorOnUnknownDevices&&i.checkForUnknownDevices(s);var l=yield i.ensureOutboundSession(e,s,a),c={room_id:i.roomId,type:t,content:n},u=i.olmDevice.encryptGroupMessage(l.sessionId,JSON.stringify(c)),d={algorithm:bn,sender_key:i.olmDevice.deviceCurve25519Key,ciphertext:u,session_id:l.sessionId,device_id:i.deviceId};return l.useCount++,d})()}isVerificationEvent(e,t){switch(e){case V.KeyVerificationCancel:case V.KeyVerificationDone:case V.KeyVerificationMac:case V.KeyVerificationStart:case V.KeyVerificationKey:case V.KeyVerificationReady:case V.KeyVerificationAccept:return!0;case V.RoomMessage:return t.msgtype===xi.KeyVerificationRequest;default:return!1}}forceDiscardSession(){this.setupPromise=this.setupPromise.then(()=>null)}checkForUnknownDevices(e){var t=new Gt(()=>new Map);for(var[n,i]of e)for(var[o,s]of i)s.isUnverified()&&!s.isKnown()&&t.getOrCreate(n).set(o,s);if(t.size)throw new Q8("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",t)}removeUnknownDevices(e){for(var[t,n]of e){for(var[i,o]of n)o.isUnverified()&&!o.isKnown()&&n.delete(i);n.size===0&&e.delete(t)}}getDevicesInRoom(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=t.length>2?t[2]:void 0,s=yield e.getEncryptionTargetMembers();n.prefixedLogger.debug("Encrypting for users (shouldEncryptForInvitedMembers: ".concat(e.shouldEncryptForInvitedMembers(),"):"),s.map(R=>"".concat(R.userId," (").concat(R.membership,")")));var a=s.map(function(R){return R.userId}),l=n.crypto.globalBlacklistUnverifiedDevices,c=e.getBlacklistUnverifiedDevices();typeof c=="boolean"&&(l=c);var u=yield n.crypto.downloadKeys(a,!1);if((o==null?void 0:o())===!0)return null;var d=new Gt(()=>new Map);for(var[f,p]of u)for(var[h,m]of p){if(o!==void 0&&(yield pH()),(o==null?void 0:o())===!0)return null;var E=n.crypto.checkDeviceTrust(f,h);if(m.isBlocked()||!E.isVerified()&&l&&!i){var y=d.getOrCreate(f),S=m.isBlocked();y.set(h,{code:S?"m.blacklisted":"m.unverified",reason:pv[S?"m.blacklisted":"m.unverified"],deviceInfo:m}),p.delete(h)}}return[u,d]})()}}class l9 extends UN{constructor(e){super(e),v(this,"pendingEvents",new Map),v(this,"olmlib",x8),v(this,"roomId",void 0),v(this,"prefixedLogger",void 0),this.roomId=e.roomId,this.prefixedLogger=b.getChild("[".concat(this.roomId," decryption]"))}decryptEvent(e){var t=this;return w(function*(){var n=e.getWireContent();if(!n.sender_key||!n.session_id||!n.ciphertext)throw new cr(Lt.MEGOLM_MISSING_FIELDS,"Missing fields in input");t.addEventToPendingList(e);var i;try{i=yield t.olmDevice.decryptGroupMessage(e.getRoomId(),n.sender_key,n.session_id,n.ciphertext,e.getId(),e.getTs())}catch(c){if(c.name==="DecryptionError")throw c;var o=Lt.OLM_DECRYPT_GROUP_MESSAGE_ERROR;throw(c==null?void 0:c.message)==="OLM.UNKNOWN_MESSAGE_INDEX"&&(t.requestKeysForEvent(e),o=Lt.OLM_UNKNOWN_MESSAGE_INDEX),new cr(o,c instanceof Error?c.message:"Unknown Error: Error is undefined",{session:n.sender_key+"|"+n.session_id})}if(i===null){t.crypto.backupManager.queryKeyBackupRateLimited(e.getRoomId(),n.session_id).catch(()=>{}),t.requestKeysForEvent(e);var s=yield t.olmDevice.sessionMayHaveProblems(n.sender_key,e.getTs()-12e4);if(s){t.prefixedLogger.info("When handling UISI from ".concat(e.getSender()," (sender key ").concat(n.sender_key,"): ")+"recent session problem with that sender:",s);var a=bk[s.type]||bk.unknown;throw s.fixed&&(a+=" Trying to create a new secure channel and re-requesting the keys."),new cr(Lt.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,a,{session:n.sender_key+"|"+n.session_id})}throw new cr(Lt.MEGOLM_UNKNOWN_INBOUND_SESSION_ID,"The sender's device has not sent us the keys for this message.",{session:n.sender_key+"|"+n.session_id})}i.untrusted||t.removeEventFromPendingList(e);var l=JSON.parse(i.result);if(l.room_id!==e.getRoomId())throw new cr(Lt.MEGOLM_BAD_ROOM,"Message intended for room "+l.room_id);return{clearEvent:l,senderCurve25519Key:i.senderKey,claimedEd25519Key:i.keysClaimed.ed25519,forwardingCurve25519KeyChain:i.forwardingCurve25519KeyChain,untrusted:i.untrusted}})()}requestKeysForEvent(e){var t=e.getWireContent(),n=e.getKeyRequestRecipients(this.userId);this.crypto.requestRoomKey({room_id:e.getRoomId(),algorithm:t.algorithm,sender_key:t.sender_key,session_id:t.session_id},n)}addEventToPendingList(e){var t,n=e.getWireContent(),i=n.sender_key,o=n.session_id;this.pendingEvents.has(i)||this.pendingEvents.set(i,new Map);var s=this.pendingEvents.get(i);s.has(o)||s.set(o,new Set),(t=s.get(o))===null||t===void 0||t.add(e)}removeEventFromPendingList(e){var t=e.getWireContent(),n=t.sender_key,i=t.session_id,o=this.pendingEvents.get(n),s=o==null?void 0:o.get(i);s&&(s.delete(e),s.size===0&&o.delete(i),o.size===0&&this.pendingEvents.delete(n))}roomKeyFromEvent(e){var t=e.getSenderKey(),n=e.getContent(),i={};if(!n.room_id||!n.session_key||!n.session_id||!n.algorithm){this.prefixedLogger.error("key event is missing fields");return}if(!Bw(e)){this.prefixedLogger.error("key event not properly encrypted");return}n["org.matrix.msc3061.shared_history"]&&(i.sharedHistory=!0);var o={senderKey:t,sessionId:n.session_id,sessionKey:n.session_key,extraSessionData:i,exportFormat:!1,roomId:n.room_id,algorithm:n.algorithm,forwardingKeyChain:[],keysClaimed:e.getKeysClaimed()};return o}forwardedRoomKeyFromEvent(e){var t=this.roomKeyFromEvent(e);if(t){var n=e.getSenderKey(),i=e.getContent(),o=this.baseApis.crypto.deviceList.getUserByIdentityKey(wr,n),s=i.sender_key,a=i.sender_claimed_ed25519_key,l=Array.isArray(i.forwarding_curve25519_key_chain)?i.forwarding_curve25519_key_chain:[];if(l=l.slice(),l.push(n),o!==e.getSender()){this.prefixedLogger.error("sending device does not belong to the user it claims to be from");return}if(!s){this.prefixedLogger.error("forwarded_room_key event is missing sender_key field");return}if(!a){this.prefixedLogger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");return}var c={ed25519:a};return t.senderKey=s,t.keysClaimed=c,t.exportFormat=!0,t.forwardingKeyChain=l,t.extraSessionData.untrusted=!0,t}}shouldAcceptForwardedKey(e,t){var n=this;return w(function*(){var i,o=e.getSenderKey(),s=(i=n.crypto.deviceList.getDeviceByIdentityKey(wr,o))!==null&&i!==void 0?i:void 0,a=n.crypto.checkDeviceInfoTrust(e.getSender(),s),l=e.getSender()===n.baseApis.getUserId(),c=a.isVerified()&&l,u=yield n.wasRoomKeyRequested(e,t),d=n.wasRoomKeyForwardedByInviter(e,t),f=n.wasRoomKeyForwardedAsHistory(t);return u&&c||d&&f})()}wasRoomKeyRequested(e,t){var n=this;return w(function*(){var i=yield n.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e.getSender(),"*",[lt.Sent]);return i.some(o=>o.requestBody.room_id===t.roomId&&o.requestBody.session_id===t.sessionId)})()}wasRoomKeyForwardedByInviter(e,t){var n,i,o,s=this.baseApis.getRoom(t.roomId),a=e.getSenderKey();if(!a)return!1;var l=this.crypto.deviceList.getUserByIdentityKey(wr,a);if(!l)return!1;var c=s==null||(n=s.getMember(this.userId))===null||n===void 0?void 0:n.events.member,u=(c==null?void 0:c.getSender())===l||(c==null||(i=c.getUnsigned())===null||i===void 0?void 0:i.prev_sender)===l&&(c==null||(o=c.getPrevContent())===null||o===void 0?void 0:o.membership)===Be.Invite;return!!(s&&u)}wasRoomKeyForwardedAsHistory(e){var t=this.baseApis.getRoom(e.roomId);return!!(t&&e.extraSessionData.sharedHistory)}shouldParkForwardedKey(e){var t=this.baseApis.getRoom(e.roomId);return!!(!t&&e.extraSessionData.sharedHistory)}parkForwardedKey(e,t){var n=this;return w(function*(){var i={senderId:e.getSender(),senderKey:t.senderKey,sessionId:t.sessionId,sessionKey:t.sessionKey,keysClaimed:t.keysClaimed,forwardingCurve25519KeyChain:t.forwardingKeyChain};yield n.crypto.cryptoStore.doTxn("readwrite",["parked_shared_history"],o=>n.crypto.cryptoStore.addParkedSharedHistory(t.roomId,i,o),b.getChild("[addParkedSharedHistory]"))})()}addRoomKey(e){var t=this;return w(function*(){try{yield t.olmDevice.addInboundGroupSession(e.roomId,e.senderKey,e.forwardingKeyChain,e.sessionId,e.sessionKey,e.keysClaimed,e.exportFormat,e.extraSessionData),(yield t.retryDecryption(e.senderKey,e.sessionId,!e.extraSessionData.untrusted))&&t.crypto.cancelRoomKeyRequest({algorithm:e.algorithm,room_id:e.roomId,session_id:e.sessionId,sender_key:e.senderKey}),yield t.crypto.backupManager.backupGroupSession(e.senderKey,e.sessionId)}catch(n){t.prefixedLogger.error("Error handling m.room_key_event: ".concat(n))}})()}onForwardedRoomKey(e){var t=this;return w(function*(){var n=t.forwardedRoomKeyFromEvent(e);n&&((yield t.shouldAcceptForwardedKey(e,n))?yield t.addRoomKey(n):t.shouldParkForwardedKey(n)&&(yield t.parkForwardedKey(e,n)))})()}onRoomKeyEvent(e){var t=this;return w(function*(){if(e.getType()=="m.forwarded_room_key")yield t.onForwardedRoomKey(e);else{var n=t.roomKeyFromEvent(e);if(!n)return;yield t.addRoomKey(n)}})()}onRoomKeyWithheldEvent(e){var t=this;return w(function*(){var n=e.getContent(),i=n.sender_key;n.code==="m.no_olm"?yield t.onNoOlmWithheldEvent(e):n.code==="m.unavailable"||(yield t.olmDevice.addInboundGroupSessionWithheld(n.room_id,i,n.session_id,n.code,n.reason)),n.session_id?yield t.retryDecryption(i,n.session_id):yield t.retryDecryptionFromSender(i)})()}onNoOlmWithheldEvent(e){var t=this;return w(function*(){var n=e.getContent(),i=n.sender_key,o=e.getSender();if(t.prefixedLogger.warn("".concat(o,":").concat(i," was unable to establish an olm session with us")),yield t.olmDevice.getSessionIdForDevice(i)){t.prefixedLogger.debug("New session already created. Not creating a new one."),yield t.olmDevice.recordSessionProblem(i,"no_olm",!0);return}var s=t.crypto.deviceList.getDeviceByIdentityKey(n.algorithm,i);if(!s&&(yield t.crypto.downloadKeys([o],!1),s=t.crypto.deviceList.getDeviceByIdentityKey(n.algorithm,i),!s)){t.prefixedLogger.info("Couldn't find device for identity key "+i+": not establishing session"),yield t.olmDevice.recordSessionProblem(i,"no_olm",!1);return}yield xo(t.olmDevice,t.baseApis,new Map([[o,[s]]]),!1);var a={algorithm:wr,sender_key:t.olmDevice.deviceCurve25519Key,ciphertext:{},[tn]:_i()};yield Ns(a.ciphertext,t.userId,void 0,t.olmDevice,o,s,{type:"m.dummy"}),yield t.olmDevice.recordSessionProblem(i,"no_olm",!0),yield t.baseApis.sendToDevice("m.room.encrypted",new Map([[o,new Map([[s.deviceId,a]])]]))})()}hasKeysForKeyRequest(e){var t=e.requestBody;return this.olmDevice.hasInboundSessionKeys(t.room_id,t.sender_key,t.session_id)}shareKeysWithDevice(e){var t=e.userId,n=e.deviceId,i=this.crypto.getStoredDevice(t,n),o=e.requestBody;this.olmlib.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[t,[i]]])).then(s=>{var a,l=(a=s.get(t))===null||a===void 0?void 0:a.get(n);return l!=null&&l.sessionId?(this.prefixedLogger.debug("sharing keys for session "+o.sender_key+"|"+o.session_id+" with device "+t+":"+n),this.buildKeyForwardingMessage(o.room_id,o.sender_key,o.session_id)):null}).then(s=>{var a={algorithm:wr,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[tn]:_i()};return this.olmlib.encryptMessageForDevice(a.ciphertext,this.userId,void 0,this.olmDevice,t,i,s).then(()=>this.baseApis.sendToDevice("m.room.encrypted",new Map([[t,new Map([[n,a]])]])))})}buildKeyForwardingMessage(e,t,n){var i=this;return w(function*(){var o=yield i.olmDevice.getInboundGroupSessionKey(e,t,n);return{type:"m.forwarded_room_key",content:{algorithm:bn,room_id:e,sender_key:t,sender_claimed_ed25519_key:o.sender_claimed_ed25519_key,session_id:n,session_key:o.key,chain_index:o.chain_index,forwarding_curve25519_key_chain:o.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":o.shared_history||!1}}})()}importRoomKey(e){var{untrusted:t,source:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i={};return(t||e.untrusted)&&(i.untrusted=!0),e["org.matrix.msc3061.shared_history"]&&(i.sharedHistory=!0),this.olmDevice.addInboundGroupSession(e.room_id,e.sender_key,e.forwarding_curve25519_key_chain,e.session_id,e.session_key,e.sender_claimed_keys,!0,i).then(()=>{n!=="backup"&&this.crypto.backupManager.backupGroupSession(e.sender_key,e.session_id).catch(o=>{this.prefixedLogger.debug("Failed to back up megolm session",o)}),this.retryDecryption(e.sender_key,e.session_id,!i.untrusted)})}retryDecryption(e,t,n){var i=this;return w(function*(){var o,s=i.pendingEvents.get(e);if(!s)return!0;var a=s.get(t);if(!a)return!0;var l=[...a];return i.prefixedLogger.debug("Retrying decryption on events:",l.map(c=>"".concat(c.getId()))),yield Promise.all(l.map(function(){var c=w(function*(u){try{yield u.attemptDecryption(i.crypto,{isRetry:!0,forceRedecryptIfUntrusted:n})}catch{}});return function(u){return c.apply(this,arguments)}}())),!((o=i.pendingEvents.get(e))!==null&&o!==void 0&&o.has(t))})()}retryDecryptionFromSender(e){var t=this;return w(function*(){var n=t.pendingEvents.get(e);return n?(t.pendingEvents.delete(e),yield Promise.all([...n].map(function(){var i=w(function*(o){var[s,a]=o;yield Promise.all([...a].map(function(){var l=w(function*(c){try{yield c.attemptDecryption(t.crypto)}catch{}});return function(c){return l.apply(this,arguments)}}()))});return function(o){return i.apply(this,arguments)}}())),!t.pendingEvents.has(e)):!0})()}sendSharedHistoryInboundSessions(e){var t=this;return w(function*(){yield xo(t.olmDevice,t.baseApis,e);var n=yield t.olmDevice.getSharedHistoryInboundGroupSessions(t.roomId);t.prefixedLogger.debug("Sharing history in with users ".concat(Array.from(e.keys())),n.map(S=>{var[R,k]=S;return"".concat(R,"|").concat(k)}));for(var[i,o]of n){var s=yield t.buildKeyForwardingMessage(t.roomId,i,o),a=[],l=new Map;for(var[c,u]of e){var d=new Map;l.set(c,d);for(var f of u){var p={algorithm:wr,sender_key:t.olmDevice.deviceCurve25519Key,ciphertext:{},[tn]:_i()};d.set(f.deviceId,p),a.push(Ns(p.ciphertext,t.userId,void 0,t.olmDevice,c,f,s))}}yield Promise.all(a);for(var[h,m]of l){for(var[E,y]of m)o9(y)||(t.prefixedLogger.debug("No ciphertext for device "+h+":"+E+": pruning"),m.delete(E));m.size===0&&(t.prefixedLogger.debug("Pruned all devices for user "+h),l.delete(h))}if(l.size===0){t.prefixedLogger.debug("No users left to send to: aborting");return}yield t.baseApis.sendToDevice("m.room.encrypted",l)}})()}}var bk={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};jN(bn,a9,l9);class _k{constructor(e,t){v(this,"accountDataClientAdapter",void 0),v(this,"crossSigningCallbacks",void 0),v(this,"ssssCryptoCallbacks",void 0),v(this,"crossSigningKeys",void 0),v(this,"keySignatures",void 0),v(this,"keyBackupInfo",void 0),v(this,"sessionBackupPrivateKey",void 0),this.accountDataClientAdapter=new u9(e),this.crossSigningCallbacks=new d9,this.ssssCryptoCallbacks=new f9(t)}addCrossSigningKeys(e,t){this.crossSigningKeys={authUpload:e,keys:t}}addSessionBackup(e){this.keyBackupInfo=e}addSessionBackupPrivateKeyToCache(e){this.sessionBackupPrivateKey=e}addKeySignature(e,t,n){this.keySignatures||(this.keySignatures={});var i=this.keySignatures[e]||{};this.keySignatures[e]=i,i[t]=n}setAccountData(e,t){var n=this;return w(function*(){yield n.accountDataClientAdapter.setAccountData(e,t)})()}buildOperation(){var e=this.accountDataClientAdapter.values;return new c9(e,this.crossSigningKeys,this.keyBackupInfo,this.keySignatures)}persist(e){var t=this;return w(function*(){if(t.crossSigningKeys){var n=DN(e.cryptoStore,e.olmDevice);for(var i of["master","self_signing","user_signing"]){var o;b.log("Cache ".concat(i," cross-signing private key locally"));var s=t.crossSigningCallbacks.privateKeys.get(i);yield(o=n.storeCrossSigningKeyCache)===null||o===void 0?void 0:o.call(n,i,s)}yield e.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],a=>{e.cryptoStore.storeCrossSigningKeys(a,t.crossSigningKeys.keys)})}t.sessionBackupPrivateKey&&(yield e.storeSessionBackupPrivateKey(t.sessionBackupPrivateKey))})()}}class c9{constructor(e,t,n,i){this.accountData=e,this.crossSigningKeys=t,this.keyBackupInfo=n,this.keySignatures=i}apply(e){var t=this;return w(function*(){var n=e.baseApis;if(t.crossSigningKeys){var i,o,s={};for(var[a,l]of Object.entries(t.crossSigningKeys.keys))s[a+"_key"]=l;yield(i=(o=t.crossSigningKeys).authUpload)===null||i===void 0?void 0:i.call(o,d=>n.uploadDeviceSigningKeys(d??void 0,s)),e.crossSigningInfo.setKeys(t.crossSigningKeys.keys)}if(t.accountData)for(var[c,u]of t.accountData)yield n.setAccountData(c,u);t.keySignatures&&(yield n.uploadKeySignatures(t.keySignatures)),t.keyBackupInfo&&(t.keyBackupInfo.version?yield n.http.authedRequest(Z.Put,"/room_keys/version/"+t.keyBackupInfo.version,void 0,{algorithm:t.keyBackupInfo.algorithm,auth_data:t.keyBackupInfo.auth_data},{prefix:Pt.V3}):yield n.http.authedRequest(Z.Post,"/room_keys/version",void 0,t.keyBackupInfo,{prefix:Pt.V3}),yield e.backupManager.checkKeyBackup())})()}}class u9 extends Tt{constructor(e){super(),this.existingValues=e,v(this,"values",new Map)}getAccountDataFromServer(e){return Promise.resolve(this.getAccountData(e))}getAccountData(e){var t=this.values.get(e);if(t)return t;var n=this.existingValues.get(e);return n?n.getContent():null}setAccountData(e,t){var n=this.values.get(e);return this.values.set(e,t),Promise.resolve().then(()=>{var i=new pr({type:e,content:t});return this.emit(be.AccountData,i,n),{}})}}class d9{constructor(){v(this,"privateKeys",new Map)}getCrossSigningKeyCache(e,t){return this.getCrossSigningKey(e,t)}storeCrossSigningKeyCache(e,t){return this.privateKeys.set(e,t),Promise.resolve()}getCrossSigningKey(e,t){var n;return Promise.resolve((n=this.privateKeys.get(e))!==null&&n!==void 0?n:null)}saveCrossSigningKeys(e){for(var[t,n]of Object.entries(e))this.privateKeys.set(t,n)}}class f9{constructor(e){this.delegateCryptoCallbacks=e,v(this,"privateKeys",new Map)}getSecretStorageKey(e,t){var n=this;return w(function*(){var i,{keys:o}=e;for(var s of Object.keys(o)){var a=n.privateKeys.get(s);if(a)return[s,a]}if(n!=null&&(i=n.delegateCryptoCallbacks)!==null&&i!==void 0&&i.getSecretStorageKey){var l=yield n.delegateCryptoCallbacks.getSecretStorageKey({keys:o},t);if(l){var[c,u]=l;n.privateKeys.set(c,u)}return l}return null})()}addPrivateKey(e,t,n){var i,o;this.privateKeys.set(e,n),(i=this.delegateCryptoCallbacks)===null||i===void 0||(o=i.cacheSecretStorageKey)===null||o===void 0||o.call(i,e,t,n)}}var $i="m.secret_storage.v1.aes-hmac-sha2";class Vd{constructor(e,t){this.accountDataAdapter=e,this.callbacks=t}getDefaultKeyId(){var e=this;return w(function*(){var t=yield e.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return t?t.key:null})()}setDefaultKeyId(e){return new Promise((t,n)=>{var i=o=>{o.getType()==="m.secret_storage.default_key"&&o.getContent().key===e&&(this.accountDataAdapter.removeListener(be.AccountData,i),t())};this.accountDataAdapter.on(be.AccountData,i),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:e}).catch(o=>{this.accountDataAdapter.removeListener(be.AccountData,i),n(o)})})}addKey(e,t,n){var i=this;return w(function*(){if(e!==$i)throw new Error("Unknown key algorithm ".concat(e));var o={algorithm:e};t.name&&(o.name=t.name),t.passphrase&&(o.passphrase=t.passphrase);var{iv:s,mac:a}=yield Ia(t.key);if(o.iv=s,o.mac=a,!n)do n=Ei(32);while(yield i.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key.".concat(n)));return yield i.accountDataAdapter.setAccountData("m.secret_storage.key.".concat(n),o),{keyId:n,keyInfo:o}})()}getKey(e){var t=this;return w(function*(){if(e||(e=yield t.getDefaultKeyId()),!e)return null;var n=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);return n?[e,n]:null})()}hasKey(e){var t=this;return w(function*(){var n=yield t.getKey(e);return!!n})()}checkKey(e,t){return w(function*(){if(t.algorithm===$i)if(t.mac){var{mac:n}=yield Ia(e,t.iv);return s_(t.mac)===s_(n)}else return!0;else throw new Error("Unknown algorithm")})()}store(e,t,n){var i=this;return w(function*(){var o={};if(!n){var s=yield i.getDefaultKeyId();if(!s)throw new Error("No keys specified and no default key present");n=[s]}if(n.length===0)throw new Error("Zero keys given to encrypt with!");for(var a of n){var l=yield i.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+a);if(!l)throw new Error("Unknown key: "+a);if(l.algorithm===$i){var c={[a]:l},[,u]=yield i.getSecretStorageKey(c,e);o[a]=yield u.encrypt(t)}else b.warn("unknown algorithm for secret storage key "+a+": "+l.algorithm)}yield i.accountDataAdapter.setAccountData(e,{encrypted:o})})()}get(e){var t=this;return w(function*(){var n=yield t.accountDataAdapter.getAccountDataFromServer(e);if(n){if(!n.encrypted)throw new Error("Content is not encrypted!");var i={};for(var o of Object.keys(n.encrypted)){var s=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+o),a=n.encrypted[o];(s==null?void 0:s.algorithm)===$i&&a.iv&&a.ciphertext&&a.mac&&(i[o]=s)}if(Object.keys(i).length===0)throw new Error("Could not decrypt ".concat(e," because none of ")+"the keys it is encrypted with are for a supported algorithm");var[l,c]=yield t.getSecretStorageKey(i,e),u=n.encrypted[l];return c.decrypt(u)}})()}isStored(e){var t=this;return w(function*(){var n=yield t.accountDataAdapter.getAccountDataFromServer(e);if(!(n!=null&&n.encrypted))return null;var i={};for(var o of Object.keys(n.encrypted)){var s=yield t.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+o);if(s){var a=n.encrypted[o];s.algorithm===$i&&a.iv&&a.ciphertext&&a.mac&&(i[o]=s)}}return Object.keys(i).length?i:null})()}getSecretStorageKey(e,t){var n=this;return w(function*(){if(!n.callbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");var i=yield n.callbacks.getSecretStorageKey({keys:e},t);if(!i)throw new Error("getSecretStorageKey callback returned falsey");if(i.length<2)throw new Error("getSecretStorageKey callback returned invalid data");var[o,s]=i;if(!e[o])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[o].algorithm===$i){var a={encrypt:function(c){return $c(c,s,t)},decrypt:function(c){return Cf(c,s,t)}};return[o,a]}else throw new Error("Unknown key type: "+e[o].algorithm)})()}}function s_(r){for(var e=r.length;e>=1&&r.charCodeAt(e-1)==61;)e--;return e<r.length?r.substring(0,e):r}var h9="\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 Ia(r,e){return $c(h9,r,"",e)}const p9=Object.freeze(Object.defineProperty({__proto__:null,SECRET_STORAGE_ALGORITHM_V1_AES:$i,ServerSideSecretStorageImpl:Vd,calculateKeyCheck:Ia,trimTrailingEquals:s_},Symbol.toStringTag,{value:"Module"}));class v9{constructor(e,t){this.baseApis=e,this.cryptoCallbacks=t,v(this,"requests",new Map)}request(e,t){var n=this.baseApis.makeTxnId(),i=Hs();this.requests.set(n,{name:e,devices:t,deferred:i});var o=c=>{var u={action:"request_cancellation",requesting_device_id:this.baseApis.deviceId,request_id:n},d=new Map;for(var f of t)d.set(f,u);this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),d]])),i.reject(new Error(c||"Cancelled"))},s={name:e,action:"request",requesting_device_id:this.baseApis.deviceId,request_id:n,[tn]:_i()},a=new Map;for(var l of t)a.set(l,s);return b.info("Request secret ".concat(e," from ").concat(t,", id ").concat(n)),this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),a]])),{requestId:n,promise:i.promise,cancel:o}}onRequestReceived(e){var t=this;return w(function*(){var n=e.getSender(),i=e.getContent();if(!(n!==t.baseApis.getUserId()||!(i.name&&i.action&&i.requesting_device_id&&i.request_id))){var o=i.requesting_device_id;if(i.action!=="request_cancellation"){if(i.action==="request"){if(o===t.baseApis.deviceId||(b.info("received request for secret ("+n+", "+o+", "+i.request_id+")"),!t.cryptoCallbacks.onSecretRequested))return;var s=yield t.cryptoCallbacks.onSecretRequested(n,o,i.request_id,i.name,t.baseApis.checkDeviceTrust(n,o));if(s){b.info("Preparing ".concat(i.name," secret for ").concat(o));var a={type:"m.secret.send",content:{request_id:i.request_id,secret:s}},l={algorithm:wr,sender_key:t.baseApis.crypto.olmDevice.deviceCurve25519Key,ciphertext:{},[tn]:_i()};yield xo(t.baseApis.crypto.olmDevice,t.baseApis,new Map([[n,[t.baseApis.getStoredDevice(n,o)]]])),yield Ns(l.ciphertext,t.baseApis.getUserId(),t.baseApis.deviceId,t.baseApis.crypto.olmDevice,n,t.baseApis.getStoredDevice(n,o),a);var c=new Map([[n,new Map([[o,l]])]]);b.info("Sending ".concat(i.name," secret for ").concat(o)),t.baseApis.sendToDevice("m.room.encrypted",c)}else b.info("Request denied for ".concat(i.name," secret for ").concat(o))}}}})()}onSecretReceived(e){if(e.getSender()===this.baseApis.getUserId()){if(!Bw(e)){b.error("secret event not properly encrypted");return}var t=e.getContent(),n=this.baseApis.crypto.deviceList.getUserByIdentityKey(wr,e.getSenderKey()||"");if(n!==e.getSender()){b.error("sending device does not belong to the user it claims to be from");return}b.log("got secret share for request",t.request_id);var i=this.requests.get(t.request_id);if(i){var o=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(wr,e.getSenderKey());if(!o){b.log("secret share from unknown device with key",e.getSenderKey());return}if(!i.devices.includes(o.deviceId)){b.log("unsolicited secret share from device",o.deviceId);return}var s=this.baseApis.crypto.checkDeviceInfoTrust(e.getSender(),o);if(!s.isVerified()){b.log("secret share from unverified device");return}b.log("Successfully received secret ".concat(i.name," ")+"from ".concat(o.deviceId)),i.deferred.resolve(t.secret)}}}}class m9{constructor(e,t,n){v(this,"storageImpl",void 0),v(this,"sharingImpl",void 0),this.storageImpl=new Vd(e,t),this.sharingImpl=new v9(n,t)}getDefaultKeyId(){return this.storageImpl.getDefaultKeyId()}setDefaultKeyId(e){return this.storageImpl.setDefaultKeyId(e)}addKey(e,t,n){return this.storageImpl.addKey(e,t,n)}getKey(e){return this.storageImpl.getKey(e)}hasKey(e){return this.storageImpl.hasKey(e)}checkKey(e,t){return this.storageImpl.checkKey(e,t)}store(e,t,n){return this.storageImpl.store(e,t,n)}get(e){return this.storageImpl.get(e)}isStored(e){var t=this;return w(function*(){return t.storageImpl.isStored(e)})()}request(e,t){return this.sharingImpl.request(e,t)}onRequestReceived(e){return this.sharingImpl.onRequestReceived(e)}onSecretReceived(e){this.sharingImpl.onSecretReceived(e)}}function g9(r,e,t){var n=Object.assign({},{code:r,reason:e},t);return new pr({type:V.KeyVerificationCancel,content:n})}function Vo(r,e){return function(t){return g9(r,e,t)}}var FN=Vo("m.user","Cancelled by user"),y9=Vo("m.timeout","Timed out"),ad=Vo("m.unknown_method","Unknown method"),BN=Vo("m.unexpected_message","Unexpected message"),ya=Vo("m.key_mismatch","Key mismatch"),S9=Vo("m.invalid_message","Invalid message");function a_(r){var e=r.getContent();if(e){var{code:t,reason:n}=e;return{code:t,reason:n}}else return{code:"Unknown error",reason:"m.unknown"}}var Ek=new Error("Verification timed out");class l_ extends Error{constructor(e){super(),this.startEvent=e}}var b9=Om;class Gw extends Tt{constructor(e,t,n,i,o,s){super(),this.channel=e,this.baseApis=t,this.userId=n,this.deviceId=i,this.startEvent=o,this.request=s,v(this,"cancelled",!1),v(this,"_done",!1),v(this,"promise",null),v(this,"transactionTimeoutTimer",null),v(this,"expectedEvent",void 0),v(this,"resolve",void 0),v(this,"reject",void 0),v(this,"resolveEvent",void 0),v(this,"rejectEvent",void 0),v(this,"started",void 0),v(this,"doVerification",void 0)}get initiatedByMe(){if(!this.startEvent)return!0;var e=this.startEvent.getSender(),t=this.startEvent.getContent();return e===this.baseApis.getUserId()&&t.from_device===this.baseApis.getDeviceId()}get hasBeenCancelled(){return this.cancelled}resetTimer(){b.info("Refreshing/starting the verification transaction timeout timer"),this.transactionTimeoutTimer!==null&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout(()=>{!this._done&&!this.cancelled&&(b.info("Triggering verification timeout"),this.cancel(Ek))},10*60*1e3)}endTimer(){this.transactionTimeoutTimer!==null&&(clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=null)}send(e,t){return this.channel.send(e,t)}waitForEvent(e){if(this._done)return Promise.reject(new Error("Verification is already done"));var t=this.request.getEventFromOtherParty(e);return t?Promise.resolve(t):(this.expectedEvent=e,new Promise((n,i)=>{this.resolveEvent=n,this.rejectEvent=i}))}canSwitchStartEvent(e){return!1}switchStartEvent(e){if(this.canSwitchStartEvent(e))if(b.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){var t=this.rejectEvent;this.rejectEvent=void 0,t(new l_(e))}else this.startEvent=e}handleEvent(e){if(!this._done){if(e.getType()===this.expectedEvent){if(this.expectedEvent!==V.KeyVerificationDone){var t;this.expectedEvent=void 0,this.rejectEvent=void 0,this.resetTimer(),(t=this.resolveEvent)===null||t===void 0||t.call(this,e)}}else if(e.getType()===V.KeyVerificationCancel){var n=this.reject;if(this.reject=void 0,n){var i=e.getContent(),{reason:o,code:s}=i;n(new Error("Other side cancelled verification "+"because ".concat(o," (").concat(s,")")))}}else if(this.expectedEvent){var a=new Error("Unexpected message: expecting "+this.expectedEvent+" but got "+e.getType());if(this.expectedEvent=void 0,this.rejectEvent){var l=this.rejectEvent;this.rejectEvent=void 0,l(a)}this.cancel(a)}}}done(){var e=this;return w(function*(){if(e.endTimer(),!e._done){var t;return e.request.onVerifierFinished(),(t=e.resolve)===null||t===void 0||t.call(e),H8(e.baseApis,e.userId,e.deviceId)}})()}cancel(e){if(this.endTimer(),!this._done){if(this.cancelled=!0,this.request.onVerifierCancelled(),this.userId&&this.deviceId)if(e===Ek){var t=y9();this.send(t.getType(),t.getContent())}else if(e instanceof pr){var n=e.getSender();if(n!==this.userId){var i=e.getContent();e.getType()===V.KeyVerificationCancel?(i.code=i.code||"m.unknown",i.reason=i.reason||i.body||"Unknown reason",this.send(V.KeyVerificationCancel,i)):this.send(V.KeyVerificationCancel,{code:"m.unknown",reason:i.body||"Unknown reason"})}}else this.send(V.KeyVerificationCancel,{code:"m.unknown",reason:e.toString()});this.promise!==null?this.reject&&this.reject(e):this.promise=Promise.reject(e),this.emit(b9.Cancel,e)}}verify(){var e=this;return this.promise?this.promise:(this.promise=new Promise((t,n)=>{this.resolve=function(){e._done=!0,e.endTimer(),t(...arguments)},this.reject=i=>{this._done=!0,this.endTimer(),n(i)}}),this.doVerification&&!this.started&&(this.started=!0,this.resetTimer(),new Promise((t,n)=>{var i,o=(i=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(this.userId))===null||i===void 0?void 0:i.getId();o===this.deviceId&&n(new Error("Device ID is the same as the cross-signing ID")),t()}).then(()=>this.doVerification()).then(this.done.bind(this),this.cancel.bind(this))),this.promise)}verifyKeys(e,t,n){var i=this;return w(function*(){var o=[];for(var[s,a]of Object.entries(t)){var l=s.split(":",2)[1],c=i.baseApis.getStoredDevice(e,l);if(c)n(s,c,a),o.push([l,s,c.keys[s]]);else{var u=i.baseApis.crypto.deviceList.getStoredCrossSigningForUser(e);u&&u.getId()===l?(n(s,rn.fromStorage({keys:{[s]:l}},l),a),o.push([l,s,l])):b.warn("verification: Could not find device ".concat(l," to verify"))}}if(!o.length)throw new Error("No devices could be verified");b.info("Verification completed! Marking devices verified: ",o);for(var[d,f,p]of o)yield i.baseApis.crypto.setDeviceVerification(e,d,!0,null,null,{[f]:p});e==i.baseApis.credentials.userId&&(yield i.baseApis.checkKeyBackup())})()}get events(){}getShowSasCallbacks(){return null}getReciprocateQrCodeCallbacks(){return null}}var Hw=function(r){return r.Sas="m.sas.v1",r.ShowQrCode="m.qr_code.show.v1",r.ScanQrCode="m.qr_code.scan.v1",r.Reciprocate="m.reciprocate.v1",r}({}),_9=Hw.ShowQrCode,KN=Hw.ScanQrCode,E9=Om;class $d extends Gw{constructor(){var e;super(...arguments),e=this,v(this,"reciprocateQREvent",void 0),v(this,"doVerification",w(function*(){if(!e.startEvent)throw new Error("It is not currently possible to start verificationwith this method yet.");var{qrCodeData:t}=e.request;if(e.startEvent.getContent().secret!==(t==null?void 0:t.encodedSharedSecret))throw ya();yield new Promise((a,l)=>{e.reciprocateQREvent={confirm:a,cancel:()=>l(FN())},e.emit(E9.ShowReciprocateQr,e.reciprocateQREvent)});var n={};switch(t==null?void 0:t.mode){case An.VerifyOtherUser:{var i=t.otherUserMasterKey;n["ed25519:".concat(i)]=i;break}case An.VerifySelfTrusted:{var o=e.request.targetDevice.deviceId;n["ed25519:".concat(o)]=t.otherDeviceKey;break}case An.VerifySelfUntrusted:{var s=t.myMasterKey;n["ed25519:".concat(s)]=s;break}}yield e.verifyKeys(e.userId,n,(a,l,c)=>{var u=n[a];if(!u)throw ya();if(c!==u)throw b.error("key ID from key info does not match"),ya();for(var d in l.keys)if(d.startsWith("ed25519")){var f=n[d];if(!f)throw ya();if(l.keys[d]!==f)throw b.error("master key does not match"),ya()}})}))}static factory(e,t,n,i,o,s){return new $d(e,t,n,i,o,s)}static get NAME(){return"m.reciprocate.v1"}getReciprocateQrCodeCallbacks(){var e;return(e=this.reciprocateQREvent)!==null&&e!==void 0?e:null}}var w9=2,T9="MATRIX",An=function(r){return r[r.VerifyOtherUser=0]="VerifyOtherUser",r[r.VerifySelfTrusted=1]="VerifySelfTrusted",r[r.VerifySelfUntrusted=2]="VerifySelfUntrusted",r}(An||{});class us{constructor(e,t,n,i,o,s){this.mode=e,this.sharedSecret=t,this.otherUserMasterKey=n,this.otherDeviceKey=i,this.myMasterKey=o,this.buffer=s}static create(e,t){return w(function*(){var n=us.generateSharedSecret(),i=us.determineMode(e,t),o=null,s=null,a=null;if(i===An.VerifyOtherUser){var l=t.getStoredCrossSigningForUser(e.otherUserId);o=l.getId("master")}else if(i===An.VerifySelfTrusted)s=yield us.getOtherDeviceKey(e,t);else if(i===An.VerifySelfUntrusted){var c=t.getUserId(),u=t.getStoredCrossSigningForUser(c);a=u.getId("master")}var d=us.generateQrData(e,t,i,n,o,s,a),f=us.generateBuffer(d);return new us(i,n,o,s,a,f)})()}get encodedSharedSecret(){return this.sharedSecret}getBuffer(){return this.buffer}static generateSharedSecret(){var e=new Uint8Array(11);return globalThis.crypto.getRandomValues(e),Rm(e)}static getOtherDeviceKey(e,t){return w(function*(){var n=t.getUserId(),i=e.targetDevice,o=i.deviceId?t.getStoredDevice(n,i.deviceId):void 0;if(!o)throw new Error("could not find device "+(i==null?void 0:i.deviceId));return o.getFingerprint()})()}static determineMode(e,t){var n=t.getUserId(),i=e.otherUserId,o=An.VerifyOtherUser;if(n===i){var s=t.checkUserTrust(n);s.isCrossSigningVerified()?o=An.VerifySelfTrusted:o=An.VerifySelfUntrusted}return o}static generateQrData(e,t,n,i,o,s,a){var l=t.getUserId(),c=e.channel.transactionId,u={prefix:T9,version:w9,mode:n,transactionId:c,firstKeyB64:"",secondKeyB64:"",secretB64:i},d=t.getStoredCrossSigningForUser(l);return n===An.VerifyOtherUser?(u.firstKeyB64=d.getId("master"),u.secondKeyB64=o):n===An.VerifySelfTrusted?(u.firstKeyB64=d.getId("master"),u.secondKeyB64=s):n===An.VerifySelfUntrusted&&(u.firstKeyB64=t.getDeviceEd25519Key(),u.secondKeyB64=a),u}static generateBuffer(e){var t=Buffer.alloc(0),n=a=>{var l=Buffer.from([a]);t=Buffer.concat([t,l])},i=a=>{var l=Buffer.alloc(2);l.writeInt16BE(a,0),t=Buffer.concat([t,l])},o=function(l,c){var u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,d=Buffer.from(l,c);u&&i(d.byteLength),t=Buffer.concat([t,d])},s=a=>{var l=Dr(a),c=Buffer.from(l);t=Buffer.concat([t,c])};return o(e.prefix,"ascii",!1),n(e.version),n(e.mode),o(e.transactionId,"utf-8"),s(e.firstKeyB64),s(e.secondKeyB64),s(e.secretB64),t}}function R9(r){return[(r[0]<<5|r[1]>>3)+1e3,((r[1]&7)<<10|r[2]<<2|r[3]>>6)+1e3,((r[3]&63)<<7|r[4]>>1)+1e3]}var cy=V.KeyVerificationStart,C9=[V.KeyVerificationAccept,V.KeyVerificationKey,V.KeyVerificationMac],wh,k9=Vo("m.mismatched_sas","Mismatched short authentication string"),I9=Vo("m.mismatched_commitment","Mismatched commitment"),x9=[["🐶","dog"],["🐱","cat"],["🦁","lion"],["🐎","horse"],["🦄","unicorn"],["🐷","pig"],["🐘","elephant"],["🐰","rabbit"],["🐼","panda"],["🐓","rooster"],["🐧","penguin"],["🐢","turtle"],["🐟","fish"],["🐙","octopus"],["🦋","butterfly"],["🌷","flower"],["🌳","tree"],["🌵","cactus"],["🍄","mushroom"],["🌏","globe"],["🌙","moon"],["☁️","cloud"],["🔥","fire"],["🍌","banana"],["🍎","apple"],["🍓","strawberry"],["🌽","corn"],["🍕","pizza"],["🎂","cake"],["❤️","heart"],["😀","smiley"],["🤖","robot"],["🎩","hat"],["👓","glasses"],["🔧","spanner"],["🎅","santa"],["👍","thumbs up"],["☂️","umbrella"],["⌛","hourglass"],["⏰","clock"],["🎁","gift"],["💡","light bulb"],["📕","book"],["✏️","pencil"],["📎","paperclip"],["✂️","scissors"],["🔒","lock"],["🔑","key"],["🔨","hammer"],["☎️","telephone"],["🏁","flag"],["🚂","train"],["🚲","bicycle"],["✈️","aeroplane"],["🚀","rocket"],["🏆","trophy"],["⚽","ball"],["🎸","guitar"],["🎺","trumpet"],["🔔","bell"],["⚓","anchor"],["🎧","headphones"],["📁","folder"],["📌","pin"]];function O9(r){var e=[r[0]>>2,(r[0]&3)<<4|r[1]>>4,(r[1]&15)<<2|r[2]>>6,r[2]&63,r[3]>>2,(r[3]&3)<<4|r[4]>>4,(r[4]&15)<<2|r[5]>>6];return e.map(t=>x9[t])}var c_={decimal:R9,emoji:O9};function P9(r,e){var t={};for(var n of e)n in c_&&(t[n]=c_[n](Array.from(r)));return t}var M9={"hkdf-hmac-sha256":"calculate_mac","org.matrix.msc3783.hkdf-hmac-sha256":"calculate_mac_fixed_base64","hkdf-hmac-sha256.v2":"calculate_mac_fixed_base64","hmac-sha256":"calculate_mac_long_kdf"};function hu(r,e){return function(t,n){var i=r[M9[e]](t,n);return b.log("SAS calculateMAC:",e,[t,n],i),i}}var A9={"curve25519-hkdf-sha256":function(e,t,n){var i="".concat(e.baseApis.getUserId(),"|").concat(e.baseApis.deviceId,"|")+"".concat(e.ourSASPubKey,"|"),o="".concat(e.userId,"|").concat(e.deviceId,"|").concat(e.theirSASPubKey,"|"),s="MATRIX_KEY_VERIFICATION_SAS|"+(e.initiatedByMe?i+o:o+i)+e.channel.transactionId;return t.generate_bytes(s,n)},curve25519:function(e,t,n){var i="".concat(e.baseApis.getUserId()).concat(e.baseApis.deviceId),o="".concat(e.userId).concat(e.deviceId),s="MATRIX_KEY_VERIFICATION_SAS"+(e.initiatedByMe?i+o:o+i)+e.channel.transactionId;return t.generate_bytes(s,n)}},u_=["curve25519-hkdf-sha256","curve25519"],d_=["sha256"],f_=["hkdf-hmac-sha256.v2","org.matrix.msc3783.hkdf-hmac-sha256","hkdf-hmac-sha256","hmac-sha256"],VN=Object.keys(c_),D9=new Set(u_),N9=new Set(d_),L9=new Set(f_),wk=new Set(VN);function pu(r,e){return Array.isArray(r)?r.filter(t=>e.has(t)):[]}var U9=Om;class wc extends Gw{constructor(){var e;super(...arguments),e=this,v(this,"waitingForAccept",void 0),v(this,"ourSASPubKey",void 0),v(this,"theirSASPubKey",void 0),v(this,"sasEvent",void 0),v(this,"doVerification",w(function*(){yield globalThis.Olm.init(),wh=wh||new globalThis.Olm.Utility,yield e.baseApis.downloadKeys([e.userId]);var t=!1;do try{return e.initiatedByMe?yield e.doSendVerification():yield e.doRespondVerification()}catch(n){if(n instanceof l_)e.startEvent=n.startEvent,t=!0;else throw n}while(t)}))}static get NAME(){return Hw.Sas}get events(){return C9}canSwitchStartEvent(e){if(e.getType()!==cy)return!1;var t=e.getContent();return(t==null?void 0:t.method)===wc.NAME&&!!this.waitingForAccept}sendStart(){var e=this;return w(function*(){var t=e.channel.completeContent(cy,{method:wc.NAME,from_device:e.baseApis.deviceId,key_agreement_protocols:u_,hashes:d_,message_authentication_codes:f_,short_authentication_string:VN});return yield e.channel.sendCompleted(cy,t),t})()}verifyAndCheckMAC(e,t,n,i){var o=this;return w(function*(){var s=A9[e](o,n,6),a=new Promise((u,d)=>{o.sasEvent={sas:P9(s,t),confirm:function(){var f=w(function*(){try{yield o.sendMAC(n,i),u()}catch(h){d(h)}});function p(){return f.apply(this,arguments)}return p}(),cancel:()=>d(FN()),mismatch:()=>d(k9())},o.emit(U9.ShowSas,o.sasEvent)}),[l]=yield Promise.all([o.waitForEvent(V.KeyVerificationMac).then(u=>(o.expectedEvent=V.KeyVerificationDone,u)),a]),c=l.getContent();yield o.checkMAC(n,c,i)})()}doSendVerification(){var e=this;return w(function*(){e.waitingForAccept=!0;var t;if(e.startEvent?t=e.channel.completedContentFromEvent(e.startEvent):t=yield e.sendStart(),!e.initiatedByMe)throw new l_(e.startEvent);var n;try{n=yield e.waitForEvent(V.KeyVerificationAccept)}finally{e.waitingForAccept=!1}var i=n.getContent(),o=pu(i.short_authentication_string,wk);if(!(D9.has(i.key_agreement_protocol)&&N9.has(i.hash)&&L9.has(i.message_authentication_code)&&o.length))throw ad();if(typeof i.commitment!="string")throw S9();var s=i.key_agreement_protocol,a=i.message_authentication_code,l=i.commitment,c=new globalThis.Olm.SAS;try{e.ourSASPubKey=c.get_pubkey(),yield e.send(V.KeyVerificationKey,{key:e.ourSASPubKey}),n=yield e.waitForEvent(V.KeyVerificationKey),i=n.getContent();var u=i.key+Io.stringify(t);if(wh.sha256(u)!==l)throw I9();e.theirSASPubKey=i.key,c.set_their_key(i.key),yield e.verifyAndCheckMAC(s,o,c,a)}finally{c.free()}})()}doRespondVerification(){var e=this;return w(function*(){var t=e.channel.completedContentFromEvent(e.startEvent),n=pu(u_,new Set(t.key_agreement_protocols))[0],i=pu(d_,new Set(t.hashes))[0],o=pu(f_,new Set(t.message_authentication_codes))[0],s=pu(t.short_authentication_string,wk);if(!(n!==void 0&&i!==void 0&&o!==void 0&&s.length))throw ad();var a=new globalThis.Olm.SAS;try{var l=a.get_pubkey()+Io.stringify(t);yield e.send(V.KeyVerificationAccept,{key_agreement_protocol:n,hash:i,message_authentication_code:o,short_authentication_string:s,commitment:wh.sha256(l)});var c=yield e.waitForEvent(V.KeyVerificationKey);t=c.getContent(),e.theirSASPubKey=t.key,a.set_their_key(t.key),e.ourSASPubKey=a.get_pubkey(),yield e.send(V.KeyVerificationKey,{key:e.ourSASPubKey}),yield e.verifyAndCheckMAC(n,s,a,o)}finally{a.free()}})()}sendMAC(e,t){var n={},i=[],o="MATRIX_KEY_VERIFICATION_MAC"+this.baseApis.getUserId()+this.baseApis.deviceId+this.userId+this.deviceId+this.channel.transactionId,s="ed25519:".concat(this.baseApis.deviceId);n[s]=hu(e,t)(this.baseApis.getDeviceEd25519Key(),o+s),i.push(s);var a=this.baseApis.getCrossSigningId();if(a){var l="ed25519:".concat(a);n[l]=hu(e,t)(a,o+l),i.push(l)}var c=hu(e,t)(i.sort().join(","),o+"KEY_IDS");return this.send(V.KeyVerificationMac,{mac:n,keys:c})}checkMAC(e,t,n){var i=this;return w(function*(){var o="MATRIX_KEY_VERIFICATION_MAC"+i.userId+i.deviceId+i.baseApis.getUserId()+i.baseApis.deviceId+i.channel.transactionId;if(t.keys!==hu(e,n)(Object.keys(t.mac).sort().join(","),o+"KEY_IDS"))throw ya();yield i.verifyKeys(i.userId,t.mac,(s,a,l)=>{if(l!==hu(e,n)(a.keys[s],o+s))throw ya()})})()}getShowSasCallbacks(){var e;return(e=this.sasEvent)!==null&&e!==void 0?e:null}}function Tk(r,e){if(!r.private_key_salt||!r.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return $w(e,r.private_key_salt,r.private_key_iterations,r.private_key_bits)}var Rk=5e5;function zw(r){return h_.apply(this,arguments)}function h_(){return h_=w(function*(r){var e=Ei(32),t=yield $w(r,e,Rk);return{key:t,salt:e,iterations:Rk}}),h_.apply(this,arguments)}var j9=10*60*1e3,F9=2*60*1e3,B9=3*1e3,Wc="m.key.verification.",at=Wc+"request",Sr=Wc+"start",yi=Wc+"cancel",K9=Wc+"done",pi=Wc+"ready",uo=zs.Unsent,ai=zs.Requested,Fi=zs.Ready,go=zs.Started,vu=zs.Cancelled,mu=zs.Done;class Sa extends Tt{constructor(e,t,n){var i;super(),i=this,this.channel=e,this.verificationMethods=t,this.client=n,v(this,"eventsByUs",new Map),v(this,"eventsByThem",new Map),v(this,"_observeOnly",!1),v(this,"timeoutTimer",null),v(this,"_accepting",!1),v(this,"_declining",!1),v(this,"verifierHasFinished",!1),v(this,"_cancelled",!1),v(this,"_chosenMethod",null),v(this,"_qrCodeData",null),v(this,"requestReceivedAt",null),v(this,"commonMethods",[]),v(this,"_phase",void 0),v(this,"_cancellingUserId",void 0),v(this,"_verifier",void 0),v(this,"cancelOnTimeout",w(function*(){try{i.initiatedByMe?yield i.cancel({reason:"Other party didn't accept in time",code:"m.timeout"}):yield i.cancel({reason:"User didn't accept in time",code:"m.timeout"})}catch(o){b.error("Error while cancelling verification request",o)}})),this.channel.request=this,this.setPhase(uo,!1)}static validateEvent(e,t,n){var i=t.getContent();return!e||!e.startsWith(Wc)?!1:i?(e===at||e===pi)&&!Array.isArray(i.methods)?(b.log("VerificationRequest: validateEvent: fail because methods"),!1):(e===at||e===pi||e===Sr)&&(typeof i.from_device!="string"||i.from_device.length===0)?(b.log("VerificationRequest: validateEvent: fail because from_device"),!1):!0:(b.log("VerificationRequest: validateEvent: no content"),!1)}get transactionId(){return this.channel.transactionId}get roomId(){return this.channel.roomId}get invalid(){return this.phase===uo}get requested(){return this.phase===ai}get cancelled(){return this.phase===vu}get ready(){return this.phase===Fi}get started(){return this.phase===go}get done(){return this.phase===mu}get methods(){return this.commonMethods}get chosenMethod(){return this._chosenMethod}calculateEventTimeout(e){var t=this.channel.getTimestamp(e)+j9;if(this.requestReceivedAt&&!this.initiatedByMe&&this.phase<=ai){var n=this.requestReceivedAt+F9;t=Math.min(t,n)}return Math.max(0,t-Date.now())}get timeout(){var e=this.getEventByEither(at);return e?this.calculateEventTimeout(e):0}get requestEvent(){return this.getEventByEither(at)}get phase(){return this._phase}get verifier(){return this._verifier}get canAccept(){return ON(this)}get accepting(){return this._accepting}get declining(){return this._declining}get pending(){return!this.observeOnly&&this._phase!==mu&&this._phase!==vu}get qrCodeData(){return this._qrCodeData}getQRCodeBytes(){var e;return(e=this._qrCodeData)===null||e===void 0?void 0:e.getBuffer()}generateQRCode(){var e=this;return w(function*(){return e.getQRCodeBytes()})()}otherPartySupportsMethod(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!t&&!this.ready&&!this.started)return!1;var n=this.eventsByThem.get(at)||this.eventsByThem.get(pi);if(!n){if(this.started&&this.initiatedByMe){var i=this.eventsByUs.get(Sr),o=i&&i.getContent(),s=o&&o.method;return e==s}return!1}var a=n.getContent();if(!a)return!1;var{methods:l}=a;return Array.isArray(l)?l.includes(e):!1}get initiatedByMe(){var e=this.eventsByUs.size+this.eventsByThem.size===0;if(this._phase===uo&&e)return!0;var t=this.eventsByUs.has(at),n=this.eventsByThem.has(at);if(t&&!n)return!0;if(!t&&n)return!1;var i=this.eventsByUs.has(Sr),o=this.eventsByThem.has(Sr);return!!(i&&!o)}get requestingUserId(){return this.initiatedByMe?this.client.getUserId():this.otherUserId}get receivingUserId(){return this.initiatedByMe?this.otherUserId:this.client.getUserId()}get otherUserId(){return this.channel.userId}get otherDeviceId(){return this.channel.deviceId}get isSelfVerification(){return this.client.getUserId()===this.otherUserId}get cancellingUserId(){var e=this.eventsByUs.get(yi),t=this.eventsByThem.get(yi);if(e&&(!t||e.getId()<t.getId()))return e.getSender();if(t)return t.getSender()}get cancellationCode(){var e=this.getEventByEither(yi);return e?e.getContent().code:null}get observeOnly(){return this._observeOnly}get targetDevice(){var e=this.eventsByThem.get(at)||this.eventsByThem.get(pi)||this.eventsByThem.get(Sr),t=e==null?void 0:e.getContent(),n=t==null?void 0:t.from_device;return{userId:this.otherUserId,deviceId:n}}beginKeyVerification(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(!this.observeOnly&&!this._verifier){var n=this.phase===ai||this.phase===Fi||this.phase===uo&&this.channel.canCreateRequest(Sr);if(n){if(this.commonMethods.length&&!this.commonMethods.includes(e)||(this._verifier=this.createVerifier(e,null,t),!this._verifier))throw ad();this._chosenMethod=e}}return this._verifier}startVerification(e){var t=this;return w(function*(){var n=t.beginKeyVerification(e);return n.verify(),n})()}scanQRCode(e){throw new Error("QR code scanning not supported by legacy crypto")}sendRequest(){var e=this;return w(function*(){if(!e.observeOnly&&e._phase===uo){var t=[...e.verificationMethods.keys()];yield e.channel.send(at,{methods:t})}})()}cancel(){var e=arguments,t=this;return w(function*(){var{reason:n="User declined",code:i="m.user"}=e.length>0&&e[0]!==void 0?e[0]:{};if(!t.observeOnly&&t._phase!==vu){if(t._declining=!0,t.emit(pa.Change),t._verifier)return t._verifier.cancel(Vo(i,n)());t._cancellingUserId=t.client.getUserId(),yield t.channel.send(yi,{code:i,reason:n})}})()}accept(){var e=this;return w(function*(){if(!e.observeOnly&&e.phase===ai&&!e.initiatedByMe){var t=[...e.verificationMethods.keys()];e._accepting=!0,e.emit(pa.Change),yield e.channel.send(pi,{methods:t})}})()}waitFor(e){return new Promise((t,n)=>{var i=()=>{var o=!1;return e(this)?(t(this),o=!0):this.cancelled&&(n(new Error("cancelled")),o=!0),o&&this.off(pa.Change,i),o};i()||this.on(pa.Change,i)})}setPhase(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;this._phase=e,t&&this.emit(pa.Change)}getEventByEither(e){return this.eventsByThem.get(e)||this.eventsByUs.get(e)}getEventBy(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return t?this.eventsByThem.get(e):this.eventsByUs.get(e)}calculatePhaseTransitions(){var e=[{phase:uo}],t=()=>e[e.length-1].phase,n=this.eventsByThem.has(at),i=this.getEventBy(at,n);i&&e.push({phase:ai,event:i});var o=i&&this.getEventBy(pi,!n);o&&t()===ai&&e.push({phase:Fi,event:o});var s;if(o||!i){var a=this.eventsByThem.get(Sr),l=this.eventsByUs.get(Sr);a&&l?s=a.getSender()<l.getSender()?a:l:s=a||l}else s=this.getEventBy(Sr,!n);if(s){var c=t()===ai&&(i==null?void 0:i.getSender())!==s.getSender(),u=t()===uo&&this.channel.canCreateRequest(Sr);(c||t()===Fi||u)&&e.push({phase:go,event:s})}var d=this.eventsByUs.get(K9);(this.verifierHasFinished||d&&t()===go)&&e.push({phase:mu});var f=this.getEventByEither(yi);return(this._cancelled||f)&&t()!==mu&&e.push({phase:vu,event:f}),e}transitionToPhase(e){var{phase:t,event:n}=e;if((t===ai||t===Fi)&&!this.wasSentByOwnDevice(n)){var i=n.getContent();this.commonMethods=i.methods.filter(s=>this.verificationMethods.has(s))}if(this.observeOnly||(t===ai||t===go||t===Fi)&&this.channel.receiveStartFromOtherDevices&&this.wasSentByOwnUser(n)&&!this.wasSentByOwnDevice(n)&&(this._observeOnly=!0),t===go){var{method:o}=n.getContent();!this._verifier&&!this.observeOnly&&(this._verifier=this.createVerifier(o,n),this._verifier?this._chosenMethod=o:this.cancel({code:"m.unknown_method",reason:"Unknown method: ".concat(o)}))}}applyPhaseTransitions(){var e=this.calculatePhaseTransitions(),t=e.findIndex(o=>o.phase===this.phase),n=e.slice(t+1);for(var i of n)this.transitionToPhase(i);return n}isWinningStartRace(e){if(e.getType()!==Sr)return!1;var t=this._verifier.startEvent,n;if(this.isSelfVerification)if(t){var i=t.getContent();n=i&&i.from_device}else n=this.client.getDeviceId();else t?n=t.getSender():n=this.client.getUserId();var o;if(this.isSelfVerification){var s=e.getContent();o=s&&s.from_device}else o=e.getSender();return o<n}hasEventId(e){for(var t of this.eventsByUs.values())if(t.getId()===e)return!0;for(var n of this.eventsByThem.values())if(n.getId()===e)return!0;return!1}handleEvent(e,t,n,i,o){var s=this;return w(function*(){if(!(s.done||s.cancelled)){var a=s._observeOnly;if(s.adjustObserveOnly(t,n),!(!s.observeOnly&&!i&&(yield s.cancelOnError(e,t)))){var l=o?s.eventsByUs.has(e):s.eventsByThem.has(e);if(!l){var c=s.phase;s.addEvent(e,t,o);var u=s.applyPhaseTransitions();try{if(s._verifier&&!s.observeOnly){var d=s.isWinningStartRace(t);if(s._verifier.canSwitchStartEvent(t)&&d)s._verifier.switchStartEvent(t);else if(!i){var f;(e===yi||(f=s._verifier.events)!==null&&f!==void 0&&f.includes(e))&&s._verifier.handleEvent(t)}}if(u.length){if(n&&u.some(E=>E.phase===Fi)){var p=s.otherPartySupportsMethod(KN,!0);p&&(s._qrCodeData=yield us.create(s,s.client))}var h=u[u.length-1],{phase:m}=h;s.setupTimeout(m),s.setPhase(m)}else s._observeOnly!==a&&s.emit(pa.Change)}finally{b.log("Verification request ".concat(s.channel.transactionId,": ")+"".concat(e," event with id:").concat(t.getId(),", ")+"content:".concat(JSON.stringify(t.getContent())," ")+"deviceId:".concat(s.channel.deviceId,", ")+"sender:".concat(t.getSender(),", isSentByUs:").concat(o,", ")+"isLiveEvent:".concat(n,", isRemoteEcho:").concat(i,", ")+"phase:".concat(c,"=>").concat(s.phase,", ")+"observeOnly:".concat(a,"=>").concat(s._observeOnly))}}}}})()}setupTimeout(e){var t=!this.timeoutTimer&&!this.observeOnly&&e===ai;if(t&&(this.timeoutTimer=setTimeout(this.cancelOnTimeout,this.timeout)),this.timeoutTimer){var n=e===go||e===Fi||e===mu||e===vu;n&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null)}}cancelOnError(e,t){var n=this;return w(function*(){if(e===Sr){var i=t.getContent().method;if(!n.verificationMethods.has(i))return yield n.cancel(a_(ad())),!0}var o=e===at&&n.phase!==uo,s=e===pi&&n.phase!==ai&&n.phase!==go;if(n.phase!==uo&&(o||s)){b.warn("Cancelling, unexpected ".concat(e," verification ")+"event from ".concat(t.getSender()));var a="Unexpected ".concat(e," event in phase ").concat(n.phase);return yield n.cancel(a_(BN({reason:a}))),!0}return!1})()}adjustObserveOnly(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;t||(this._observeOnly=!0),this.calculateEventTimeout(e)<B9&&(this._observeOnly=!0)}addEvent(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(n?this.eventsByUs.set(e,t):this.eventsByThem.set(e,t),e===at){for(var[i,o]of this.eventsByThem.entries())o.getSender()!==this.otherUserId&&this.eventsByThem.delete(i);this.requestReceivedAt=Date.now()}}createVerifier(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;n||(n=this.targetDevice);var{userId:i,deviceId:o}=n,s=this.verificationMethods.get(e);if(!s){b.warn("could not find verifier constructor for method",e);return}return new s(this.channel,this.client,i,o,t,this)}wasSentByOwnUser(e){return(e==null?void 0:e.getSender())===this.client.getUserId()}wasSentByOwnDevice(e){if(!this.wasSentByOwnUser(e))return!1;var t=e.getContent();return!(!t||t.from_device!==this.client.getDeviceId())}onVerifierCancelled(){this._cancelled=!0;var e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}onVerifierFinished(){this.channel.send(V.KeyVerificationDone,{}),this.verifierHasFinished=!0;var e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}getEventFromOtherParty(e){return this.eventsByThem.get(e)}}var Ck=V.RoomMessage,kk="m.reference",Ik="m.relates_to";class Kr{constructor(e,t,n){this.client=e,this.roomId=t,this.userId=n,v(this,"requestEventId",void 0)}get receiveStartFromOtherDevices(){return!0}get transactionId(){return this.requestEventId}static getOtherPartyUserId(e,t){var n=Kr.getEventType(e);if(n===at){var i=t.getUserId(),o=e.getSender(),s=e.getContent(),a=s.to;if(o===i)return a;if(a===i)return o}}getTimestamp(e){return e.getTs()}static canCreateRequest(e){return e===at}canCreateRequest(e){return Kr.canCreateRequest(e)}static getTransactionId(e){if(Kr.getEventType(e)===at)return e.getId();var t=e.getRelation();if((t==null?void 0:t.rel_type)===kk)return t.event_id}static validateEvent(e,t){var n=Kr.getTransactionId(e);if(typeof n!="string"||n.length===0)return!1;var i=Kr.getEventType(e),o=e.getContent();if(i===at){if(!o||typeof o.to!="string"||!o.to.length)return b.log("InRoomChannel: validateEvent: no valid to "+o.to),!1;if(!Kr.getOtherPartyUserId(e,t))return b.log("InRoomChannel: validateEvent: "+"not directed to or sent by me: ".concat(e.getSender())+", ".concat(o.to)),!1}return Sa.validateEvent(i,e,t)}static getEventType(e){var t=e.getType();if(t===Ck){var n=e.getContent();if(n){var{msgtype:i}=n;if(i===at)return at}}return t&&t!==at?t:""}handleEvent(e,t){var n=arguments,i=this;return w(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!1;if(!t.hasEventId(e.getId())){var s=Kr.getEventType(e);if(e.getRoomId()===i.roomId){if(!i.userId){var a=Kr.getOtherPartyUserId(e,i.client);a&&(i.userId=a)}var l=i.client.getUserId(),c=e.getSender();if(i.userId&&c!==l&&c!==i.userId){b.log("InRoomChannel: ignoring verification event from non-participating sender ".concat(c));return}i.requestEventId||(i.requestEventId=Kr.getTransactionId(e));var u=!!e.getTxnId(),d=!!e.getUnsigned().transaction_id,f=e.getSender()===i.client.getUserId();return t.handleEvent(s,e,o,u||d,f)}}})()}completedContentFromEvent(e){var t=Object.assign({},e.getContent());return t[Ik]=e.getRelation(),t}completeContent(e,t){return t=Object.assign({},t),(e===at||e===pi||e===Sr)&&(t.from_device=this.client.getDeviceId()),e===at?t={body:this.client.getUserId()+" is requesting to verify your key, but your client does not support in-chat key verification. You will need to use legacy key verification to verify keys.",msgtype:at,to:this.userId,from_device:t.from_device,methods:t.methods}:t[Ik]={rel_type:kk,event_id:this.transactionId},t}send(e,t){var n=this.completeContent(e,t);return this.sendCompleted(e,n)}sendCompleted(e,t){var n=this;return w(function*(){var i=e;e===at&&(i=Ck);var o=yield n.client.sendEvent(n.roomId,i,t);e===at&&(n.requestEventId=o.event_id)})()}}class V9{constructor(){v(this,"requestsByRoomId",new Map)}getRequest(e){var t=e.getRoomId(),n=Kr.getTransactionId(e);return this.getRequestByTxnId(t,n)}getRequestByChannel(e){return this.getRequestByTxnId(e.roomId,e.transactionId)}getRequestByTxnId(e,t){var n=this.requestsByRoomId.get(e);if(n)return n.get(t)}setRequest(e,t){this.doSetRequest(e.getRoomId(),Kr.getTransactionId(e),t)}setRequestByChannel(e,t){this.doSetRequest(e.roomId,e.transactionId,t)}doSetRequest(e,t,n){var i=this.requestsByRoomId.get(e);i||(i=new Map,this.requestsByRoomId.set(e,i)),i.set(t,n)}removeRequest(e){var t=e.getRoomId(),n=this.requestsByRoomId.get(t);n&&(n.delete(Kr.getTransactionId(e)),n.size===0&&this.requestsByRoomId.delete(t))}findRequestInProgress(e,t){var n=this.requestsByRoomId.get(e);if(n){for(var i of n.values())if(i.pending&&(t===void 0||i.requestingUserId===t))return i}}}class Br{constructor(e,t,n,i,o){this.client=e,this.userId=t,this.devices=n,this.transactionId=i,this.deviceId=o,v(this,"request",void 0)}isToDevices(e){if(e.length===this.devices.length){for(var t of e)if(!this.devices.includes(t))return!1;return!0}else return!1}static getEventType(e){return e.getType()}static getTransactionId(e){var t=e.getContent();return t&&t.transaction_id}static canCreateRequest(e){return e===at||e===Sr}canCreateRequest(e){return Br.canCreateRequest(e)}static validateEvent(e,t){if(e.isCancelled())return b.warn("Ignoring flagged verification request from "+e.getSender()),!1;var n=e.getContent();if(!n)return b.warn("ToDeviceChannel.validateEvent: invalid: no content"),!1;if(!n.transaction_id)return b.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"),!1;var i=e.getType();if(i===at){if(!Number.isFinite(n.timestamp))return b.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"),!1;if(e.getSender()===t.getUserId()&&n.from_device==t.getDeviceId())return b.warn("ToDeviceChannel.validateEvent: invalid: from own device"),!1}return Sa.validateEvent(i,e,t)}getTimestamp(e){var t=e.getContent();return t&&t.timestamp}handleEvent(e,t){var n=arguments,i=this;return w(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!1,s=e.getType(),a=e.getContent();if(s===at||s===pi||s===Sr){i.transactionId||(i.transactionId=a.transaction_id);var l=a.from_device;if(!i.deviceId&&i.devices.includes(l)&&(i.deviceId=l),!i.deviceId||i.deviceId!==l){var c=i.completeContent(yi,a_(BN()));return i.sendToDevices(yi,c,[l])}}var u=t.phase===go||t.phase===Fi;yield t.handleEvent(e.getType(),e,o,!1,!1);var d=t.phase===go||t.phase===Fi,f=s===Sr||s===pi;if(f&&!u&&d&&i.deviceId){var p=i.devices.filter(m=>m!==i.deviceId&&m!==i.client.getDeviceId());if(p.length){var h=i.completeContent(yi,{code:"m.accepted",reason:"Verification request accepted by another device"});yield i.sendToDevices(yi,h,p)}}})()}completedContentFromEvent(e){return e.getContent()}completeContent(e,t){return t=Object.assign({},t),this.transactionId&&(t.transaction_id=this.transactionId),(e===at||e===pi||e===Sr)&&(t.from_device=this.client.getDeviceId()),e===at&&(t.timestamp=Date.now()),t}send(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};(e===at||e===Sr)&&!this.transactionId&&(this.transactionId=Br.makeTransactionId());var n=this.completeContent(e,t);return this.sendCompleted(e,n)}sendCompleted(e,t){var n=this;return w(function*(){var i;e===at||e===yi&&!n.deviceId?i=yield n.sendToDevices(e,t,n.devices):i=yield n.sendToDevices(e,t,[n.deviceId]);var o=new pr({sender:n.client.getUserId(),content:t,type:e});return yield n.request.handleEvent(e,o,!0,!0,!0),i})()}sendToDevices(e,t,n){var i=this;return w(function*(){if(n.length){var o=new Map;for(var s of n)o.set(s,t);yield i.client.sendToDevice(e,new Map([[i.userId,o]]))}})()}static makeTransactionId(){return Ei(32)}}class $9{constructor(){v(this,"requestsByUserId",new Map)}getRequest(e){return this.getRequestBySenderAndTxnId(e.getSender(),Br.getTransactionId(e))}getRequestByChannel(e){return this.getRequestBySenderAndTxnId(e.userId,e.transactionId)}getRequestBySenderAndTxnId(e,t){var n=this.requestsByUserId.get(e);if(n)return n.get(t)}setRequest(e,t){this.setRequestBySenderAndTxnId(e.getSender(),Br.getTransactionId(e),t)}setRequestByChannel(e,t){this.setRequestBySenderAndTxnId(e.userId,e.transactionId,t)}setRequestBySenderAndTxnId(e,t,n){var i=this.requestsByUserId.get(e);i||(i=new Map,this.requestsByUserId.set(e,i)),i.set(t,n)}removeRequest(e){var t=e.getSender(),n=this.requestsByUserId.get(t);n&&(n.delete(Br.getTransactionId(e)),n.size===0&&this.requestsByUserId.delete(t))}findRequestInProgress(e,t){var n=this.requestsByUserId.get(e);if(n){for(var i of n.values())if(i.pending&&i.channel.isToDevices(t))return i}}getRequestsInProgress(e){var t=this.requestsByUserId.get(e);return t?Array.from(t.values()).filter(n=>n.pending):[]}}class vv extends Gw{constructor(){super(...arguments),v(this,"doVerification",w(function*(){throw new Error("Verification is not possible with this method")}))}static factory(e,t,n,i,o,s){return new vv(e,t,n,i,o,s)}static get NAME(){return"org.matrix.illegal_method"}}var ip="org.matrix.msc2697.v1.olm.libolm_pickle",xk=7*24*60*60*1e3;class W9{constructor(e){this.crypto=e,v(this,"inProgress",!1),v(this,"timeoutId",void 0),v(this,"key",void 0),v(this,"keyInfo",void 0),v(this,"deviceDisplayName",void 0),this.getDehydrationKeyFromCache()}getDehydrationKeyFromCache(){var e=this;return this.crypto.cryptoStore.doTxn("readonly",[_e.STORE_ACCOUNT],t=>{this.crypto.cryptoStore.getSecretStorePrivateKey(t,function(){var n=w(function*(i){if(i){var{key:o,keyInfo:s,deviceDisplayName:a,time:l}=i,c=Buffer.from(e.crypto.olmDevice.pickleKey),u=yield Cf(o,c,ip);e.key=Dr(u),e.keyInfo=s,e.deviceDisplayName=a;var d=Date.now(),f=Math.max(1,l+xk-d);e.timeoutId=globalThis.setTimeout(e.dehydrateDevice.bind(e),f)}});return function(i){return n.apply(this,arguments)}}(),"dehydration")})}setKeyAndQueueDehydration(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{},o=t.length>2?t[2]:void 0,s=yield n.setKey(e,i,o);s||n.dehydrateDevice()})()}setKey(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{},o=t.length>2?t[2]:void 0;if(!e){n.timeoutId&&(globalThis.clearTimeout(n.timeoutId),n.timeoutId=void 0),yield n.crypto.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],l=>{n.crypto.cryptoStore.storeSecretStorePrivateKey(l,"dehydration",null)}),n.key=void 0,n.keyInfo=void 0;return}for(var s=!!n.key&&e.length==n.key.length,a=0;s&&a<e.length;a++)e[a]!=n.key[a]&&(s=!1);return s||(n.key=e,n.keyInfo=i,n.deviceDisplayName=o),s})()}dehydrateDevice(){var e=this;return w(function*(){if(e.inProgress){b.log("Dehydration already in progress -- not starting new dehydration");return}e.inProgress=!0,e.timeoutId&&(globalThis.clearTimeout(e.timeoutId),e.timeoutId=void 0);try{var t=Buffer.from(e.crypto.olmDevice.pickleKey),n=yield $c(Zr(e.key),t,ip);yield e.crypto.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],N=>{e.crypto.cryptoStore.storeSecretStorePrivateKey(N,"dehydration",{keyInfo:e.keyInfo,key:n,deviceDisplayName:e.deviceDisplayName,time:Date.now()})}),b.log("Attempting to dehydrate device"),b.log("Creating account");var i=new globalThis.Olm.Account;i.create();var o=JSON.parse(i.identity_keys()),s=i.max_number_of_one_time_keys();i.generate_one_time_keys(s/2),i.generate_fallback_key();var a=JSON.parse(i.one_time_keys()),l=JSON.parse(i.fallback_key());i.mark_keys_as_published();var c=i.pickle(new Uint8Array(e.key)),u={algorithm:ip,account:c};e.keyInfo.passphrase&&(u.passphrase=e.keyInfo.passphrase),b.log("Uploading account to server");var d=yield e.crypto.baseApis.http.authedRequest(Z.Put,"/dehydrated_device",void 0,{device_data:u,initial_device_display_name:e.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"}),f=d.device_id;b.log("Preparing device keys",f);var p={algorithms:e.crypto.supportedAlgorithms,device_id:f,user_id:e.crypto.userId,keys:{["ed25519:".concat(f)]:o.ed25519,["curve25519:".concat(f)]:o.curve25519}},h=i.sign(Io.stringify(p));p.signatures={[e.crypto.userId]:{["ed25519:".concat(f)]:h}},e.crypto.crossSigningInfo.getId("self_signing")&&(yield e.crypto.crossSigningInfo.signObject(p,"self_signing")),b.log("Preparing one-time keys");var m={};for(var[E,y]of Object.entries(a.curve25519)){var S={key:y},R=i.sign(Io.stringify(S));S.signatures={[e.crypto.userId]:{["ed25519:".concat(f)]:R}},m["signed_curve25519:".concat(E)]=S}b.log("Preparing fallback keys");var k={};for(var[x,T]of Object.entries(l.curve25519)){var O={key:T,fallback:!0},C=i.sign(Io.stringify(O));O.signatures={[e.crypto.userId]:{["ed25519:".concat(f)]:C}},k["signed_curve25519:".concat(x)]=O}return b.log("Uploading keys to server"),yield e.crypto.baseApis.http.authedRequest(Z.Post,"/keys/upload/"+encodeURI(f),void 0,{device_keys:p,one_time_keys:m,"org.matrix.msc2732.fallback_keys":k}),b.log("Done dehydrating"),e.timeoutId=globalThis.setTimeout(e.dehydrateDevice.bind(e),xk),f}finally{e.inProgress=!1}})()}stop(){this.timeoutId&&(globalThis.clearTimeout(this.timeoutId),this.timeoutId=void 0)}}var q9=200,G9=5e3;class xa{constructor(e,t){this.baseApis=e,this.getKey=t,v(this,"algorithm",void 0),v(this,"backupInfo",void 0),v(this,"checkedForBackup",void 0),v(this,"sendingBackups",void 0),v(this,"sessionLastCheckAttemptedTime",{}),v(this,"clientRunning",!0),this.checkedForBackup=!1,this.sendingBackups=!1}stop(){this.clientRunning=!1}get version(){return this.backupInfo&&this.backupInfo.version}static checkBackupVersion(e){var t=uy[e.algorithm];if(!t)throw new Error("Unknown backup algorithm: "+e.algorithm);if(typeof e.auth_data!="object")throw new Error("Invalid backup data returned");return t.checkBackupVersion(e)}static makeAlgorithm(e,t){var n=uy[e.algorithm];if(!n)throw new Error("Unknown backup algorithm");return n.init(e.auth_data,t)}enableKeyBackup(e){var t=this;return w(function*(){t.backupInfo=e,t.algorithm&&t.algorithm.free(),t.algorithm=yield xa.makeAlgorithm(e,t.getKey),t.baseApis.emit(et.KeyBackupStatus,!0),t.scheduleKeyBackupSend()})()}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit(et.KeyBackupStatus,!1)}getKeyBackupEnabled(){return this.checkedForBackup?!!this.algorithm:null}prepareKeyBackupVersion(e,t){return w(function*(){var n=t?uy[t]:Y9;if(!n)throw new Error("Unknown backup algorithm");var[i,o]=yield n.prepare(e),s=hv(i);return{algorithm:n.algorithmName,auth_data:o,recovery_key:s,privateKey:i}})()}createKeyBackupVersion(e){var t=this;return w(function*(){t.algorithm=yield xa.makeAlgorithm(e,t.getKey)})()}deleteAllKeyBackupVersions(){var e=this;return w(function*(){for(var t,n,i=(t=(n=yield e.baseApis.getKeyBackupVersion())===null||n===void 0?void 0:n.version)!==null&&t!==void 0?t:null;i!=null;){var o,s;yield e.deleteKeyBackupVersion(i),e.disableKeyBackup(),i=(o=(s=yield e.baseApis.getKeyBackupVersion())===null||s===void 0?void 0:s.version)!==null&&o!==void 0?o:null}})()}deleteKeyBackupVersion(e){var t=this;return w(function*(){var n=Se("/room_keys/version/$version",{$version:e});yield t.baseApis.http.authedRequest(Z.Delete,n,void 0,void 0,{prefix:Pt.V3})})()}checkAndStart(){var e=this;return w(function*(){if(b.log("Checking key backup status..."),e.baseApis.isGuest())return b.log("Skipping key backup check since user is guest"),e.checkedForBackup=!0,null;var t;try{var n;t=(n=yield e.baseApis.getKeyBackupVersion())!==null&&n!==void 0?n:void 0}catch(o){return b.log("Error checking for active key backup",o),o.httpStatus===404&&(e.checkedForBackup=!0),null}e.checkedForBackup=!0;var i=yield e.isKeyBackupTrusted(t);return i.usable&&!e.backupInfo?(b.log("Found usable key backup v".concat(t.version,": enabling key backups")),yield e.enableKeyBackup(t)):!i.usable&&e.backupInfo?(b.log("No usable key backup: disabling key backup"),e.disableKeyBackup()):!i.usable&&!e.backupInfo?b.log("No usable key backup: not enabling key backup"):i.usable&&e.backupInfo&&(t.version!==e.backupInfo.version?(b.log("On backup version ".concat(e.backupInfo.version," but ")+"found version ".concat(t.version,": switching.")),e.disableKeyBackup(),yield e.enableKeyBackup(t),yield e.scheduleAllGroupSessionsForBackup()):b.log("Backup version ".concat(t.version," still current"))),{backupInfo:t,trustInfo:i}})()}checkKeyBackup(){var e=this;return w(function*(){return e.checkedForBackup=!1,e.checkAndStart()})()}queryKeyBackupRateLimited(e,t){var n=this;return w(function*(){if(n.backupInfo){var i=new Date().getTime();(!n.sessionLastCheckAttemptedTime[t]||i-n.sessionLastCheckAttemptedTime[t]>G9)&&(n.sessionLastCheckAttemptedTime[t]=i,yield n.baseApis.restoreKeyBackupWithCache(e,t,n.backupInfo,{}))}})()}isKeyBackupTrusted(e){var t=this;return w(function*(){var n={usable:!1,trusted_locally:!1,sigs:[]};if(!e||!e.algorithm||!e.auth_data||!e.auth_data.signatures)return b.info("Key backup is absent or missing required data: ".concat(JSON.stringify(e))),n;var i=t.baseApis.getUserId(),o=yield t.baseApis.crypto.getSessionBackupPrivateKey();if(o){var s=null;try{s=yield xa.makeAlgorithm(e,w(function*(){return o})),(yield s.keyMatches(o))&&(b.info("Backup is trusted locally"),n.trusted_locally=!0)}catch{}finally{var a;(a=s)===null||a===void 0||a.free()}}var l=e.auth_data.signatures[i]||{};for(var c of Object.keys(l)){var u=c.split(":");if(u[0]!=="ed25519"){b.log("Ignoring unknown signature type: "+u[0]);continue}var d={deviceId:u[1]},f=t.baseApis.crypto.crossSigningInfo.getId();if(f===d.deviceId){d.crossSigningId=!0;try{yield Ec(t.baseApis.crypto.olmDevice,e.auth_data,i,d.deviceId,f),d.valid=!0}catch(h){b.warn("Bad signature from cross signing key "+f,h),d.valid=!1}n.sigs.push(d);continue}var p=t.baseApis.crypto.deviceList.getStoredDevice(i,d.deviceId);if(p){d.device=p,d.deviceTrust=t.baseApis.checkDeviceTrust(i,d.deviceId);try{yield Ec(t.baseApis.crypto.olmDevice,e.auth_data,i,p.deviceId,p.getFingerprint()),d.valid=!0}catch(h){b.info("Bad signature from key ID "+c+" userID "+t.baseApis.getUserId()+" device ID "+p.deviceId+" fingerprint: "+p.getFingerprint(),e.auth_data,h),d.valid=!1}}else d.valid=null,b.info("Ignoring signature from unknown key "+c);n.sigs.push(d)}return n.usable=n.sigs.some(h=>{var m;return h.valid&&(h.device&&((m=h.deviceTrust)===null||m===void 0?void 0:m.isVerified())||h.crossSigningId)}),n})()}scheduleKeyBackupSend(){var e=arguments,t=this;return w(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:1e4;if(b.debug("Key backup: scheduleKeyBackupSend currentSending:".concat(t.sendingBackups," delay:").concat(n)),!t.sendingBackups){t.sendingBackups=!0;try{var i=Math.random()*n;if(yield As(i),!t.clientRunning){t.sendingBackups=!1;return}for(var o=0;;){if(!t.algorithm)return;try{var s=yield t.backupPendingKeys(q9);if(s===0){t.sendingBackups=!1;return}o=0}catch(l){if(o++,b.log("Key backup request failed",l),l instanceof hr){var a=l.data.errcode;if(a=="M_NOT_FOUND"||a=="M_WRONG_ROOM_KEYS_VERSION"){t.sendingBackups=!1,t.baseApis.crypto.emit(et.KeyBackupFailed,a),yield t.checkKeyBackup();return}}}if(o&&(yield As(1e3*Math.pow(2,Math.min(o-1,4)))),!t.clientRunning){b.debug("Key backup send loop aborted, client stopped"),t.sendingBackups=!1;return}}}catch(l){b.log("Backup loop failed ".concat(l)),t.sendingBackups=!1}}})()}backupPendingKeys(e){var t=this;return w(function*(){var n=yield t.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(e);if(!n.length)return 0;var i=yield t.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();t.baseApis.crypto.emit(et.KeyBackupSessionsRemaining,i);var o={};for(var s of n){var a,l=s.sessionData.room_id;Qi(o,l,o[l]||{sessions:{}});var c=t.baseApis.crypto.olmDevice.exportInboundGroupSession(s.senderKey,s.sessionId,s.sessionData);c.algorithm=bn;var u=(c.forwarding_curve25519_key_chain||[]).length,d=t.baseApis.crypto.deviceList.getUserByIdentityKey(bn,s.senderKey),f=(a=t.baseApis.crypto.deviceList.getDeviceByIdentityKey(bn,s.senderKey))!==null&&a!==void 0?a:void 0,p=t.baseApis.crypto.checkDeviceInfoTrust(d,f).isVerified();Qi(o[l].sessions,s.sessionId,{first_message_index:c.first_known_index,forwarded_count:u,is_verified:p,session_data:yield t.algorithm.encryptSession(c)})}return yield t.baseApis.sendKeyBackup(void 0,void 0,t.backupInfo.version,{rooms:o}),yield t.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(n),i=yield t.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(),t.baseApis.crypto.emit(et.KeyBackupSessionsRemaining,i),n.length})()}backupGroupSession(e,t){var n=this;return w(function*(){yield n.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{senderKey:e,sessionId:t}]),n.backupInfo&&n.scheduleKeyBackupSend()})()}scheduleAllGroupSessionsForBackup(){var e=this;return w(function*(){yield e.flagAllGroupSessionsForBackup(),e.scheduleKeyBackupSend(0)})()}flagAllGroupSessionsForBackup(){var e=this;return w(function*(){yield e.baseApis.crypto.cryptoStore.doTxn("readwrite",[_e.STORE_INBOUND_GROUP_SESSIONS,_e.STORE_BACKUP],n=>{e.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(n,i=>{i!==null&&e.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([i],n)})});var t=yield e.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();return e.baseApis.emit(et.KeyBackupSessionsRemaining,t),t})()}countSessionsNeedingBackup(){return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup()}}class Tc{constructor(e,t,n){this.authData=e,this.publicKey=t,this.getKey=n}static init(e,t){return w(function*(){if(!e||!("public_key"in e))throw new Error("auth_data missing required information");var n=new globalThis.Olm.PkEncryption;return n.set_recipient_key(e.public_key),new Tc(e,n,t)})()}static prepare(e){return w(function*(){var t=new globalThis.Olm.PkDecryption;try{var n={};if(!e)n.public_key=t.generate_key();else if(e instanceof Uint8Array)n.public_key=t.init_with_private_key(e);else{var i=yield zw(e);n.private_key_salt=i.salt,n.private_key_iterations=i.iterations,n.public_key=t.init_with_private_key(i.key)}var o=new globalThis.Olm.PkEncryption;return o.set_recipient_key(n.public_key),[t.get_private_key(),n]}finally{t.free()}})()}static checkBackupVersion(e){if(!("public_key"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!0}encryptSession(e){var t=this;return w(function*(){var n=Object.assign({},e);return delete n.session_id,delete n.room_id,delete n.first_known_index,t.publicKey.encrypt(JSON.stringify(n))})()}decryptSessions(e){var t=this;return w(function*(){var n=yield t.getKey(),i=new globalThis.Olm.PkDecryption;try{var o=i.init_with_private_key(n);if(o!==t.authData.public_key)throw new hr({errcode:qc.RESTORE_BACKUP_ERROR_BAD_KEY});var s=[];for(var[a,l]of Object.entries(e))try{var c=JSON.parse(i.decrypt(l.session_data.ephemeral,l.session_data.mac,l.session_data.ciphertext));c.session_id=a,s.push(c)}catch(u){b.log("Failed to decrypt megolm session from backup",u,l)}return s}finally{i.free()}})()}keyMatches(e){var t=this;return w(function*(){var n=new globalThis.Olm.PkDecryption,i;try{i=n.init_with_private_key(e)}finally{n.free()}return i===t.authData.public_key})()}free(){this.publicKey.free()}}v(Tc,"algorithmName","m.megolm_backup.v1.curve25519-aes-sha2");function H9(r){var e=new Uint8Array(r);return globalThis.crypto.getRandomValues(e),e}var z9=new Bt("m.megolm_backup.v1.aes-hmac-sha2","org.matrix.msc3270.v1.aes-hmac-sha2");class Wd{constructor(e,t){this.authData=e,this.key=t}static init(e,t){return w(function*(){if(!e)throw new Error("auth_data missing");var n=yield t();if(e.mac){var{mac:i}=yield Ia(n,e.iv);if(e.mac.replace(/=+$/g,"")!==i.replace(/=+/g,""))throw new Error("Key does not match")}return new Wd(e,n)})()}static prepare(e){return w(function*(){var t,n={};if(!e)t=H9(32);else if(e instanceof Uint8Array)t=new Uint8Array(e);else{var i=yield zw(e);n.private_key_salt=i.salt,n.private_key_iterations=i.iterations,t=i.key}var{iv:o,mac:s}=yield Ia(t);return n.iv=o,n.mac=s,[t,n]})()}static checkBackupVersion(e){if(!("iv"in e.auth_data&&"mac"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!1}encryptSession(e){var t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,$c(JSON.stringify(t),this.key,e.session_id)}decryptSessions(e){var t=this;return w(function*(){var n=[];for(var[i,o]of Object.entries(e))try{var s=JSON.parse(yield Cf(o.session_data,t.key,i));s.session_id=i,n.push(s)}catch(a){b.log("Failed to decrypt megolm session from backup",a,o)}return n})()}keyMatches(e){var t=this;return w(function*(){if(t.authData.mac){var{mac:n}=yield Ia(e,t.authData.iv);return t.authData.mac.replace(/=+$/g,"")===n.replace(/=+/g,"")}else return!0})()}free(){this.key.fill(0)}}v(Wd,"algorithmName",z9.name);var uy={[Tc.algorithmName]:Tc,[Wd.algorithmName]:Wd},Y9=Tc;function Ok(r){var e;return{trusted:r.usable,matchesDecryptionKey:(e=r.trusted_locally)!==null&&e!==void 0?e:!1}}class J9{constructor(e){v(this,"algorithm",void 0),v(this,"sourceTrusted",void 0),this.algorithm=e,this.sourceTrusted=!e.untrusted}free(){this.algorithm.free()}decryptSessions(e){var t=this;return w(function*(){return yield t.algorithm.decryptSessions(e)})()}}class X9{constructor(e){this.cryptoStore=e,v(this,"roomEncryption",{})}init(){var e=this;return w(function*(){yield e.cryptoStore.doTxn("readwrite",[_e.STORE_ROOMS],t=>{e.cryptoStore.getEndToEndRooms(t,n=>{e.roomEncryption=n})})})()}getRoomEncryption(e){return this.roomEncryption[e]||null}isRoomEncrypted(e){return!!this.getRoomEncryption(e)}setRoomEncryption(e,t){var n=this;return w(function*(){n.roomEncryption[e]=t,yield n.cryptoStore.doTxn("readwrite",[_e.STORE_ROOMS],i=>{n.cryptoStore.storeEndToEndRoom(e,t,i)})})()}}function Pk(r,e){var t=new Map(Object.entries(r.keys)),n=r.getDisplayName()||void 0,i=new Map;if(r.signatures)for(var o in r.signatures)i.set(o,new Map(Object.entries(r.signatures[o])));return new _N({deviceId:r.deviceId,userId:e,keys:t,algorithms:r.algorithms,verified:r.verified,signatures:i,displayName:n})}function Mk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Q9(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Mk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Mk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var fo=rn.DeviceVerification,dy={[$d.NAME]:$d,[wc.NAME]:wc,[_9]:vv,[KN]:vv};$d.NAME,wc.NAME;function $N(){return!!globalThis.Olm}var Z9=60*60*1e3,e7=5*60*1e3,et=function(r){return r.DeviceVerificationChanged="deviceVerificationChanged",r[r.UserTrustStatusChanged=Yt.UserTrustStatusChanged]="UserTrustStatusChanged",r.UserCrossSigningUpdated="userCrossSigningUpdated",r.RoomKeyRequest="crypto.roomKeyRequest",r.RoomKeyRequestCancellation="crypto.roomKeyRequestCancellation",r[r.KeyBackupStatus=Yt.KeyBackupStatus]="KeyBackupStatus",r[r.KeyBackupFailed=Yt.KeyBackupFailed]="KeyBackupFailed",r[r.KeyBackupSessionsRemaining=Yt.KeyBackupSessionsRemaining]="KeyBackupSessionsRemaining",r[r.KeyBackupDecryptionKeyCached=Yt.KeyBackupDecryptionKeyCached]="KeyBackupDecryptionKeyCached",r.KeySignatureUploadFailure="crypto.keySignatureUploadFailure",r.VerificationRequest="crypto.verification.request",r[r.VerificationRequestReceived=Yt.VerificationRequestReceived]="VerificationRequestReceived",r.Warning="crypto.warning",r[r.WillUpdateDevices=Yt.WillUpdateDevices]="WillUpdateDevices",r[r.DevicesUpdated=Yt.DevicesUpdated]="DevicesUpdated",r[r.KeysChanged=Yt.KeysChanged]="KeysChanged",r[r.LegacyCryptoStoreMigrationProgress=Yt.LegacyCryptoStoreMigrationProgress]="LegacyCryptoStoreMigrationProgress",r}({});class mv extends Tt{static getOlmVersion(){return hk.getOlmVersion()}constructor(e,t,n,i,o,s){var a;if(super(),a=this,this.baseApis=e,this.userId=t,this.deviceId=n,this.clientStore=i,this.cryptoStore=o,v(this,"backupManager",void 0),v(this,"crossSigningInfo",void 0),v(this,"olmDevice",void 0),v(this,"deviceList",void 0),v(this,"dehydrationManager",void 0),v(this,"secretStorage",void 0),v(this,"roomList",void 0),v(this,"reEmitter",void 0),v(this,"verificationMethods",void 0),v(this,"supportedAlgorithms",void 0),v(this,"outgoingRoomKeyRequestManager",void 0),v(this,"toDeviceVerificationRequests",void 0),v(this,"inRoomVerificationRequests",void 0),v(this,"trustCrossSignedDevices",!0),v(this,"lastOneTimeKeyCheck",null),v(this,"oneTimeKeyCheckInProgress",!1),v(this,"roomEncryptors",new Map),v(this,"roomDecryptors",new Map),v(this,"deviceKeys",{}),v(this,"globalBlacklistUnverifiedDevices",!1),v(this,"globalErrorOnUnknownDevices",!0),v(this,"receivedRoomKeyRequests",[]),v(this,"receivedRoomKeyRequestCancellations",[]),v(this,"processingRoomKeyRequests",!1),v(this,"lazyLoadMembers",!1),v(this,"roomDeviceTrackingState",{}),v(this,"forceNewSessionRetryTime",new Gt(()=>new Gt(()=>0))),v(this,"sendKeyRequestsImmediately",!1),v(this,"oneTimeKeyCount",void 0),v(this,"needsNewFallback",void 0),v(this,"fallbackCleanup",void 0),v(this,"onDeviceListUserCrossSigningUpdated",function(){var d=w(function*(f){if(f===a.userId){var p=a.deviceList.getStoredCrossSigningForUser(f),h=p?p.getId():null,m=a.crossSigningInfo.getId(),E=m!==h;m&&h&&!E?yield a.checkOwnCrossSigningTrust():(a.storeTrustedSelfKeys(null),a.emit(et.KeysChanged,{}),a.emit(et.UserTrustStatusChanged,a.userId,a.checkUserTrust(f)))}else{yield a.checkDeviceVerifications(f);var y=a.deviceList.getStoredCrossSigningForUser(f);y&&(y.updateCrossSigningVerifiedBefore(a.checkUserTrust(f).isCrossSigningVerified()),a.deviceList.setRawStoredCrossSigningForUser(f,y.toStorage())),a.emit(et.UserTrustStatusChanged,f,a.checkUserTrust(f))}});return function(f){return d.apply(this,arguments)}}()),v(this,"onMembership",(d,f,p)=>{try{this.onRoomMembership(d,f,p)}catch(h){b.error("Error handling membership change:",h)}}),v(this,"onToDeviceEvent",d=>{try{b.log("received to-device ".concat(d.getType()," from: ")+"".concat(d.getSender()," id: ").concat(d.getContent()[tn])),d.getType()=="m.room_key"||d.getType()=="m.forwarded_room_key"?this.onRoomKeyEvent(d):d.getType()=="m.room_key_request"?this.onRoomKeyRequestEvent(d):d.getType()==="m.secret.request"?this.secretStorage.onRequestReceived(d):d.getType()==="m.secret.send"?this.secretStorage.onSecretReceived(d):d.getType()==="m.room_key.withheld"?this.onRoomKeyWithheldEvent(d):d.getContent().transaction_id?this.onKeyVerificationMessage(d):d.getContent().msgtype==="m.bad.encrypted"?this.onToDeviceBadEncrypted(d):(d.isBeingDecrypted()||d.shouldAttemptDecryption())&&(d.isBeingDecrypted()||d.attemptDecryption(this),d.once(ot.Decrypted,f=>{this.onToDeviceEvent(f)}))}catch(f){b.error("Error handling toDeviceEvent:",f)}}),v(this,"onTimelineEvent",function(d,f,p,h){var{liveEvent:m=!0}=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};if(Kr.validateEvent(d,a.baseApis)){var E=y=>{var S=new Kr(a.baseApis,y.getRoomId());return new Sa(S,a.verificationMethods,a.baseApis)};a.handleVerificationEvent(d,a.inRoomVerificationRequests,E,m)}}),b.debug("Crypto: initialising roomlist..."),this.roomList=new X9(o),this.reEmitter=new Vc(this),s){this.verificationMethods=new Map;for(var l of s)typeof l=="string"?dy[l]&&this.verificationMethods.set(l,dy[l]):l.NAME?this.verificationMethods.set(l.NAME,l):b.warn("Excluding unknown verification method ".concat(l))}else this.verificationMethods=new Map(Object.entries(dy));this.backupManager=new xa(e,w(function*(){var d=yield a.getSessionBackupPrivateKey();if(d)return d;var f=yield a.secretStorage.get("m.megolm_backup.v1");if(f){var p=op(f);if(p){var h=yield a.secretStorage.getKey();yield a.secretStorage.store("m.megolm_backup.v1",p,[h[0]])}return Dr(p||f)}if(a.baseApis.cryptoCallbacks&&a.baseApis.cryptoCallbacks.getBackupKey)return a.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")})),this.olmDevice=new hk(o),this.deviceList=new z8(e,o,this.olmDevice),this.deviceList.on(et.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[et.DevicesUpdated,et.WillUpdateDevices]),this.supportedAlgorithms=Array.from(o_.keys()),this.outgoingRoomKeyRequestManager=new n9(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new $9,this.inRoomVerificationRequests=new V9;var c=this.baseApis.cryptoCallbacks||{},u=DN(o,this.olmDevice);this.crossSigningInfo=new gi(t,c,u),this.secretStorage=new m9(e,c,e),this.dehydrationManager=new W9(this),!c.getCrossSigningKey&&c.getSecretStorageKey&&(c.getCrossSigningKey=function(){var d=w(function*(f){return gi.getFromSecretStorage(f,a.secretStorage)});return function(f){return d.apply(this,arguments)}}())}init(){var e=arguments,t=this;return w(function*(){var{exportedOlmDevice:n,pickleKey:i}=e.length>0&&e[0]!==void 0?e[0]:{};b.log("Crypto: initialising Olm..."),yield globalThis.Olm.init(),b.log(n?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),yield t.olmDevice.init({fromExportedDevice:n,pickleKey:i}),b.log("Crypto: loading device list..."),yield t.deviceList.load(),t.deviceKeys["ed25519:"+t.deviceId]=t.olmDevice.deviceEd25519Key,t.deviceKeys["curve25519:"+t.deviceId]=t.olmDevice.deviceCurve25519Key,b.log("Crypto: fetching own devices...");var o=t.deviceList.getRawStoredDevicesForUser(t.userId);if(o||(o={}),!o[t.deviceId]){b.log("Crypto: adding this device to the store...");var s={keys:t.deviceKeys,algorithms:t.supportedAlgorithms,verified:fo.VERIFIED,known:!0};o[t.deviceId]=s,t.deviceList.storeDevicesForUser(t.userId,o),t.deviceList.saveIfDirty()}yield t.cryptoStore.doTxn("readonly",[_e.STORE_ACCOUNT],a=>{t.cryptoStore.getCrossSigningKeys(a,l=>{l&&Object.keys(l).length!==0&&(b.log("Loaded cross-signing public keys from crypto store"),t.crossSigningInfo.setKeys(l))})}),t.deviceList.startTrackingDeviceList(t.userId),b.debug("Crypto: initialising roomlist..."),yield t.roomList.init(),b.log("Crypto: checking for key backup..."),t.backupManager.checkAndStart()})()}setDeviceIsolationMode(e){throw new Error("Not supported")}getVersion(){var e=mv.getOlmVersion();return"Olm ".concat(e[0],".").concat(e[1],".").concat(e[2])}getTrustCrossSignedDevices(){return this.trustCrossSignedDevices}getCryptoTrustCrossSignedDevices(){return this.trustCrossSignedDevices}setTrustCrossSignedDevices(e){this.trustCrossSignedDevices=e;for(var t of this.deviceList.getKnownUserIds()){var n=this.deviceList.getRawStoredDevicesForUser(t);for(var i of Object.keys(n)){var o=this.checkDeviceTrust(t,i);if(!o.isLocallyVerified()&&o.isCrossSigningVerified()){var s=this.deviceList.getStoredDevice(t,i);this.emit(et.DeviceVerificationChanged,t,i,s)}}}}setCryptoTrustCrossSignedDevices(e){this.setTrustCrossSignedDevices(e)}createRecoveryKeyFromPassphrase(e){return w(function*(){var t=new globalThis.Olm.PkDecryption;try{if(e){var n=yield zw(e);t.init_with_private_key(n.key);var i=t.get_private_key();return{keyInfo:{passphrase:{algorithm:"m.pbkdf2",iterations:n.iterations,salt:n.salt}},privateKey:i,encodedPrivateKey:hv(i)}}else{t.generate_key();var o=t.get_private_key();return{privateKey:o,encodedPrivateKey:hv(o)}}}finally{t==null||t.free()}})()}userHasCrossSigningKeys(){var e=arguments,t=this;return w(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:t.userId;return yield t.downloadKeys([n]),t.deviceList.getStoredCrossSigningForUser(n)!==null})()}isCrossSigningReady(){var e=this;return w(function*(){var t=e.crossSigningInfo.getId(),n=(yield e.crossSigningInfo.isStoredInKeyCache())||(yield e.crossSigningInfo.isStoredInSecretStorage(e.secretStorage));return!!(t&&n)})()}isSecretStorageReady(){var e=this;return w(function*(){var t=yield e.secretStorage.hasKey(),n=yield e.crossSigningInfo.isStoredInSecretStorage(e.secretStorage),i=!e.backupManager.getKeyBackupEnabled()||(yield e.baseApis.isKeyBackupKeyStored());return!!(t&&n&&i)})()}getCrossSigningStatus(){var e=this;return w(function*(){var t,n,i,o=!!e.crossSigningInfo.getId(),s=!!(yield e.crossSigningInfo.isStoredInSecretStorage(e.secretStorage)),a=e.crossSigningInfo.getCacheCallbacks(),l=!!(yield(t=a.getCrossSigningKeyCache)===null||t===void 0?void 0:t.call(a,"master")),c=!!(yield(n=a.getCrossSigningKeyCache)===null||n===void 0?void 0:n.call(a,"self_signing")),u=!!(yield(i=a.getCrossSigningKeyCache)===null||i===void 0?void 0:i.call(a,"user_signing"));return{publicKeysOnDevice:o,privateKeysInSecretStorage:s,privateKeysCachedLocally:{masterKey:l,selfSigningKey:c,userSigningKey:u}}})()}bootstrapCrossSigning(){var e=arguments,t=this;return w(function*(){var{authUploadDeviceSigningKeys:n,setupNewCrossSigning:i}=e.length>0&&e[0]!==void 0?e[0]:{};b.log("Bootstrapping cross-signing");var o=t.baseApis.cryptoCallbacks,s=new _k(t.baseApis.store.accountData,o),a=new gi(t.userId,s.crossSigningCallbacks,s.crossSigningCallbacks),l=function(){var E=w(function*(){a.resetKeys(),yield t.signObject(a.keys.master),s.addCrossSigningKeys(n,a.keys);var y=t.deviceList.getStoredDevice(t.userId,t.deviceId),S=yield a.signDevice(t.userId,y);s.addKeySignature(t.userId,t.deviceId,S),t.backupManager.backupInfo&&(yield a.signObject(t.backupManager.backupInfo.auth_data,"master"),s.addSessionBackup(t.backupManager.backupInfo))});return function(){return E.apply(this,arguments)}}(),c=t.crossSigningInfo.getId(),u=yield t.crossSigningInfo.isStoredInKeyCache(),d=yield t.crossSigningInfo.isStoredInSecretStorage(t.secretStorage),f=u||d;b.log({setupNewCrossSigning:i,publicKeysOnDevice:c,privateKeysInCache:u,privateKeysInStorage:d,privateKeysExistSomewhere:f}),!f||i?(b.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),yield l()):c&&u?b.log("Cross-signing public keys trusted and private keys found locally"):d&&(b.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),yield t.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));var p=s.crossSigningCallbacks.privateKeys;if(p.size&&!t.baseApis.cryptoCallbacks.saveCrossSigningKeys){var h=new Vd(s.accountDataClientAdapter,s.ssssCryptoCallbacks);(yield h.hasKey())&&(b.log("Storing new cross-signing private keys in secret storage"),yield gi.storeInSecretStorage(p,h))}var m=s.buildOperation();yield m.apply(t),yield s.persist(t),b.log("Cross-signing ready")})()}bootstrapSecretStorage(){var e=arguments,t=this;return w(function*(){var{createSecretStorageKey:n=w(function*(){return{}}),keyBackupInfo:i,setupNewKeyBackup:o,setupNewSecretStorage:s,getKeyBackupPassphrase:a}=e.length>0&&e[0]!==void 0?e[0]:{};b.log("Bootstrapping Secure Secret Storage");var l=t.baseApis.cryptoCallbacks,c=new _k(t.baseApis.store.accountData,l),u=new Vd(c.accountDataClientAdapter,c.ssssCryptoCallbacks),d=null,f=function(){var ae=w(function*(q){var{keyId:z,keyInfo:Q}=yield u.addKey($i,q);return c.ssssCryptoCallbacks.addPrivateKey(z,Q,q.key),yield u.setDefaultKeyId(z),z});return function(z){return ae.apply(this,arguments)}}(),p=function(){var ae=w(function*(q,z){if(!z.mac){var Q,Ie,Y=yield(Q=(Ie=t.baseApis.cryptoCallbacks).getSecretStorageKey)===null||Q===void 0?void 0:Q.call(Ie,{keys:{[q]:z}},"");if(Y){var le=Y[1];c.ssssCryptoCallbacks.addPrivateKey(q,z,le);var{iv:B,mac:W}=yield Ia(le);z.iv=B,z.mac=W,yield c.setAccountData("m.secret_storage.key.".concat(q),z)}}});return function(z,Q){return ae.apply(this,arguments)}}(),h=function(){var ae=w(function*(q){if(t.crossSigningInfo.getId()&&(yield t.crossSigningInfo.isStoredInKeyCache("master")))try{b.log("Adding cross-signing signature to key backup"),yield t.crossSigningInfo.signObject(q,"master")}catch(z){b.error("Signing key backup with cross-signing keys failed",z)}else b.warn("Cross-signing keys not available, skipping signature on key backup")});return function(z){return ae.apply(this,arguments)}}(),m=yield t.secretStorage.getKey(),[E,y]=m||[null,null],S=!s&&y&&y.algorithm===$i;if(b.log({keyBackupInfo:i,setupNewKeyBackup:o,setupNewSecretStorage:s,storageExists:S,oldKeyInfo:y}),!S&&!i){b.log("Secret storage does not exist, creating new storage key");var{keyInfo:R,privateKey:k}=yield n();d=yield f({passphrase:R==null?void 0:R.passphrase,key:k,name:R==null?void 0:R.name})}else if(!S&&i){b.log("Secret storage does not exist, using key backup key");var x=(yield t.getSessionBackupPrivateKey())||(yield a==null?void 0:a()),T={key:x};i.auth_data.private_key_salt&&i.auth_data.private_key_iterations&&(T.passphrase={algorithm:"m.pbkdf2",iterations:i.auth_data.private_key_iterations,salt:i.auth_data.private_key_salt,bits:256}),d=yield f(T),yield u.store("m.megolm_backup.v1",Zr(x),[d]),yield h(i.auth_data),c.addSessionBackup(i)}else b.log("Secret storage exists"),y&&y.algorithm===$i&&(yield p(E,y));if(!t.baseApis.cryptoCallbacks.saveCrossSigningKeys&&(yield t.isCrossSigningReady())&&(d||!(yield t.crossSigningInfo.isStoredInSecretStorage(u)))){b.log("Copying cross-signing private keys from cache to secret storage");var O=yield t.crossSigningInfo.getCrossSigningKeysFromCache();yield gi.storeInSecretStorage(O,u)}if(o&&!i){b.log("Creating new message key backup version");var C=yield t.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),N=od(C.recovery_key);yield u.store("m.megolm_backup.v1",Zr(N));var F={algorithm:C.algorithm,auth_data:C.auth_data};yield h(F.auth_data),yield t.signObject(F.auth_data),c.addSessionBackup(F)}var H=yield u.get("m.megolm_backup.v1");if(H){b.info("Got session backup key from secret storage: caching");var ie=op(H);if(ie){var $=d||E;yield u.store("m.megolm_backup.v1",ie,$?[$]:null)}var X=new Uint8Array(Dr(ie||H));c.addSessionBackupPrivateKeyToCache(X)}else if(t.backupManager.getKeyBackupEnabled()){var oe=(yield t.getSessionBackupPrivateKey())||(yield a==null?void 0:a());if(!oe){b.error("Key backup is enabled but couldn't get key backup key!");return}b.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),yield u.store("m.megolm_backup.v1",Zr(oe))}var re=c.buildOperation();yield re.apply(t),yield c.persist(t),b.log("Secure Secret Storage ready")})()}resetKeyBackup(){var e=this;return w(function*(){yield e.backupManager.deleteAllKeyBackupVersions();var t=yield e.backupManager.prepareKeyBackupVersion();yield e.signObject(t.auth_data);var{version:n}=yield e.baseApis.http.authedRequest(Z.Post,"/room_keys/version",void 0,t,{prefix:Pt.V3});b.log("Created backup version ".concat(n));var i=t.privateKey;yield e.secretStorage.store("m.megolm_backup.v1",Zr(i)),yield e.storeSessionBackupPrivateKey(i),yield e.backupManager.checkAndStart(),yield e.backupManager.scheduleAllGroupSessionsForBackup()})()}deleteKeyBackupVersion(e){var t=this;return w(function*(){yield t.backupManager.deleteKeyBackupVersion(e)})()}addSecretStorageKey(e,t,n){return this.secretStorage.addKey(e,t,n)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}getSecretStorageKey(e){return this.secretStorage.getKey(e)}storeSecret(e,t,n){return this.secretStorage.store(e,t,n)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){return t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId))),this.secretStorage.request(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}checkSecretStoragePrivateKey(e,t){var n=null;try{n=new globalThis.Olm.PkDecryption;var i=n.init_with_private_key(e);return i===t}finally{var o;(o=n)===null||o===void 0||o.free()}}getSessionBackupPrivateKey(){var e=this;return w(function*(){var t=yield new Promise(s=>{e.cryptoStore.doTxn("readonly",[_e.STORE_ACCOUNT],a=>{e.cryptoStore.getSecretStorePrivateKey(a,s,"m.megolm_backup.v1")})}),n=null;if(typeof t=="string"&&(n=new Uint8Array(Dr(op(t)||t)),yield e.storeSessionBackupPrivateKey(n)),t&&typeof t=="object"&&"ciphertext"in t){var i=Buffer.from(e.olmDevice.pickleKey),o=yield Cf(t,i,"m.megolm_backup.v1");n=Dr(o)}return n})()}storeSessionBackupPrivateKey(e,t){var n=this;return w(function*(){if(!(e instanceof Uint8Array))throw new Error("storeSessionBackupPrivateKey expects Uint8Array, got ".concat(e));var i=Buffer.from(n.olmDevice.pickleKey),o=yield $c(Zr(e),i,"m.megolm_backup.v1");return n.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],s=>{n.cryptoStore.storeSecretStorePrivateKey(s,"m.megolm_backup.v1",o)})})()}loadSessionBackupPrivateKeyFromSecretStorage(){throw new Error("Not implmeented")}getActiveSessionBackupVersion(){var e=this;return w(function*(){if(e.backupManager.getKeyBackupEnabled()){var t;return(t=e.backupManager.version)!==null&&t!==void 0?t:null}return null})()}getKeyBackupInfo(){return w(function*(){throw new Error("Not implemented")})()}isKeyBackupTrusted(e){var t=this;return w(function*(){var n=yield t.backupManager.isKeyBackupTrusted(e);return Ok(n)})()}checkKeyBackupAndEnable(){var e=this;return w(function*(){var t=yield e.backupManager.checkKeyBackup();return!t||!t.backupInfo?null:{backupInfo:t.backupInfo,trustInfo:Ok(t.trustInfo)}})()}checkCrossSigningPrivateKey(e,t){var n=null;try{n=new globalThis.Olm.PkSigning;var i=n.init_with_seed(e);return i===t}finally{var o;(o=n)===null||o===void 0||o.free()}}afterCrossSigningLocalKeyChange(){var e=this;return w(function*(){b.info("Starting cross-signing key change post-processing");var t=e.deviceList.getStoredDevice(e.userId,e.deviceId),n=yield e.crossSigningInfo.signDevice(e.userId,t);b.info("Starting background key sig upload for ".concat(e.deviceId));var i=f=>{var{shouldEmit:p=!1}=f;return e.baseApis.uploadKeySignatures({[e.userId]:{[e.deviceId]:n}}).then(h=>{var{failures:m}=h||{};if(Object.keys(m||[]).length>0)throw p&&e.baseApis.emit(et.KeySignatureUploadFailure,m,"afterCrossSigningLocalKeyChange",i),new Nu("Key upload failed",{failures:m});b.info("Finished background key sig upload for ".concat(e.deviceId))}).catch(h=>{b.error("Error during background key sig upload for ".concat(e.deviceId),h)})};i({shouldEmit:!0});var o=e.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(o){b.info("Starting device verification upgrade");var s={};for(var[a,l]of Object.entries(e.deviceList.crossSigningInfo)){var c=yield e.checkForDeviceVerificationUpgrade(a,gi.fromStorage(l,a));c&&(s[a]=c)}if(Object.keys(s).length>0){b.info("Found ".concat(Object.keys(s).length," verif users to upgrade"));try{var u=yield o({users:s});if(u)for(var d of u)d in s&&(yield e.baseApis.setDeviceVerified(d,s[d].crossSigningInfo.getId()))}catch(f){b.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",f)}}b.info("Finished device verification upgrade")}b.info("Finished cross-signing key change post-processing")})()}checkForDeviceVerificationUpgrade(e,t){var n=this;return w(function*(){var i=n.crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!i.isVerified()){var o=n.deviceList.getRawStoredDevicesForUser(e),s=yield n.checkForValidDeviceSignature(e,t.keys.master,o);if(s.length)return{devices:s.map(a=>rn.fromStorage(o[a],a)),crossSigningInfo:t}}})()}checkForValidDeviceSignature(e,t,n){var i=this;return w(function*(){var o=[];if(n&&t.signatures&&t.signatures[e])for(var s of Object.keys(t.signatures[e])){var[,a]=s.split(":",2);if(a in n&&n[a].verified===fo.VERIFIED)try{yield Ec(i.olmDevice,t,e,a,n[a].keys[s]),o.push(a)}catch{}}return o})()}getCrossSigningKeyId(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:qw.Master;return Promise.resolve(this.getCrossSigningId(e))}getCrossSigningId(e){return this.crossSigningInfo.getId(e)}getStoredCrossSigningForUser(e){return this.deviceList.getStoredCrossSigningForUser(e)}checkUserTrust(e){var t=this.deviceList.getStoredCrossSigningForUser(e);return t?this.crossSigningInfo.checkUserTrust(t):new sd(!1,!1,!1)}getUserVerificationStatus(e){var t=this;return w(function*(){return t.checkUserTrust(e)})()}pinCurrentUserIdentity(e){return w(function*(){throw new Error("not implemented")})()}getDeviceVerificationStatus(e,t){var n=this;return w(function*(){var i=n.deviceList.getStoredDevice(e,t);return i?n.checkDeviceInfoTrust(e,i):null})()}checkDeviceTrust(e,t){var n=this.deviceList.getStoredDevice(e,t);return this.checkDeviceInfoTrust(e,n)}checkDeviceInfoTrust(e,t){var n=!!(t!=null&&t.isVerified()),i=this.deviceList.getStoredCrossSigningForUser(e);if(t&&i){var o=this.trustCrossSignedDevices||e===this.userId;return this.crossSigningInfo.checkDeviceTrust(i,t,n,o)}else return new ec(!1,!1,n,!1)}checkIfOwnDeviceCrossSigned(e){var t,n=this.deviceList.getStoredDevice(this.userId,e);if(!n)return!1;var i=this.deviceList.getStoredCrossSigningForUser(this.userId);return(t=i==null?void 0:i.checkDeviceTrust(i,n,!1,!0).isCrossSigningVerified())!==null&&t!==void 0?t:!1}checkOwnCrossSigningTrust(){var e=arguments,t=this;return w(function*(){var{allowPrivateKeyRequests:n=!1}=e.length>0&&e[0]!==void 0?e[0]:{},i=t.userId;yield t.downloadKeys([t.userId]);var o=yield t.crossSigningInfo.getCrossSigningKeysFromCache(),s=t.deviceList.getStoredCrossSigningForUser(i);if(!s){b.error("Got cross-signing update event for user "+i+" but no new cross-signing information found!");return}var a=s.getId(),l=t.crossSigningInfo.getId()!==a,c=s.getId()&&!o.has("master");if(l&&b.info("Got new master public key",a),n&&(l||c)){b.info("Attempting to retrieve cross-signing master private key");var u=null;try{var d=yield t.crossSigningInfo.getCrossSigningKey("master",a);u=d[1],b.info("Got cross-signing master private key")}finally{var f;(f=u)===null||f===void 0||f.free()}}var p=t.crossSigningInfo.getId("self_signing"),h=t.crossSigningInfo.getId("user_signing");t.storeTrustedSelfKeys(s.keys);var m=p!==s.getId("self_signing"),E=h!==s.getId("user_signing"),y=s.getId("self_signing")&&!o.has("self_signing"),S=s.getId("user_signing")&&!o.has("user_signing"),R={};if(m&&b.info("Got new self-signing key",s.getId("self_signing")),n&&(m||y)){b.info("Attempting to retrieve cross-signing self-signing private key");var k=null;try{var x=yield t.crossSigningInfo.getCrossSigningKey("self_signing",s.getId("self_signing"));k=x[1],b.info("Got cross-signing self-signing private key")}finally{var T;(T=k)===null||T===void 0||T.free()}var O=t.deviceList.getStoredDevice(t.userId,t.deviceId),C=yield t.crossSigningInfo.signDevice(t.userId,O);R[t.deviceId]=C}if(E&&b.info("Got new user-signing key",s.getId("user_signing")),n&&(E||S)){b.info("Attempting to retrieve cross-signing user-signing private key");var N=null;try{var F=yield t.crossSigningInfo.getCrossSigningKey("user_signing",s.getId("user_signing"));N=F[1],b.info("Got cross-signing user-signing private key")}finally{var H;(H=N)===null||H===void 0||H.free()}}if(l){var ie=t.crossSigningInfo.keys.master;yield t.signObject(ie);var $=ie.signatures[t.userId]["ed25519:"+t.deviceId];R[t.crossSigningInfo.getId()]=Object.assign({},ie,{signatures:{[t.userId]:{["ed25519:"+t.deviceId]:$}}})}var X=Object.keys(R);if(X.length){var oe=re=>{var{shouldEmit:ae=!1}=re;return b.info("Starting background key sig upload for ".concat(X)),t.baseApis.uploadKeySignatures({[t.userId]:R}).then(q=>{var{failures:z}=q||{};if(b.info("Finished background key sig upload for ".concat(X)),Object.keys(z||[]).length>0)throw ae&&t.baseApis.emit(et.KeySignatureUploadFailure,z,"checkOwnCrossSigningTrust",oe),new Nu("Key upload failed",{failures:z})}).catch(q=>{b.error("Error during background key sig upload for ".concat(X),q)})};oe({shouldEmit:!0})}t.emit(et.UserTrustStatusChanged,i,t.checkUserTrust(i)),l&&(t.emit(et.KeysChanged,{}),yield t.afterCrossSigningLocalKeyChange()),yield t.backupManager.checkKeyBackup()})()}getBackupDecryptor(e,t){return w(function*(){if(!(t instanceof Uint8Array))throw new Error("getBackupDecryptor expects Uint8Array");var n=yield xa.makeAlgorithm(e,w(function*(){return t}));return(yield n.keyMatches(t))?new J9(n):Promise.reject(new hr({errcode:qc.RESTORE_BACKUP_ERROR_BAD_KEY}))})()}importBackedUpRoomKeys(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return n.source="backup",this.importRoomKeys(e,n)}storeTrustedSelfKeys(e){var t=this;return w(function*(){e?t.crossSigningInfo.setKeys(e):t.crossSigningInfo.clearKeys(),yield t.cryptoStore.doTxn("readwrite",[_e.STORE_ACCOUNT],n=>{t.cryptoStore.storeCrossSigningKeys(n,t.crossSigningInfo.keys)})})()}checkDeviceVerifications(e){var t=this;return w(function*(){var n=t.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(n){if(b.info("Starting device verification upgrade for ".concat(e)),t.crossSigningInfo.keys.user_signing){var i=t.deviceList.getStoredCrossSigningForUser(e);if(i){var o=yield t.checkForDeviceVerificationUpgrade(e,i);if(o){var s=yield n({users:{[e]:o}});s.includes(e)&&(yield t.baseApis.setDeviceVerified(e,i.getId()))}}}b.info("Finished device verification upgrade for ".concat(e))}})()}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(e){e.on(Ar.Membership,this.onMembership),e.on(be.ToDeviceEvent,this.onToDeviceEvent),e.on(pe.Timeline,this.onTimelineEvent),e.on(ot.Decrypted,this.onTimelineEvent)}start(){b.warn("MatrixClient.crypto.start() is deprecated")}stop(){this.outgoingRoomKeyRequestManager.stop(),this.deviceList.stop(),this.dehydrationManager.stop(),this.backupManager.stop()}getDeviceEd25519Key(){return this.olmDevice.deviceEd25519Key}getDeviceCurve25519Key(){return this.olmDevice.deviceCurve25519Key}getOwnDeviceKeys(){var e=this;return w(function*(){if(!e.olmDevice.deviceCurve25519Key)throw new Error("Curve25519 key not yet created");if(!e.olmDevice.deviceEd25519Key)throw new Error("Ed25519 key not yet created");return{ed25519:e.olmDevice.deviceEd25519Key,curve25519:e.olmDevice.deviceCurve25519Key}})()}setGlobalBlacklistUnverifiedDevices(e){this.globalBlacklistUnverifiedDevices=e}getGlobalBlacklistUnverifiedDevices(){return this.globalBlacklistUnverifiedDevices}uploadDeviceKeys(){var e={algorithms:this.supportedAlgorithms,device_id:this.deviceId,keys:this.deviceKeys,user_id:this.userId};return this.signObject(e).then(()=>this.baseApis.uploadKeysRequest({device_keys:e}))}getNeedsNewFallback(){return!!this.needsNewFallback}maybeUploadOneTimeKeys(){var e=this,t=1e3*60,n=5;if(!this.oneTimeKeyCheckInProgress){var i=Date.now();if(!(this.lastOneTimeKeyCheck!==null&&i-this.lastOneTimeKeyCheck<t)){this.lastOneTimeKeyCheck=i;var o=this.olmDevice.maxNumberOfOneTimeKeys(),s=Math.floor(o/2),a=function(){var l=w(function*(c){for(;s>c||e.getNeedsNewFallback();){if(s>c){b.info("generating oneTimeKeys");var u=Math.min(s-c,n);yield e.olmDevice.generateOneTimeKeys(u)}if(e.getNeedsNewFallback()){var d=yield e.olmDevice.getFallbackKey();(!d.curve25519||Object.keys(d.curve25519).length==0)&&(b.info("generating fallback key"),e.fallbackCleanup&&(clearTimeout(e.fallbackCleanup),delete e.fallbackCleanup),yield e.olmDevice.generateFallbackKey())}b.info("calling uploadOneTimeKeys");var f=yield e.uploadOneTimeKeys();if(f.one_time_key_counts&&f.one_time_key_counts.signed_curve25519)c=f.one_time_key_counts.signed_curve25519;else throw new Error("response for uploading keys does not contain one_time_key_counts.signed_curve25519")}});return function(u){return l.apply(this,arguments)}}();this.oneTimeKeyCheckInProgress=!0,Promise.resolve().then(()=>this.oneTimeKeyCount!==void 0?Promise.resolve(this.oneTimeKeyCount):this.baseApis.uploadKeysRequest({}).then(l=>l.one_time_key_counts.signed_curve25519||0)).then(l=>a(l)).catch(l=>{b.error("Error uploading one-time keys",l.stack||l)}).finally(()=>{this.oneTimeKeyCount=void 0,this.oneTimeKeyCheckInProgress=!1})}}}uploadOneTimeKeys(){var e=this;return w(function*(){var t=[],n;if(e.getNeedsNewFallback()){n={};var i=yield e.olmDevice.getFallbackKey();for(var[o,s]of Object.entries(i.curve25519)){var a={key:s,fallback:!0};n["signed_curve25519:"+o]=a,t.push(e.signObject(a))}e.needsNewFallback=!1}var l=yield e.olmDevice.getOneTimeKeys(),c={};for(var u in l.curve25519)if(l.curve25519.hasOwnProperty(u)){var d={key:l.curve25519[u]};c["signed_curve25519:"+u]=d,t.push(e.signObject(d))}yield Promise.all(t);var f={one_time_keys:c};n&&(f["org.matrix.msc2732.fallback_keys"]=n,f.fallback_keys=n);var p=yield e.baseApis.uploadKeysRequest(f);return n&&(e.fallbackCleanup=setTimeout(()=>{delete e.fallbackCleanup,e.olmDevice.forgetOldFallbackKey()},60*60*1e3)),yield e.olmDevice.markKeysAsPublished(),p})()}downloadKeys(e,t){return this.deviceList.downloadKeys(e,!!t)}getStoredDevicesForUser(e){return this.deviceList.getStoredDevicesForUser(e)}getUserDeviceInfo(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1,o=new Map,s=[],a=function*(d){var f=yield n.getStoredDevicesForUser(d);if(f){var p=new Map(f.map(h=>[h.deviceId,Pk(h,d)]));o.set(d,p)}else s.push(d)};for(var l of e)yield*a(l);if(i&&s.length>0){var c=yield n.downloadKeys(s);c.forEach((u,d)=>{var f=new Map;u.forEach((p,h)=>f.set(h,Pk(p,d))),o.set(d,f)})}return o})()}getStoredDevice(e,t){return this.deviceList.getStoredDevice(e,t)}saveDeviceList(e){return this.deviceList.saveIfDirty(e)}setDeviceVerified(e,t){var n=arguments,i=this;return w(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!0;yield i.setDeviceVerification(e,t,o)})()}crossSignDevice(e){var t=this;return w(function*(){yield t.setDeviceVerified(t.userId,e,!0)})()}setDeviceVerification(e,t){var n=arguments,i=this;return w(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:null,s=n.length>3&&n[3]!==void 0?n[3]:null,a=n.length>4&&n[4]!==void 0?n[4]:null,l=n.length>5?n[5]:void 0,c=i.deviceList.getStoredCrossSigningForUser(e);if((c==null?void 0:c.getId())===t){if(s!==null||a!==null)throw new Error("Cannot set blocked or known for a cross-signing key");if(!o)throw new Error("Cannot set a cross-signing key as unverified");var u=l?Object.values(l)[0]:null;if(l&&(Object.values(l).length!==1||u!==c.getId()))throw new Error("Key did not match expected value: expected ".concat(c.getId(),", got ").concat(u));if(!i.crossSigningInfo.getId()&&e===i.crossSigningInfo.userId&&(i.storeTrustedSelfKeys(c.keys),i.emit(et.UserTrustStatusChanged,i.userId,i.checkUserTrust(e))),e!==i.userId){b.info("Master key "+c.getId()+" for "+e+" marked verified. Signing...");var d=yield i.crossSigningInfo.signUser(c);if(d){var f=function(){var O=w(function*(C){var{shouldEmit:N=!1}=C;b.info("Uploading signature for "+e+"...");var F=yield i.baseApis.uploadKeySignatures({[e]:{[t]:d}}),{failures:H}=F||{};if(Object.keys(H||[]).length>0)throw N&&i.baseApis.emit(et.KeySignatureUploadFailure,H,"setDeviceVerification",f),new Nu("Key upload failed",{failures:H})});return function(N){return O.apply(this,arguments)}}();yield f({shouldEmit:!0})}return d}else return c}var p=i.deviceList.getRawStoredDevicesForUser(e);if(!p||!p[t])throw new Error("Unknown device "+e+":"+t);var h=p[t],m=h.verified;if(o){if(l){for(var[E,y]of Object.entries(l))if(h.keys[E]!==y)throw new Error("Key did not match expected value: expected ".concat(y,", got ").concat(h.keys[E]))}m=fo.VERIFIED}else o!==null&&m==fo.VERIFIED&&(m=fo.UNVERIFIED);s?m=fo.BLOCKED:s!==null&&m==fo.BLOCKED&&(m=fo.UNVERIFIED);var S=h.known;if(a!==null&&(S=a),(h.verified!==m||h.known!==S)&&(h.verified=m,h.known=S,i.deviceList.storeDevicesForUser(e,p),i.deviceList.saveIfDirty()),o&&e===i.userId){b.info("Own device "+t+" marked verified: signing");var R,k=i.checkDeviceTrust(e,t);if(k.isCrossSigningVerified()?b.log("Own device ".concat(t," already cross-signing verified")):R=yield i.crossSigningInfo.signDevice(e,rn.fromStorage(h,t)),R){var x=function(){var O=w(function*(C){var{shouldEmit:N=!1}=C;b.info("Uploading signature for "+t);var F=yield i.baseApis.uploadKeySignatures({[e]:{[t]:R}}),{failures:H}=F||{};if(Object.keys(H||[]).length>0)throw N&&i.baseApis.emit(et.KeySignatureUploadFailure,H,"setDeviceVerification",x),new Nu("Key upload failed",{failures:H})});return function(N){return O.apply(this,arguments)}}();yield x({shouldEmit:!0})}}var T=rn.fromStorage(h,t);return i.emit(et.DeviceVerificationChanged,e,t,T),T})()}findVerificationRequestDMInProgress(e,t){return this.inRoomVerificationRequests.findRequestInProgress(e,t)}getVerificationRequestsToDeviceInProgress(e){return this.toDeviceVerificationRequests.getRequestsInProgress(e)}requestVerificationDM(e,t){var n=this.inRoomVerificationRequests.findRequestInProgress(t);if(n)return Promise.resolve(n);var i=new Kr(this.baseApis,t,e);return this.requestVerificationWithChannel(e,i,this.inRoomVerificationRequests)}requestVerification(e,t){t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(e)));var n=this.toDeviceVerificationRequests.findRequestInProgress(e,t);if(n)return Promise.resolve(n);var i=new Br(this.baseApis,e,t,Br.makeTransactionId());return this.requestVerificationWithChannel(e,i,this.toDeviceVerificationRequests)}requestOwnUserVerification(){return this.requestVerification(this.userId)}requestDeviceVerification(e,t){return this.requestVerification(e,[t])}requestVerificationWithChannel(e,t,n){var i=this;return w(function*(){var o=new Sa(t,i.verificationMethods,i.baseApis);t.transactionId&&n.setRequestByChannel(t,o),yield o.sendRequest();var s=n.getRequestByChannel(t);return s?o=s:(b.log("Crypto: adding new request to "+"requestsByTxnId with id ".concat(t.transactionId," ").concat(t.roomId)),n.setRequestByChannel(t,o)),o})()}beginKeyVerification(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null,o;if(i){if(o=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(t,i),!o)throw new Error("No request found for user ".concat(t," with ")+"transactionId ".concat(i))}else{i=Br.makeTransactionId();var s=new Br(this.baseApis,t,[n],i,n);o=new Sa(s,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(t,i,o)}return o.beginKeyVerification(e,{userId:t,deviceId:n})}legacyDeviceVerification(e,t,n){var i=this;return w(function*(){var o=Br.makeTransactionId(),s=new Br(i.baseApis,e,[t],o,t),a=new Sa(s,i.verificationMethods,i.baseApis);i.toDeviceVerificationRequests.setRequestBySenderAndTxnId(e,o,a);var l=a.beginKeyVerification(n,{userId:e,deviceId:t});return yield Promise.race([l.verify(),a.waitFor(c=>c.started)]),a})()}getOlmSessionsForUser(e){var t=this;return w(function*(){var n=t.getStoredDevicesForUser(e)||[],i={};for(var o of n){var s=o.getIdentityKey(),a=yield t.olmDevice.getSessionInfoForDevice(s);i[o.deviceId]={deviceIdKey:s,sessions:a}}return i})()}getEventSenderDeviceInfo(e){var t=e.getSenderKey(),n=e.getWireContent().algorithm;if(!t||!n||e.isKeySourceUntrusted())return null;var i=this.deviceList.getDeviceByIdentityKey(n,t);if(i===null)return null;var o=e.getClaimedEd25519Key();return o?o!==i.getFingerprint()?(b.warn("Event "+e.getId()+" claims ed25519 key "+o+" but sender device has key "+i.getFingerprint()),null):i:(b.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(e){var t,n,i={};if(i.senderKey=(t=e.getSenderKey())!==null&&t!==void 0?t:void 0,i.algorithm=e.getWireContent().algorithm,!i.senderKey||!i.algorithm)return i.encrypted=!1,i;i.encrypted=!0,e.isKeySourceUntrusted()?i.authenticated=!1:i.authenticated=!0,i.sender=(n=this.deviceList.getDeviceByIdentityKey(i.algorithm,i.senderKey))!==null&&n!==void 0?n:void 0;var o=e.getClaimedEd25519Key();return o||(b.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),i.mismatchedSender=!0),i.sender&&o!==i.sender.getFingerprint()&&(b.warn("Event "+e.getId()+" claims ed25519 key "+o+"but sender device has key "+i.sender.getFingerprint()),i.mismatchedSender=!0),i}getEncryptionInfoForEvent(e){var t=this;return w(function*(){var n=t.getEventEncryptionInfo(e);if(!n.encrypted)return null;var i=e.getSender();if(!i||n.mismatchedSender)return{shieldColour:ns.RED,shieldReason:wl.MISMATCHED_SENDER_KEY};var o=t.checkUserTrust(i);if(!o.isCrossSigningVerified())return n.authenticated?{shieldColour:ns.NONE,shieldReason:null}:{shieldColour:ns.GREY,shieldReason:wl.AUTHENTICITY_NOT_GUARANTEED};var s=i&&n.sender&&(yield t.getDeviceVerificationStatus(i,n.sender.deviceId));return s?s.isVerified()?n.authenticated?{shieldColour:ns.NONE,shieldReason:null}:{shieldColour:ns.GREY,shieldReason:wl.AUTHENTICITY_NOT_GUARANTEED}:{shieldColour:ns.RED,shieldReason:wl.UNSIGNED_DEVICE}:{shieldColour:ns.GREY,shieldReason:wl.UNKNOWN_DEVICE}})()}forceDiscardSession(e){var t=this.roomEncryptors.get(e);if(t===void 0)throw new Error("Room not encrypted");if(t.forceDiscardSession===void 0)throw new Error("Room encryption algorithm doesn't support session discarding");return t.forceDiscardSession(),Promise.resolve()}setRoomEncryption(e,t,n){var i=this;return w(function*(){var o=i.clientStore.getRoom(e);if(!o)throw new Error("Unable to enable encryption tracking devices in unknown room ".concat(e));yield i.setRoomEncryptionImpl(o,t),!i.lazyLoadMembers&&!n&&i.deviceList.refreshOutdatedDeviceLists()})()}setRoomEncryptionImpl(e,t){var n=this;return w(function*(){var i=e.roomId;if(!t.algorithm){b.log("Ignoring setRoomEncryption with no algorithm");return}var o=n.roomList.getRoomEncryption(i);if(o&&JSON.stringify(o)!=JSON.stringify(t)){b.error("Ignoring m.room.encryption event which requests a change of config in "+i);return}var s=n.roomEncryptors.get(i);if(!s){var a=null;o||(a=n.roomList.setRoomEncryption(i,t));var l=NN.get(t.algorithm);if(!l)throw new Error("Unable to encrypt with "+t.algorithm);var c=new l({userId:n.userId,deviceId:n.deviceId,crypto:n,olmDevice:n.olmDevice,baseApis:n.baseApis,roomId:i,config:t});if(n.roomEncryptors.set(i,c),a&&(yield a),b.log("Enabling encryption in ".concat(i)),e.membersLoaded())yield n.trackRoomDevicesImpl(e);else{var u=d=>{e.off(Me.Update,u),e.membersLoaded()&&n.trackRoomDevicesImpl(e).catch(f=>{b.error("Error enabling device tracking in ".concat(i),f)})};e.on(Me.Update,u)}}})()}trackRoomDevices(e){var t=this.clientStore.getRoom(e);if(!t)throw new Error("Unable to start tracking devices in unknown room ".concat(e));return this.trackRoomDevicesImpl(t)}trackRoomDevicesImpl(e){var t=this,n=e.roomId,i=function(){var s=w(function*(){if(t.roomEncryptors.has(n)){b.log("Starting to track devices for room ".concat(n," ..."));var a=yield e.getEncryptionTargetMembers();a.forEach(l=>{t.deviceList.startTrackingDeviceList(l.userId)})}});return function(){return s.apply(this,arguments)}}(),o=this.roomDeviceTrackingState[n];return o||(o=i(),this.roomDeviceTrackingState[n]=o.catch(s=>{throw delete this.roomDeviceTrackingState[n],s})),o}ensureOlmSessionsForUsers(e,t){var n=new Map;for(var i of e){var o=[];n.set(i,o);var s=this.getStoredDevicesForUser(i)||[];for(var a of s){var l=a.getIdentityKey();l!=this.olmDevice.deviceCurve25519Key&&a.verified!=fo.BLOCKED&&o.push(a)}}return xo(this.olmDevice,this.baseApis,n,t)}exportRoomKeys(){var e=this;return w(function*(){var t=[];return yield e.cryptoStore.doTxn("readonly",[_e.STORE_INBOUND_GROUP_SESSIONS],n=>{e.cryptoStore.getAllEndToEndInboundGroupSessions(n,i=>{if(i!==null){var o=e.olmDevice.exportInboundGroupSession(i.senderKey,i.sessionId,i.sessionData);delete o.first_known_index,o.algorithm=bn,t.push(o)}})}),t})()}exportRoomKeysAsJson(){var e=this;return w(function*(){return JSON.stringify(yield e.exportRoomKeys())})()}importRoomKeys(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=0,i=0,o=e.length;function s(){var a;(a=t.progressCallback)===null||a===void 0||a.call(t,{stage:"load_keys",successes:n,failures:i,total:o})}return Promise.all(e.map(a=>{if(!a.room_id||!a.algorithm)return b.warn("ignoring room key entry with missing fields",a),i++,t.progressCallback&&s(),null;var l=this.getRoomDecryptor(a.room_id,a.algorithm);return l.importRoomKey(a,t).finally(()=>{n++,t.progressCallback&&s()})})).then()}importRoomKeysAsJson(e,t){var n=this;return w(function*(){return yield n.importRoomKeys(JSON.parse(e))})()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(e){var t=this.roomEncryptors.get(e.roomId);t&&t.prepareToEncrypt(e)}encryptEvent(e,t){var n=this;return w(function*(){var i=e.getRoomId(),o=n.roomEncryptors.get(i);if(!o)throw new Error("Room "+i+" was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");yield n.trackRoomDevicesImpl(t);var s=e.getContent(),a=s["m.relates_to"];a&&(s=Object.assign({},s),delete s["m.relates_to"]);var l=s["io.element.performance_metrics"];l&&(s=Object.assign({},s),delete s["io.element.performance_metrics"]);var c=yield o.encryptMessage(t,e.getType(),s);a&&(c["m.relates_to"]=a),l&&(c["io.element.performance_metrics"]=l),e.makeEncrypted("m.room.encrypted",c,n.olmDevice.deviceCurve25519Key,n.olmDevice.deviceEd25519Key)})()}decryptEvent(e){var t=this;return w(function*(){if(e.isRedacted()){var n=new pr(Q9({room_id:e.getRoomId()},e.getUnsigned().redacted_because)),i=e.getUnsigned().redacted_because;if(n.isEncrypted())try{var o=yield t.decryptEvent(n);i=o.clearEvent}catch(l){b.warn("Decryption of redaction failed. Falling back to unencrypted event.",l)}return{clearEvent:{room_id:e.getRoomId(),type:"m.room.message",content:{},unsigned:{redacted_because:i}}}}else{var s=e.getWireContent(),a=t.getRoomDecryptor(e.getRoomId(),s.algorithm);return a.decryptEvent(e)}})()}processDeviceLists(e){var t=this;return w(function*(){yield t.evalDeviceListChanges(e)})()}requestRoomKey(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(e,t,n).then(()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()}).catch(i=>{b.error("Error requesting key for event",i)})}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch(t=>{b.warn("Error clearing pending room key requests",t)})}cancelAndResendAllOutgoingKeyRequests(){var e=this;return w(function*(){yield e.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()})()}onCryptoEvent(e,t){var n=this;return w(function*(){var i=t.getContent();yield n.setRoomEncryptionImpl(e,i)})()}onSyncWillProcess(e){var t=this;return w(function*(){e.oldSyncToken||(b.log("Initial sync performed - resetting device tracking state"),t.deviceList.stopTrackingAllDeviceLists(),t.deviceList.startTrackingDeviceList(t.userId),t.roomDeviceTrackingState={}),t.sendKeyRequestsImmediately=!1})()}onSyncCompleted(e){var t=this;return w(function*(){var n;t.deviceList.setSyncToken((n=e.nextSyncToken)!==null&&n!==void 0?n:null),t.deviceList.saveIfDirty(),t.deviceList.startTrackingDeviceList(t.userId),t.deviceList.refreshOutdatedDeviceLists(),e.catchingUp||(t.maybeUploadOneTimeKeys(),t.processReceivedRoomKeyRequests(),t.outgoingRoomKeyRequestManager.sendQueuedRequests(),t.sendKeyRequestsImmediately=!0)})()}evalDeviceListChanges(e){var t=this;return w(function*(){if(Array.isArray(e==null?void 0:e.changed)&&e.changed.forEach(i=>{t.deviceList.invalidateUserDeviceList(i)}),Array.isArray(e==null?void 0:e.left)&&e.left.length){var n=new Set(yield t.getTrackedE2eUsers());e.left.forEach(i=>{n.has(i)||t.deviceList.stopTrackingDeviceList(i)})}})()}getTrackedE2eUsers(){var e=this;return w(function*(){var t=[];for(var n of e.getTrackedE2eRooms()){var i=yield n.getEncryptionTargetMembers();for(var o of i)t.push(o.userId)}return t})()}getTrackedE2eRooms(){return this.clientStore.getRooms().filter(e=>{var t=this.roomEncryptors.get(e.roomId);if(!t||!this.roomDeviceTrackingState[e.roomId])return!1;var n=e.getMyMembership();return n===Be.Join||n===Be.Invite})}encryptAndSendToDevices(e,t){var n=this;return w(function*(){try{var i=yield n.prepareToDeviceBatch(e,t);try{yield n.baseApis.queueToDevice(i)}catch(o){throw b.error("sendToDevice failed",o),o}}catch(o){throw b.error("encryptAndSendToDevices promises failed",o),o}})()}prepareToDeviceBatch(e,t){var n=this;return w(function*(){var i={eventType:V.RoomMessageEncrypted,batch:[]};return yield Promise.all(e.map(function(){var o=w(function*(s){var{userId:a,deviceInfo:l}=s,c=l.deviceId,u={algorithm:wr,sender_key:n.olmDevice.deviceCurve25519Key,ciphertext:{},[tn]:_i()};i.batch.push({userId:a,deviceId:c,payload:u}),yield xo(n.olmDevice,n.baseApis,new Map([[a,[l]]])),yield Ns(u.ciphertext,n.userId,n.deviceId,n.olmDevice,a,l,t)});return function(s){return o.apply(this,arguments)}}())),i.batch=i.batch.filter(o=>Object.keys(o.payload.ciphertext).length>0?!0:(b.log("No ciphertext for device ".concat(o.userId,":").concat(o.deviceId,": pruning")),!1)),i})()}encryptToDeviceMessages(e,t,n){var i=this;return w(function*(){var o=new Set(t.map(l=>{var{userId:c}=l;return c})),s=yield i.downloadKeys(Array.from(o),!1),a=[];return t.forEach(l=>{var{userId:c,deviceId:u}=l,d=s.get(c);if(!d){b.warn("No devices found for user ".concat(c));return}d.has(u)?a.push({userId:c,deviceInfo:d.get(u)}):b.warn("No device found for user ".concat(c," with id ").concat(u))}),i.prepareToDeviceBatch(a,n)})()}preprocessToDeviceMessages(e){return w(function*(){return e.filter(t=>{var n;return t.type===V.RoomMessageEncrypted&&!["m.olm.v1.curve25519-aes-sha2"].includes((n=t.content)===null||n===void 0?void 0:n.algorithm)?(b.log("Ignoring invalid encrypted to-device event from "+t.sender),!1):!0})})()}updateOneTimeKeyCount(e){if(isFinite(e))this.oneTimeKeyCount=e;else throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number")}processKeyCounts(e,t){return e!==void 0&&this.updateOneTimeKeyCount(e.signed_curve25519||0),t!==void 0&&(this.needsNewFallback=!t.includes("signed_curve25519")),Promise.resolve()}onRoomKeyEvent(e){var t=e.getContent();if(!t.room_id||!t.algorithm){b.error("key event is missing fields");return}this.backupManager.checkedForBackup||this.backupManager.checkAndStart();var n=this.getRoomDecryptor(t.room_id,t.algorithm);n.onRoomKeyEvent(e)}onRoomKeyWithheldEvent(e){var t=e.getContent();if(t.code!=="m.no_olm"&&(!t.room_id||!t.session_id)||!t.algorithm||!t.sender_key){b.error("key withheld event is missing fields");return}b.info("Got room key withheld event from ".concat(e.getSender()," ")+"for ".concat(t.algorithm," session ").concat(t.sender_key,"|").concat(t.session_id," ")+"in room ".concat(t.room_id," with code ").concat(t.code," (").concat(t.reason,")"));var n=this.getRoomDecryptor(t.room_id,t.algorithm);if(n.onRoomKeyWithheldEvent&&n.onRoomKeyWithheldEvent(e),!t.room_id){var i=this.getRoomDecryptors(t.algorithm);for(var o of i)o.retryDecryptionFromSender(t.sender_key)}}onKeyVerificationMessage(e){if(Br.validateEvent(e,this.baseApis)){var t=n=>{if(Br.canCreateRequest(Br.getEventType(n))){var i=n.getContent(),o=i&&i.from_device;if(o){var s=n.getSender(),a=new Br(this.baseApis,s,[o]);return new Sa(a,this.verificationMethods,this.baseApis)}}};this.handleVerificationEvent(e,this.toDeviceVerificationRequests,t)}}handleVerificationEvent(e,t,n){var i=arguments,o=this;return w(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!0;if(e.isSending()&&e.status!=je.SENT){var a,l;try{yield new Promise((f,p)=>{a=f,l=()=>{e.status==je.CANCELLED&&p(new Error("Event status set to CANCELLED."))},e.once(ot.LocalEventIdReplaced,a),e.on(ot.Status,l)})}catch(f){b.error("error while waiting for the verification event to be sent: ",f);return}finally{e.removeListener(ot.LocalEventIdReplaced,a),e.removeListener(ot.Status,l)}}var c=t.getRequest(e),u=!1;if(!c){if(c=n(e),!c){b.log("Crypto: could not find VerificationRequest for "+"".concat(e.getType(),", and could not create one, so ignoring."));return}u=!0,t.setRequest(e,c)}e.setVerificationRequest(c);try{yield c.channel.handleEvent(e,c,s)}catch(f){b.error("error while handling verification event",f)}var d=u&&!c.initiatedByMe&&!c.invalid&&!c.observeOnly;d&&(o.baseApis.emit(et.VerificationRequest,c),o.baseApis.emit(et.VerificationRequestReceived,c))})()}onToDeviceBadEncrypted(e){var t=this;return w(function*(){var n=e.getWireContent(),i=e.getSender(),o=n.algorithm,s=n.sender_key;t.baseApis.emit(be.UndecryptableToDeviceEvent,e);var a=()=>{var m=t.getRoomDecryptors(bn);for(var E of m)E.retryDecryptionFromSender(s)};if(!(i===void 0||s===void 0||s===void 0)){var l=t.forceNewSessionRetryTime.getOrCreate(i),c=l.getOrCreate(s);if(c>Date.now()){b.debug("New session already forced with device ".concat(i,":").concat(s,": ")+"not forcing another until at least ".concat(new Date(c).toUTCString())),yield t.olmDevice.recordSessionProblem(s,"wedged",!0),a();return}l.set(s,Date.now()+e7);var u=t.deviceList.getDeviceByIdentityKey(o,s);if(!u&&(yield t.downloadKeys([i],!1),u=t.deviceList.getDeviceByIdentityKey(o,s),!u)){b.info("Couldn't find device for identity key "+s+": not re-establishing session"),yield t.olmDevice.recordSessionProblem(s,"wedged",!1),a();return}var d=new Map([[i,[u]]]);yield xo(t.olmDevice,t.baseApis,d,!0),l.set(s,Date.now()+Z9);var f={algorithm:wr,sender_key:t.olmDevice.deviceCurve25519Key,ciphertext:{},[tn]:_i()};yield Ns(f.ciphertext,t.userId,t.deviceId,t.olmDevice,i,u,{type:"m.dummy"}),yield t.olmDevice.recordSessionProblem(s,"wedged",!0),a(),yield t.baseApis.sendToDevice("m.room.encrypted",new Map([[i,new Map([[u.deviceId,f]])]]));var p=yield t.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(i,u.deviceId);for(var h of p)t.requestRoomKey(h.requestBody,h.recipients,!0)}})()}onRoomMembership(e,t,n){var i=t.roomId,o=this.roomEncryptors.get(i);if(o){if(i in this.roomDeviceTrackingState){var s;t.membership==Be.Join?(b.log("Join event for "+t.userId+" in "+i),this.deviceList.startTrackingDeviceList(t.userId)):t.membership==Be.Invite&&(s=this.clientStore.getRoom(i))!==null&&s!==void 0&&s.shouldEncryptForInvitedMembers()&&(b.log("Invite event for "+t.userId+" in "+i),this.deviceList.startTrackingDeviceList(t.userId))}o.onRoomMembership(e,t,n)}}onRoomKeyRequestEvent(e){var t=e.getContent();if(t.action==="request"){var n=new t7(e);this.receivedRoomKeyRequests.push(n)}else if(t.action==="request_cancellation"){var i=new r7(e);this.receivedRoomKeyRequestCancellations.push(i)}}processReceivedRoomKeyRequests(){var e=this;return w(function*(){if(!e.processingRoomKeyRequests){e.processingRoomKeyRequests=!0;try{var t=e.receivedRoomKeyRequests;e.receivedRoomKeyRequests=[];var n=e.receivedRoomKeyRequestCancellations;e.receivedRoomKeyRequestCancellations=[],yield Promise.all(t.map(i=>e.processReceivedRoomKeyRequest(i))),yield Promise.all(n.map(i=>e.processReceivedRoomKeyRequestCancellation(i)))}catch(i){b.error("Error processing room key requsts: ".concat(i))}finally{e.processingRoomKeyRequests=!1}}})()}processReceivedRoomKeyRequest(e){var t=this;return w(function*(){var n=e.userId,i=e.deviceId,o=e.requestBody,s=o.room_id,a=o.algorithm;if(b.log("m.room_key_request from ".concat(n,":").concat(i)+" for ".concat(s," / ").concat(o.session_id," (id ").concat(e.requestId,")")),n!==t.userId){if(!t.roomEncryptors.get(s)){b.debug("room key request for unencrypted room ".concat(s));return}var l=t.roomEncryptors.get(s),c=t.deviceList.getStoredDevice(n,i);if(!c){b.debug("Ignoring keyshare for unknown device ".concat(n,":").concat(i));return}try{yield l.reshareKeyWithDevice(o.sender_key,o.session_id,n,c)}catch(d){b.warn("Failed to re-share keys for session "+o.session_id+" with device "+n+":"+c.deviceId,d)}return}if(i===t.deviceId){b.log("Ignoring room key request from ourselves");return}if(!t.roomDecryptors.has(s)){b.log("room key request for unencrypted room ".concat(s));return}var u=t.roomDecryptors.get(s).get(a);if(!u){b.log("room key request for unknown alg ".concat(a," in room ").concat(s));return}if(!(yield u.hasKeysForKeyRequest(e))){b.log("room key request for unknown session ".concat(s," / ")+o.session_id);return}if(e.share=()=>{u.shareKeysWithDevice(e)},t.checkDeviceTrust(n,i).isVerified()){b.log("device is already verified: sharing keys"),e.share();return}t.emit(et.RoomKeyRequest,e)})()}processReceivedRoomKeyRequestCancellation(e){var t=this;return w(function*(){b.log("m.room_key_request cancellation for ".concat(e.userId,":")+"".concat(e.deviceId," (id ").concat(e.requestId,")")),t.emit(et.RoomKeyRequestCancellation,e)})()}getRoomDecryptor(e,t){var n,i;if(e&&(n=this.roomDecryptors.get(e),n||(n=new Map,this.roomDecryptors.set(e,n)),i=n.get(t),i))return i;var o=o_.get(t);if(!o)throw new cr(Lt.UNKNOWN_ENCRYPTION_ALGORITHM,'Unknown encryption algorithm "'+t+'".');return i=new o({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:e??void 0}),n&&n.set(t,i),i}getRoomDecryptors(e){var t=[];for(var n of this.roomDecryptors.values())n.has(e)&&t.push(n.get(e));return t}signObject(e){var t=this;return w(function*(){var n=new Map(Object.entries(e.signatures||{})),i=e.unsigned;delete e.signatures,delete e.unsigned;var o=n.get(t.userId)||{};n.set(t.userId,o),o["ed25519:"+t.deviceId]=yield t.olmDevice.sign(Io.stringify(e)),e.signatures=ms(n),i!==void 0&&(e.unsigned=i)})()}isRoomEncrypted(e){return this.roomList.isRoomEncrypted(e)}isEncryptionEnabledInRoom(e){var t=this;return w(function*(){return t.isRoomEncrypted(e)})()}getRoomEncryption(e){return this.roomList.getRoomEncryption(e)}isDehydrationSupported(){return w(function*(){return!1})()}startDehydration(e){return w(function*(){throw new Error("Not implemented")})()}restoreKeyBackup(e){throw new Error("Not implemented")}restoreKeyBackupWithPassphrase(e,t){throw new Error("Not implemented")}}function op(r){if(typeof r!="string"||r.indexOf(",")<0)return null;var e=Uint8Array.from(r.split(","),t=>parseInt(t));return Zr(e)}class t7{constructor(e){v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"requestId",void 0),v(this,"requestBody",void 0),v(this,"share",void 0);var t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id,this.requestBody=t.body||{},this.share=()=>{throw new Error("don't know how to share keys for this request yet")}}}class r7{constructor(e){v(this,"userId",void 0),v(this,"deviceId",void 0),v(this,"requestId",void 0);var t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id}}class n7{constructor(e){this.ourEvent=e,v(this,"timeline",void 0),v(this,"ourEventIndex",0),v(this,"paginateTokens",{[Ge.Backward]:null,[Ge.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?Ge.Backward:Ge.Forward]}setPaginateToken(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.paginateTokens[t?Ge.Backward:Ge.Forward]=e??null}addEvents(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}class Pm{static fromJson(e,t){var n=e.context||{},i=(n.events_before||[]).map(t),o=(n.events_after||[]).map(t),s=new n7(t(e.result)),a=s.ourEvent.threadRootId;return i=i.filter(l=>l.threadRootId===a),o=o.filter(l=>l.threadRootId===a),s.setPaginateToken(n.start,!0),s.addEvents(i,!0),s.addEvents(o,!1),s.setPaginateToken(n.end,!1),new Pm(e.rank,s)}constructor(e,t){this.rank=e,this.context=t}}var i7=function(r){return r.Public="public",r.Private="private",r}({}),Yw=function(r){return r.PrivateChat="private_chat",r.TrustedPrivateChat="trusted_private_chat",r.PublicChat="public_chat",r}({}),WN=function(r){return r.Public="public",r.Invite="invite",r.Private="private",r.Knock="knock",r.Restricted="restricted",r}({}),o7=function(r){return r.RoomMembership="m.room_membership",r}({}),gv=function(r){return r.CanJoin="can_join",r.Forbidden="forbidden",r}({}),Jw=function(r){return r.Invited="invited",r.Joined="joined",r.Shared="shared",r.WorldReadable="world_readable",r}({});function Ak(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Dk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ak(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Ak(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function s7(r,e){var t=!!e.preventReEmit,n=e.decrypt!==!1;function i(o){e.toDevice&&delete o.room_id;var s=r.getRoom(o.room_id),a;s&&o.state_key===void 0&&(a=s.findEventById(o.event_id)),!a||a.status?a=new pr(o):(a.setUnsigned(Dk(Dk({},a.getUnsigned()),o.unsigned)),t=!0);var l=a.getServerAggregatedRelation(Nt.Replace);if(l!=null&&l.content){var c=i(l);a.makeReplaced(c)}var u=s==null?void 0:s.findThreadForEvent(a);return u&&a.setThread(u),a.isEncrypted()&&(t||r.reEmitter.reEmit(a,[ot.Decrypted]),n&&r.decryptEventIfNeeded(a)),t||(r.reEmitter.reEmit(a,[ot.Replaced,ot.VisibilityChange]),s==null||s.reEmitter.reEmit(a,[ot.BeforeRedaction])),a}return i}function Nk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Xo(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Nk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Nk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class Lk{constructor(e,t,n){this.client=e,this.indexEvent=t,this.directory=n}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 w(function*(){yield e.client.sendStateEvent(e.roomId,So.name,{},e.id),yield e.client.redactEvent(e.roomId,e.id);var t=(yield e.getVersionHistory())[1];t&&(yield t.delete())})()}getName(){return this.indexEvent.getContent().name||"Unnamed File"}setName(e){var t=this;return w(function*(){yield t.client.sendStateEvent(t.roomId,So.name,Xo(Xo({},t.indexEvent.getContent()),{},{name:e}),t.id)})()}isLocked(){return this.indexEvent.getContent().locked||!1}setLocked(e){var t=this;return w(function*(){yield t.client.sendStateEvent(t.roomId,So.name,Xo(Xo({},t.indexEvent.getContent()),{},{locked:e}),t.id)})()}getFileInfo(){var e=this;return w(function*(){var t=yield e.getFileEvent(),n=t.getOriginalContent().file,i=e.client.mxcUrlToHttp(n.url);if(!i)throw new Error("No HTTP URL available for ".concat(n.url));return{info:n,httpUrl:i}})()}getFileEvent(){var e=this;return w(function*(){var t=e.client.getRoom(e.roomId);if(!t)throw new Error("Unknown room");for(var n=t.getUnfilteredTimelineSet().findEventById(e.id);!n&&t.getLiveTimeline().getState(we.BACKWARDS).paginationToken;)yield e.client.scrollback(t,100),n=t.getUnfilteredTimelineSet().findEventById(e.id);if(!n)throw new Error("Failed to find event");return yield e.client.decryptEventIfNeeded(n),n})()}createNewVersion(e,t,n,i){var o=this;return w(function*(){var s=yield o.directory.createFile(e,t,n,Xo(Xo({},i??{}),{},{"m.new_content":!0,"m.relates_to":{rel_type:Nt.Replace,event_id:o.id}}));return yield o.client.sendStateEvent(o.roomId,So.name,{active:!0,name:e,version:o.version+1},s.event_id),yield o.client.sendStateEvent(o.roomId,So.name,Xo(Xo({},o.indexEvent.getContent()),{},{active:!1}),o.id),s})()}getVersionHistory(){var e=this;return w(function*(){var t=[];t.push(e);var n=e.client.getRoom(e.roomId);if(!n)throw new Error("Invalid or unknown room");var i=[...n.getLiveTimeline().getEvents()].reverse(),o,s=yield e.getFileEvent();do if(o=i.find(l=>l.replacingEventId()===s.getId()),o){var a=e.directory.getFile(o.getId());if(a)t.push(a),s=o;else break}while(o);return t})()}}function Uk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function ia(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Uk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Uk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var a7={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[V.RoomPowerLevels]:100,[V.RoomHistoryVisibility]:100,[V.RoomTombstone]:100,[V.RoomEncryption]:100,[V.RoomName]:50,[V.RoomMessage]:50,[V.RoomMessageEncrypted]:50,[V.Sticker]:50},users:{}},fl=function(r){return r.Viewer="viewer",r.Editor="editor",r.Owner="owner",r}({});class jk{constructor(e,t){if(this.client=e,this.roomId=t,v(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(V.SpaceParent);return e!=null&&e.length?e.every(t=>{var n;return!((n=t.getContent())!==null&&n!==void 0&&n.via)}):!0}setName(e){var t=this;return w(function*(){yield t.client.sendStateEvent(t.roomId,V.RoomName,{name:e},"")})()}invite(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!0,o=[n.retryInvite(e)];i&&o.push(...n.getDirectories().map(s=>s.invite(e,i))),yield Promise.all(o)})()}retryInvite(e){var t=this;return mH(w(function*(){yield t.client.invite(t.roomId,e).catch(n=>{throw(n==null?void 0:n.errcode)==="M_FORBIDDEN"?new oD.AbortError(n):n})}))}setPermissions(e,t){var n=this;return w(function*(){var i,o=n.room.currentState.getStateEvents(V.RoomPowerLevels,"");if(Array.isArray(o))throw new Error("Unexpected return type for power levels");var s=(o==null?void 0:o.getContent())||{},a=s.users_default||0,l=s.events_default||50,c=((i=s.events)===null||i===void 0?void 0:i[V.RoomPowerLevels])||100,u=s.users||{};switch(t){case fl.Viewer:u[e]=a;break;case fl.Editor:u[e]=l;break;case fl.Owner:u[e]=c;break;default:throw new Error("Invalid role: "+t)}s.users=u,yield n.client.sendStateEvent(n.roomId,V.RoomPowerLevels,s,"")})()}getPermissions(e){var t,n,i=this.room.currentState.getStateEvents(V.RoomPowerLevels,"");if(Array.isArray(i))throw new Error("Unexpected return type for power levels");var o=(i==null?void 0:i.getContent())||{},s=o.users_default||0,a=o.events_default||50,l=((t=o.events)===null||t===void 0?void 0:t[V.RoomPowerLevels])||100,c=((n=o.users)===null||n===void 0?void 0:n[e])||s;return c>=l?fl.Owner:c>=a?fl.Editor:fl.Viewer}createDirectory(e){var t=this;return w(function*(){var n=yield t.client.unstableCreateFileTree(e);return yield t.client.sendStateEvent(t.roomId,V.SpaceChild,{via:[t.client.getDomain()]},n.roomId),yield t.client.sendStateEvent(n.roomId,V.SpaceParent,{via:[t.client.getDomain()]},t.roomId),n})()}getDirectories(){var e=[],t=this.room.currentState.getStateEvents(V.SpaceChild);for(var n of t)try{var i=n.getStateKey();if(i){var o=this.client.unstableGetFileTreeSpace(i);o&&e.push(o)}}catch(s){b.warn("Unable to create tree space instance for listing. Are we joined?",s)}return e}getDirectory(e){return this.getDirectories().find(t=>t.roomId===e)}delete(){var e=this;return w(function*(){var t=e.getDirectories();for(var n of t)yield n.delete();var i=[Be.Invite,Be.Knock,Be.Join],o=e.room.currentState.getStateEvents(V.RoomMember);for(var s of o){var a=s.getStateKey()!==e.client.getUserId();if(a&&i.includes(s.getContent().membership)){var l=s.getStateKey();if(!l)throw new Error("State key not found for branch");yield e.client.kick(e.roomId,l,"Room deleted")}}yield e.client.leave(e.roomId)})()}getOrderedChildren(e){var t=e.map(n=>({roomId:n.getStateKey(),order:n.getContent().order})).filter(n=>n.roomId);return t.sort((n,i)=>{if(n.order&&!i.order)return-1;if(!n.order&&i.order)return 1;if(!n.order&&!i.order){var o,s,a,l,c=this.client.getRoom(n.roomId),u=this.client.getRoom(i.roomId);if(!c||!u)return ep(n.roomId,i.roomId);var d=(o=(s=c.currentState.getStateEvents(V.RoomCreate,""))===null||s===void 0?void 0:s.getTs())!==null&&o!==void 0?o:0,f=(a=(l=u.currentState.getStateEvents(V.RoomCreate,""))===null||l===void 0?void 0:l.getTs())!==null&&a!==void 0?a:0;return d===f?ep(n.roomId,i.roomId):d-f}else return ep(n.order,i.order)}),t}getParentRoom(){var e=this.room.currentState.getStateEvents(V.SpaceParent),t=e[0];if(!t)throw new Error("Expected to have a parent in a non-top level space");var n=t.getStateKey();if(!n)throw new Error("No state key found for parent");var i=this.client.getRoom(n);if(!i)throw new Error("Unable to locate room for parent");return i}getOrder(){if(this.isTopLevel)return-1;var e=this.getParentRoom(),t=e.currentState.getStateEvents(V.SpaceChild),n=this.getOrderedChildren(t);return n.findIndex(i=>i.roomId===this.roomId)}setOrder(e){var t=this;return w(function*(){var n;if(t.isTopLevel)throw new Error("Cannot set order of top level spaces currently");var i=t.getParentRoom(),o=i.currentState.getStateEvents(V.SpaceChild),s=t.getOrderedChildren(o);e=Math.max(Math.min(e,s.length-1),0);var a=t.getOrder(),l=a<e;l&&e===s.length-1?e--:!l&&e===0&&e++;var c=s[l?e:e-1],u=s[l?e+1:e],d=Ds[0],f=!1;if(!c)u!=null&&u.order&&(d=bC(u.order));else if(e===s.length-1)u!=null&&u.order&&(d=uu(u.order));else{var p=c==null?void 0:c.order,h=u==null?void 0:u.order;p&&h?p===h?d=uu(p):d=gH(p,h):p?d=uu(p):h?d=bC(h):f=!0}if(f){for(var m,E=0;E<=e;E++){var y=s[E];if(E===0&&(m=y.order),y.order)m=y.order;else{var S;m=m?uu(m):Ds[0];var R=i.currentState.getStateEvents(V.SpaceChild,y.roomId),k=(S=R==null?void 0:R.getContent())!==null&&S!==void 0?S:{via:[t.client.getDomain()]};yield t.client.sendStateEvent(i.roomId,V.SpaceChild,ia(ia({},k),{},{order:m}),y.roomId)}}m&&(d=uu(m))}var x=i.currentState.getStateEvents(V.SpaceChild,t.roomId),T=(n=x==null?void 0:x.getContent())!==null&&n!==void 0?n:{via:[t.client.getDomain()]};yield t.client.sendStateEvent(i.roomId,V.SpaceChild,ia(ia({},T),{},{order:d}),t.roomId)})()}createFile(e,t,n,i){var o=this;return w(function*(){var s,{content_uri:a}=yield o.client.uploadContent(t,{includeFilename:!1});n.url=a;var l={msgtype:xi.File,body:e,url:a,file:n};i=(s=i)!==null&&s!==void 0?s:{},i["m.new_content"]&&(i["m.new_content"]=l);var c=yield o.client.sendMessage(o.roomId,ia(ia(ia({},i),l),{},{[DD.name]:{}}));return yield o.client.sendStateEvent(o.roomId,So.name,{active:!0,name:e},c.event_id),c})()}getFile(e){var t=this.room.currentState.getStateEvents(So.name,e);return t?new Lk(this.client,t,this):null}listFiles(){return this.listAllFiles().filter(e=>e.isActive)}listAllFiles(){var e,t=(e=this.room.currentState.getStateEvents(So.name))!==null&&e!==void 0?e:[];return t.map(n=>new Lk(this.client,n,this))}}var qN=function(r){return r.Recent="recent",r.Rank="rank",r}({}),va=function(r){return r.LocalStreamsChanged="local_streams_changed",r}({});class l7 extends Tt{constructor(e){super(),this.client=e,v(this,"audioInput",void 0),v(this,"audioSettings",void 0),v(this,"videoInput",void 0),v(this,"localUserMediaStream",void 0),v(this,"userMediaStreams",[]),v(this,"screensharingStreams",[]),v(this,"getMediaStreamPromise",void 0)}restoreMediaSettings(e,t){this.audioInput=e,this.videoInput=t}setAudioInput(e){var t=this;return w(function*(){b.info("MediaHandler setAudioInput() running (deviceId=".concat(e,")")),t.audioInput!==e&&(t.audioInput=e,yield t.updateLocalUsermediaStreams())})()}setAudioSettings(e){var t=this;return w(function*(){b.info("MediaHandler setAudioSettings() running (opts=".concat(JSON.stringify(e),")")),t.audioSettings=Object.assign({},e),yield t.updateLocalUsermediaStreams()})()}setVideoInput(e){var t=this;return w(function*(){b.info("MediaHandler setVideoInput() running (deviceId=".concat(e,")")),t.videoInput!==e&&(t.videoInput=e,yield t.updateLocalUsermediaStreams())})()}setMediaInputs(e,t){var n=this;return w(function*(){b.log("MediaHandler setMediaInputs() running (audioInput: ".concat(e," videoInput: ").concat(t,")")),n.audioInput=e,n.videoInput=t,yield n.updateLocalUsermediaStreams()})()}updateLocalUsermediaStreams(){var e=this;return w(function*(){if(e.userMediaStreams.length!==0){var t=new Map;for(var n of e.client.callEventHandler.calls.values())t.set(n.callId,{audio:n.hasLocalUserMediaAudioTrack,video:n.hasLocalUserMediaVideoTrack});for(var i of e.userMediaStreams){b.log("MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=".concat(i.id,")"));for(var o of i.getTracks())o.stop()}e.userMediaStreams=[],e.localUserMediaStream=void 0;for(var s of e.client.callEventHandler.calls.values())if(!(s.callHasEnded()||!t.has(s.callId))){var{audio:a,video:l}=t.get(s.callId);b.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=".concat(s.callId,")"));var c=yield e.getUserMediaStream(a,l);s.callHasEnded()||(yield s.updateLocalUsermediaStream(c))}for(var u of e.client.groupCallEventHandler.groupCalls.values())if(u.localCallFeed){b.log("MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=".concat(u.groupCallId,")"));var d=yield e.getUserMediaStream(!0,u.type===km.Video);u.state!==Dt.Ended&&(yield u.updateLocalUsermediaStream(d))}e.emit(va.LocalStreamsChanged)}})()}hasAudioDevice(){return w(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(t=>t.kind==="audioinput").length>0}catch(t){return b.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",t),!1}})()}hasVideoDevice(){return w(function*(){try{var e=yield navigator.mediaDevices.enumerateDevices();return e.filter(t=>t.kind==="videoinput").length>0}catch(t){return b.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",t),!1}})()}getUserMediaStream(e,t){var n=arguments,i=this;return w(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!0;return i.getMediaStreamPromise?i.getMediaStreamPromise=i.getMediaStreamPromise.then(()=>i.getUserMediaStreamInternal(e,t,o)):i.getMediaStreamPromise=i.getUserMediaStreamInternal(e,t,o),i.getMediaStreamPromise})()}getUserMediaStreamInternal(e,t,n){var i=this;return w(function*(){var o=e&&(yield i.hasAudioDevice()),s=t&&(yield i.hasVideoDevice()),a,l=!0;if(i.localUserMediaStream){var c,u;o!==i.localUserMediaStream.getAudioTracks().length>0&&(l=!1),s!==i.localUserMediaStream.getVideoTracks().length>0&&(l=!1),o&&((c=i.localUserMediaStream.getAudioTracks()[0])===null||c===void 0||(c=c.getSettings())===null||c===void 0?void 0:c.deviceId)!==i.audioInput&&(l=!1),s&&((u=i.localUserMediaStream.getVideoTracks()[0])===null||u===void 0||(u=u.getSettings())===null||u===void 0?void 0:u.deviceId)!==i.videoInput&&(l=!1)}else l=!1;if(l){var h;if(a=i.localUserMediaStream.clone(),b.log("MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=".concat((h=i.localUserMediaStream)===null||h===void 0?void 0:h.id," newStreamId=").concat(a.id," shouldRequestAudio=").concat(o," shouldRequestVideo=").concat(s,")")),!o)for(var m of a.getAudioTracks())a.removeTrack(m);if(!s)for(var E of a.getVideoTracks())a.removeTrack(E)}else{var d=i.getUserMediaContraints(o,s);a=yield navigator.mediaDevices.getUserMedia(d),b.log("MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=".concat(a.id,", shouldRequestAudio=").concat(o,", shouldRequestVideo=").concat(s,", constraints=").concat(JSON.stringify(d),")"));for(var f of a.getTracks()){var p=f.getSettings();f.kind==="audio"?i.audioInput=p.deviceId:f.kind==="video"&&(i.videoInput=p.deviceId)}n&&(i.localUserMediaStream=a)}return n&&i.userMediaStreams.push(a),i.emit(va.LocalStreamsChanged),a})()}stopUserMediaStream(e){b.log("MediaHandler stopUserMediaStream() stopping (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop();var n=this.userMediaStreams.indexOf(e);if(n!==-1&&(b.debug("MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=".concat(e.id,")"),e.id),this.userMediaStreams.splice(n,1)),this.emit(va.LocalStreamsChanged),this.localUserMediaStream===e)this.localUserMediaStream=void 0;else for(var i of e.getTracks()){var o;if((o=this.localUserMediaStream)!==null&&o!==void 0&&o.getTrackById(i.id)){this.stopUserMediaStream(this.localUserMediaStream);break}}}getScreensharingStream(){var e=arguments,t=this;return w(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:{},i=e.length>1&&e[1]!==void 0?e[1]:!0,o;if(t.screensharingStreams.length===0){var s=t.getScreenshareContraints(n);n.desktopCapturerSourceId?(b.debug("MediaHandler getScreensharingStream() calling getUserMedia() (opts=".concat(JSON.stringify(n),")")),o=yield navigator.mediaDevices.getUserMedia(s)):(b.debug("MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=".concat(JSON.stringify(n),")")),o=yield navigator.mediaDevices.getDisplayMedia(s))}else{var a=t.screensharingStreams[t.screensharingStreams.length-1];b.log("MediaHandler getScreensharingStream() cloning (streamId=".concat(a.id,")")),o=a.clone()}return i&&t.screensharingStreams.push(o),t.emit(va.LocalStreamsChanged),o})()}stopScreensharingStream(e){b.debug("MediaHandler stopScreensharingStream() stopping stream (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop();var n=this.screensharingStreams.indexOf(e);n!==-1&&(b.debug("MediaHandler stopScreensharingStream() splicing stream out (streamId=".concat(e.id,")")),this.screensharingStreams.splice(n,1)),this.emit(va.LocalStreamsChanged)}stopAllStreams(){for(var e of this.userMediaStreams){b.log("MediaHandler stopAllStreams() stopping (streamId=".concat(e.id,")"));for(var t of e.getTracks())t.stop()}for(var n of this.screensharingStreams)for(var i of n.getTracks())i.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0,this.emit(va.LocalStreamsChanged)}getUserMediaContraints(e,t){var n=!!navigator.webkitGetUserMedia;return{audio:e?{deviceId:this.audioInput?{ideal:this.audioInput}:void 0,autoGainControl:this.audioSettings?{ideal:this.audioSettings.autoGainControl}:void 0,echoCancellation:this.audioSettings?{ideal:this.audioSettings.echoCancellation}:void 0,noiseSuppression:this.audioSettings?{ideal:this.audioSettings.noiseSuppression}:void 0}:!1,video:t?{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:n?{exact:640}:{ideal:640},height:n?{exact:360}:{ideal:360}}:!1}}getScreenshareContraints(e){var{desktopCapturerSourceId:t,audio:n}=e;return t?{audio:n??!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t}}}:{audio:n??!1,video:!0}}}var Fk=function(r){return r.RequestFinished="FINISHED",r.Complete="COMPLETE",r}({}),kf=function(r){return r.PreProcess="ExtState.PreProcess",r.PostProcess="ExtState.PostProcess",r}({}),p_=function(r){return r.RoomData="SlidingSync.RoomData",r.Lifecycle="SlidingSync.Lifecycle",r.List="SlidingSync.List",r}({}),c7=3;class u7{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return kf.PreProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return w(function*(){e.device_lists&&(yield t.crypto.processDeviceLists(e.device_lists)),yield t.crypto.processKeyCounts(e.device_one_time_keys_count,e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]),t.crypto.onSyncCompleted({})})()}}class d7{constructor(e,t){this.client=e,this.cryptoCallbacks=t,v(this,"nextBatch",null)}name(){return"to_device"}when(){return kf.PreProcess}onRequest(e){var t={since:this.nextBatch!==null?this.nextBatch:void 0};return e&&(t.limit=100,t.enabled=!0),t}onResponse(e){var t=this;return w(function*(){var n=[],i=e.events||[];i.length>0&&t.cryptoCallbacks&&(i=yield t.cryptoCallbacks.preprocessToDeviceMessages(i)),i.map(t.client.getEventMapper()).map(o=>{if(o.getType()==="m.key.verification.cancel"){var s=o.getContent().transaction_id;s&&n.push(s)}return o}).forEach(o=>{var s=o.getContent();if(o.getType()=="m.room.message"&&s.msgtype=="m.bad.encrypted"){b.log("Ignoring undecryptable to-device event from "+o.getSender());return}if(o.getType()==="m.key.verification.start"||o.getType()==="m.key.verification.request"){var a=s.transaction_id;n.includes(a)&&o.flagCancelled()}t.client.emit(be.ToDeviceEvent,o)}),t.nextBatch=e.next_batch})()}}class f7{constructor(e){this.client=e}name(){return"account_data"}when(){return kf.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return w(function*(){e.global&&e.global.length>0&&t.processGlobalAccountData(e.global);for(var n in e.rooms){var i=tc(t.client,n,e.rooms[n]),o=t.client.getRoom(n);if(!o){b.warn("got account data for room but room doesn't exist on client:",n);continue}o.addAccountData(i),i.forEach(s=>{t.client.emit(be.Event,s)})}})()}processGlobalAccountData(e){var t=tc(this.client,void 0,e),n=t.reduce((i,o)=>(i[o.getType()]=this.client.store.getAccountData(o.getType()),i),{});this.client.store.storeAccountDataEvents(t),t.forEach(i=>{if(i.getType()===V.PushRules){var o=i.getContent();this.client.setPushRules(o)}var s=n[i.getType()];return this.client.emit(be.AccountData,i,s),i})}}class h7{constructor(e){this.client=e}name(){return"typing"}when(){return kf.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return w(function*(){if(e!=null&&e.rooms)for(var n in e.rooms)HN(t.client,n,[e.rooms[n]])})()}}class p7{constructor(e){this.client=e}name(){return"receipts"}when(){return kf.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){var t=this;return w(function*(){if(e!=null&&e.rooms)for(var n in e.rooms)HN(t.client,n,[e.rooms[n]])})()}}class GN{constructor(e,t,n,i){this.slidingSync=e,this.client=t,v(this,"opts",void 0),v(this,"syncOpts",void 0),v(this,"syncState",null),v(this,"syncStateData",void 0),v(this,"lastPos",null),v(this,"failCount",0),v(this,"notifEvents",[]),this.opts=pN(n),this.syncOpts=vN(i),t.getNotifTimelineSet()&&t.reEmitter.reEmit(t.getNotifTimelineSet(),[pe.Timeline,pe.TimelineReset]),this.slidingSync.on(p_.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(p_.RoomData,this.onRoomData.bind(this));var o=[new d7(this.client,this.syncOpts.cryptoCallbacks),new f7(this.client),new h7(this.client),new p7(this.client)];this.syncOpts.crypto&&o.push(new u7(this.syncOpts.crypto)),o.forEach(s=>{this.slidingSync.registerExtension(s)})}onRoomData(e,t){var n=this;return w(function*(){var i=n.client.store.getRoom(e);if(!i){if(!t.initial){b.debug("initial flag not set but no stored room exists for room ",e,t);return}i=mN(n.client,e,n.opts)}yield n.processRoomData(n.client,i,t)})()}onLifecycle(e,t,n){switch(n&&b.debug("onLifecycle",e,n),e){case Fk.Complete:if(this.purgeNotifications(),!t)break;this.lastPos||this.updateSyncState(ct.Prepared,{oldSyncToken:void 0,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(ct.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.lastPos=t.pos;break;case Fk.RequestFinished:if(n){if(this.failCount+=1,this.updateSyncState(this.failCount>c7?ct.Error:ct.Reconnecting,{error:new hr(n)}),this.shouldAbortSync(new hr(n)))return}else this.failCount=0;break}}syncLeftRooms(){return w(function*(){return[]})()}peek(e){return w(function*(){return null})()}stopPeeking(){}setPresence(e){}getSyncState(){return this.syncState}getSyncStateData(){var e;return(e=this.syncStateData)!==null&&e!==void 0?e:null}createRoom(e){var{timelineSupport:t}=this.client,n=new Tm(e,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t});return this.client.reEmitter.reEmit(n,[pe.Name,pe.Redaction,pe.RedactionCancelled,pe.Receipt,pe.Tags,pe.LocalEchoUpdated,pe.AccountData,pe.MyMembership,pe.Timeline,pe.TimelineReset]),this.registerStateListeners(n),n}registerStateListeners(e){this.client.reEmitter.reEmit(e.currentState,[Me.Events,Me.Members,Me.NewMember,Me.Update]),e.currentState.on(Me.NewMember,(t,n,i)=>{var o;i.user=(o=this.client.getUser(i.userId))!==null&&o!==void 0?o:void 0,this.client.reEmitter.reEmit(i,[Ar.Name,Ar.Typing,Ar.PowerLevel,Ar.Membership])})}shouldAbortSync(e){return e.errcode==="M_UNKNOWN_TOKEN"?(b.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(ct.Error,{error:e}),!0):!1}processRoomData(e,t,n){var i=this;return w(function*(){n=v7(e,t.roomId,n);var o=tc(i.client,t.roomId,n.required_state),s=tc(i.client,t.roomId,n.timeline,!1),a=[];if(n.initial){var l=new Set;t.getLiveTimeline().getEvents().forEach(S=>{l.add(S.getId())});for(var c=[],u=[],d=!1,f=s.length-1;f>=0;f--){var p=s[f];if(l.has(p.getId())){d=!0;continue}d?c.push(p):u.unshift(p)}s=u,c.length>0&&t.addEventsToTimeline(c,!0,t.getLiveTimeline(),n.prev_batch)}var h=t.hasEncryptionStateEvent();if(n.notification_count!=null&&t.setUnreadNotificationCount(it.Total,n.notification_count),n.highlight_count!=null&&(!h||h&&t.getUnreadNotificationCount(it.Highlight)<=0)&&t.setUnreadNotificationCount(it.Highlight,n.highlight_count),Number.isInteger(n.invited_count)&&t.currentState.setInvitedMemberCount(n.invited_count),Number.isInteger(n.joined_count)&&t.currentState.setJoinedMemberCount(n.joined_count),n.invite_state){var m=tc(i.client,t.roomId,n.invite_state);yield i.injectRoomEvents(t,m),n.initial&&(t.recalculate(),i.client.store.storeRoom(t),i.client.emit(be.Room,t)),m.forEach(S=>{i.client.emit(be.Event,S)}),t.updateMyMembership(Be.Invite);return}if(n.initial){var E;t.getLiveTimeline().setPaginationToken((E=n.prev_batch)!==null&&E!==void 0?E:null,we.BACKWARDS)}yield i.injectRoomEvents(t,o,s,n.num_live),t.addEphemeralEvents(a),t.updateMyMembership(Be.Join),t.recalculate(),n.initial&&(e.store.storeRoom(t),e.emit(be.Room,t)),i.addNotifications(s);var y=function(){var S=w(function*(R){e.emit(be.Event,R),R.isState()&&R.getType()==V.RoomEncryption&&i.syncOpts.cryptoCallbacks&&(yield i.syncOpts.cryptoCallbacks.onCryptoEvent(t,R))});return function(k){return S.apply(this,arguments)}}();yield Fl(o,y),yield Fl(s,y),a.forEach(function(S){e.emit(be.Event,S)}),t.decryptCriticalEvents()})()}injectRoomEvents(e,t,n,i){var o=this;return w(function*(){n=n||[],t=t||[],i=i||0;var s=e.getLiveTimeline(),a=s.getEvents().length==0;if(a){for(var l of t)o.client.getPushActionsForEvent(l);s.initialiseState(t)}a||(e.oldState.setStateEvents(t),e.currentState.setStateEvents(t));var c=[];i>0&&(c=n.slice(-1*i),n=n.slice(0,-1*c.length)),yield e.addLiveEvents(n,{fromCache:!0}),c.length>0&&(yield e.addLiveEvents(c,{fromCache:!1})),e.recalculate(),o.resolveInvites(e)})()}resolveInvites(e){if(!(!e||!this.opts.resolveInvitesToProfiles)){var t=this.client;e.getMembersWithMembership(Be.Invite).forEach(function(n){if(!n.requestedProfileInfo){n.requestedProfileInfo=!0;var i=t.getUser(n.userId),o;i?o=Promise.resolve({avatar_url:i.avatarUrl,displayname:i.displayName}):o=t.getProfileInfo(n.userId),o.then(function(s){var a=n.events.member;a.getContent().membership===Be.Invite&&(a.getContent().avatar_url=s.avatar_url,a.getContent().displayname=s.displayname,n.setMembershipEvent(a,e.currentState))},function(s){})}})}}retryImmediately(){return!0}sync(){var e=this;return w(function*(){for(b.debug("Sliding sync init loop");!e.client.isGuest();)try{b.debug("Getting push rules...");var t=yield e.client.getPushRules();b.debug("Got push rules"),e.client.pushRules=t;break}catch(n){if(b.error("Getting push rules failed",n),e.shouldAbortSync(n))return}yield e.slidingSync.start()})()}stop(){b.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,t){var n=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(be.Sync,this.syncState,n,t)}addNotifications(e){if(this.client.getNotifTimelineSet())for(var t of e){var n=this.client.getPushActionsForEvent(t);n&&n.notify&&n.tweaks&&n.tweaks.highlight&&this.notifEvents.push(t)}}purgeNotifications(){this.notifEvents.sort(function(e,t){return e.getTs()-t.getTs()}),this.notifEvents.forEach(e=>{var t;(t=this.client.getNotifTimelineSet())===null||t===void 0||t.addLiveEvent(e)}),this.notifEvents=[]}}function v7(r,e,t){if(!t.name)return t;for(var n of t.required_state)if(n.type===V.RoomName&&n.state_key==="")return n.content={name:t.name},t;return t.required_state.push({event_id:"$fake-sliding-sync-name-event-"+e,state_key:"",type:V.RoomName,content:{name:t.name},sender:r.getUserId(),origin_server_ts:new Date().getTime()}),t}function tc(r,e,t){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,i=r.getEventMapper({decrypt:n});return t.map(function(o){return o.room_id=e,i(o)})}function HN(r,e,t){var n=tc(r,e,t),i=r.getRoom(e);if(!i){b.warn("got ephemeral events for room but room doesn't exist on client:",e);return}i.addEphemeralEvents(n),n.forEach(o=>{r.emit(be.Event,o)})}class Rc{static RETRY_BACKOFF_RATELIMIT(e,t,n){return lN(n,t,!1)}static QUEUE_MESSAGES(e){return e.getType()===V.RoomMessage||e.hasAssociation()?"message":null}constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Rc.RETRY_BACKOFF_RATELIMIT,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Rc.QUEUE_MESSAGES;this.retryAlgorithm=e,this.queueAlgorithm=t,v(this,"queues",{}),v(this,"activeQueues",[]),v(this,"procFn",null),v(this,"processQueue",n=>{var i=this.peekNextEvent(n);if(!i){this.disableQueue(n);return}this.queues[n].length,Promise.resolve().then(()=>this.procFn(i.event)).then(o=>{this.removeNextEvent(n),i.event.getId(),i.defer.resolve(o),this.processQueue(n)},o=>{i.attempts+=1;var s=this.retryAlgorithm(i.event,i.attempts,o);i.attempts,i.event.getId(),s===-1?(b.info("Queue '%s' giving up on event %s",n,i.event.getId()),this.clearQueue(n,o)):setTimeout(this.processQueue,s,n)})})}getQueueForEvent(e){var t=this.queueAlgorithm(e);return!t||!this.queues[t]?null:this.queues[t].map(function(n){return n.event})}removeEventFromQueue(e){var t=this.queueAlgorithm(e);if(!t||!this.queues[t])return!1;var n=!1;return iv(this.queues[t],i=>i.event.getId()===e.getId()?(n=!0,!0):!1),n}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){var t=this.queueAlgorithm(e);if(!t)return null;this.queues[t]||(this.queues[t]=[]);var n=Hs();return this.queues[t].push({event:e,defer:n,attempts:0}),e.getId(),this.startProcessingQueues(),n.promise}startProcessingQueues(){this.procFn&&Object.keys(this.queues).filter(e=>this.activeQueues.indexOf(e)===-1&&this.queues[e].length>0).forEach(e=>{this.activeQueues.push(e),this.processQueue(e)})}disableQueue(e){var t=this.activeQueues.indexOf(e);t>=0&&this.activeQueues.splice(t,1),b.info("Stopping queue '%s' as it is now empty",e)}clearQueue(e,t){b.info("clearing queue '%s'",e);for(var n;n=this.removeNextEvent(e);)n.defer.reject(t);this.disableQueue(e)}peekNextEvent(e){var t=this.queues[e];if(Array.isArray(t))return t[0]}removeNextEvent(e){var t=this.queues[e];if(Array.isArray(t))return t.shift()}}var Bk=20;class m7{constructor(e){var t=this;this.client=e,v(this,"sending",!1),v(this,"running",!0),v(this,"retryTimeout",null),v(this,"retryAttempts",0),v(this,"sendQueue",w(function*(){if(t.retryTimeout!==null&&clearTimeout(t.retryTimeout),t.retryTimeout=null,!(t.sending||!t.running)){b.debug("Attempting to send queued to-device messages"),t.sending=!0;var n;try{for(;t.running&&(n=yield t.client.store.getOldestToDeviceBatch(),n!==null);)yield t.sendBatch(n),yield t.client.store.removeToDeviceBatch(n.id),t.retryAttempts=0;if(!t.running)return;b.debug("All queued to-device messages sent")}catch(o){++t.retryAttempts;var i=Rc.RETRY_BACKOFF_RATELIMIT(null,t.retryAttempts,o);if(i===-1){Math.floor(o.httpStatus/100)===4?(b.error("Fatal error when sending to-device message - dropping to-device batch!",o),yield t.client.store.removeToDeviceBatch(n.id)):b.info("Automatic retry limit reached for to-device messages.");return}b.info("Failed to send batch of to-device messages. Will retry in ".concat(i,"ms"),o),t.retryTimeout=setTimeout(t.sendQueue,i)}finally{t.sending=!1}}})),v(this,"onResumedSync",(n,i)=>{n===ct.Syncing&&i!==ct.Syncing&&(b.info("Resuming queue after resumed sync"),this.sendQueue())})}start(){this.running=!0,this.sendQueue(),this.client.on(be.Sync,this.onResumedSync)}stop(){this.running=!1,this.retryTimeout!==null&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.client.removeListener(be.Sync,this.onResumedSync)}queueBatch(e){var t=this;return w(function*(){for(var n=[],i=0;i<e.batch.length;i+=Bk){var o={eventType:e.eventType,batch:e.batch.slice(i,i+Bk),txnId:t.client.makeTxnId()};n.push(o);var s=o.batch.map(a=>"".concat(a.userId,"/").concat(a.deviceId," (msgid ").concat(a.payload[tn],")"));b.info("Enqueuing batch of to-device messages. type=".concat(e.eventType," txnid=").concat(o.txnId),s)}yield t.client.store.saveToDeviceBatches(n),t.sendQueue()})()}sendBatch(e){var t=this;return w(function*(){var n=new Gt(()=>new Map);for(var i of e.batch)n.getOrCreate(i.userId).set(i.deviceId,i.payload);b.info("Sending batch of ".concat(e.batch.length," to-device messages with ID ").concat(e.id," and txnId ").concat(e.txnId)),yield t.client.sendToDevice(e.eventType,n,e.txnId)})()}}var fy=new ln.UnstableValue("m.policies","org.matrix.msc3847.policies"),Th=new ln.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites"),Kk=function(r){return r.Ban="m.ban",r}({}),rc=function(r){return r.User="m.policy.user",r.Room="m.policy.room",r.Server="m.policy.server",r}({}),Vk={[rc.User]:V.PolicyRuleUser,[rc.Room]:V.PolicyRuleRoom,[rc.Server]:V.PolicyRuleServer};class g7{constructor(e){this.client=e}addRule(e,t,n){var i=this;return w(function*(){var o=yield i.getOrCreateTargetRoom(),s=yield i.client.sendStateEvent(o.roomId,Vk[e],{entity:t,reason:n,recommendation:Kk.Ban});return s.event_id})()}removeRule(e){var t=this;return w(function*(){yield t.client.redactEvent(e.getRoomId(),e.getId())})()}addSource(e){var t=this;return w(function*(){yield t.client.joinRoom(e);var n=(yield t.getOrCreateSourceRooms()).map(i=>i.roomId);return n.includes(e)?!1:(n.push(e),yield t.withIgnoreInvitesPolicies(i=>{i.sources=n}),!0)})()}getRuleForInvite(e){var t=this;return w(function*(){var{sender:n,roomId:i}=e,o=yield t.getOrCreateSourceRooms(),s=n.split(":")[1],a=i.split(":")[1];for(var l of o){var c=l.getUnfilteredTimelineSet().getLiveTimeline().getState(we.FORWARDS);for(var{scope:u,entities:d}of[{scope:rc.Room,entities:[i]},{scope:rc.User,entities:[n]},{scope:rc.Server,entities:[s,a]}]){var f=c.getStateEvents(Vk[u]);for(var p of f){var h=p.getContent();if((h==null?void 0:h.recommendation)==Kk.Ban){var m=h==null?void 0:h.entity;if(m){var E=void 0;try{E=new RegExp(_D(m))}catch{continue}for(var y of d)if(y&&E.test(y))return p}}}}}return null})()}getOrCreateTargetRoom(){var e=this;return w(function*(){var t=e.getIgnoreInvitesPolicies(),n=t.target;if(typeof n!="string"&&(n=null),n){var i=e.client.getRoom(n);if(i)return i;n=null}return n=(yield e.client.createRoom({name:"Individual Policy Room",preset:Yw.PrivateChat})).room_id,yield e.withIgnoreInvitesPolicies(o=>{o.target=n}),e.client.getRoom(n)})()}getOrCreateSourceRooms(){var e=this;return w(function*(){var t=e.getIgnoreInvitesPolicies(),n=t.sources,i=!1;Array.isArray(n)||(i=!0,n=[]);var o=n.filter(a=>typeof a=="string").map(a=>e.client.getRoom(a)).filter(a=>!!a);if(o.length!=n.length&&(i=!0),o.length==0){var s=yield e.getOrCreateTargetRoom();i=!0,o=[s]}return i&&(yield e.withIgnoreInvitesPolicies(a=>{a.sources=n})),o})()}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}withIgnoreInvitesPolicies(e){var t=this;return w(function*(){var{policies:n,ignoreInvitesPolicies:i}=t.getPoliciesAndIgnoreInvitesPolicies();e(i),n[Th.name]=i,yield t.client.setAccountData(fy.name,n)})()}getPoliciesAndIgnoreInvitesPolicies(){var e={};for(var t of[fy.name,fy.altName]){var n;if(t){var i=(n=this.client.getAccountData(t))===null||n===void 0?void 0:n.getContent();if(i){e=i;break}}}var o={},s=!1;for(var a of[Th.name,Th.altName])if(a){var l=e[a];if(l&&typeof l=="object"){o=l,s=!0;break}}return s||(e[Th.name]=o),{policies:e,ignoreInvitesPolicies:o}}}var hy="matrix-js-sdk",sp=function(r){return r.Cancel="cancel",r.Restart="restart",r.Send="send",r}({}),zN=r=>r.type==="livekit"&&"focus_selection"in r,y7=(r,e)=>{var t,n="Malformed session membership event: ";return typeof r.device_id!="string"&&e.push(n+"device_id must be string"),typeof r.call_id!="string"&&e.push(n+"call_id must be string"),typeof r.application!="string"&&e.push(n+"application must be a string"),typeof((t=r.focus_active)===null||t===void 0?void 0:t.type)!="string"&&e.push(n+"focus_active.type must be a string"),Array.isArray(r.foci_preferred)||e.push(n+"foci_preferred must be an array"),r.created_ts&&typeof r.created_ts!="number"&&e.push(n+"created_ts must be number"),r.scope&&typeof r.scope!="string"&&e.push(n+"scope must be string"),e.length===0},is=r=>"membershipID"in r,S7=(r,e)=>{var t="Malformed legacy rtc membership event: ";return"expires"in r||"expires_ts"in r||e.push(t+"expires_ts or expires must be present"),"expires"in r&&typeof r.expires!="number"&&e.push(t+"expires must be numeric"),"expires_ts"in r&&typeof r.expires_ts!="number"&&e.push(t+"expires_ts must be numeric"),typeof r.device_id!="string"&&e.push(t+"device_id must be string"),typeof r.call_id!="string"&&e.push(t+"call_id must be string"),typeof r.application!="string"&&e.push(t+"application must be a string"),typeof r.membershipID!="string"&&e.push(t+"membershipID must be a string"),r.created_ts&&typeof r.created_ts!="number"&&e.push(t+"created_ts must be number"),r.scope&&typeof r.scope!="string"&&e.push(t+"scope must be string"),e.length===0};class gu{static equal(e,t){return Va(e.membershipData,t.membershipData)}constructor(e,t){this.parentEvent=e,v(this,"membershipData",void 0);var n=[],i=[];if(!y7(t,n)&&!S7(t,i))throw Error("unknown CallMembership data. Does not match legacy call.member (".concat(i.join(" & "),") events nor MSC4143 (").concat(n.join(" & "),")"));this.membershipData=t}get sender(){return this.parentEvent.getSender()}get eventId(){return this.parentEvent.getId()}get callId(){return this.membershipData.call_id}get deviceId(){return this.membershipData.device_id}get application(){return this.membershipData.application}get scope(){return this.membershipData.scope}get membershipID(){return is(this.membershipData)?this.membershipData.membershipID:this.createdTs().toString()}createdTs(){var e;return(e=this.membershipData.created_ts)!==null&&e!==void 0?e:this.parentEvent.getTs()}getAbsoluteExpiry(){if(is(this.membershipData))return"expires"in this.membershipData?this.createdTs()+this.membershipData.expires:this.membershipData.expires_ts}getLocalExpiry(){if(is(this.membershipData))if("expires"in this.membershipData){var e=this.parentEvent.getTs()-this.createdTs(),t=this.parentEvent.localTimestamp-e;return t+this.membershipData.expires}else return this.membershipData.expires_ts}getMsUntilExpiry(){if(is(this.membershipData))return this.getAbsoluteExpiry()-Date.now()}isExpired(){return is(this.membershipData)?this.getMsUntilExpiry()<=0:!1}getPreferredFoci(){var e;return is(this.membershipData)?(e=this.membershipData.foci_active)!==null&&e!==void 0?e:[]:this.membershipData.foci_preferred}getFocusSelection(){if(is(this.membershipData))return"oldest_membership";var e=this.membershipData.focus_active;if(zN(e))return e.focus_selection}}function $k(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function b7(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?$k(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):$k(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Ve=b.getChild("MatrixRTCSession"),ap=(r,e)=>"".concat(r,":").concat(e),py=r=>ap(r.sender,r.deviceId);function _7(r,e){return r===e?!0:!!r&&!!e&&r.length===e.length&&r.every((t,n)=>t===e[n])}var hl=function(r){return r.MembershipsChanged="memberships_changed",r.JoinStateChanged="join_state_changed",r.EncryptionKeyChanged="encryption_key_changed",r}({});class nc extends Tt{get membershipExpiryTimeout(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipExpiryTimeout)!==null&&e!==void 0?e:60*60*1e3}get memberEventCheckPeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.memberEventCheckPeriod)!==null&&e!==void 0?e:2*60*1e3}get callMemberEventRetryDelayMinimum(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryDelayMinimum)!==null&&e!==void 0?e:3e3}get updateEncryptionKeyThrottle(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.updateEncryptionKeyThrottle)!==null&&e!==void 0?e:3e3}get makeKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.makeKeyDelay)!==null&&e!==void 0?e:3e3}get useKeyDelay(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.useKeyDelay)!==null&&e!==void 0?e:5e3}get membershipServerSideExpiryTimeout(){var e,t,n;return(e=(t=this.membershipServerSideExpiryTimeoutOverride)!==null&&t!==void 0?t:(n=this.joinConfig)===null||n===void 0?void 0:n.membershipServerSideExpiryTimeout)!==null&&e!==void 0?e:8e3}get membershipKeepAlivePeriod(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.membershipKeepAlivePeriod)!==null&&e!==void 0?e:5e3}get callMemberEventRetryJitter(){var e,t;return(e=(t=this.joinConfig)===null||t===void 0?void 0:t.callMemberEventRetryJitter)!==null&&e!==void 0?e:2e3}get callId(){return this._callId}static callMembershipsForRoom(e){var t=e.getLiveTimeline().getState(we.FORWARDS);if(!t)throw Ve.warn("Couldn't get state for room "+e.roomId),new Error("Could't get state for room "+e.roomId);var n=t.getStateEvents(V.GroupCallMemberPrefix),i=[];for(var o of n){var s=o.getContent(),a=Object.keys(s).length;if(a!==0){var l=[];if(a>1&&"focus_active"in s)l.push(s);else if(a===1&&"memberships"in s){if(!Array.isArray(s.memberships)){Ve.warn("Malformed member event from ".concat(o.getSender(),": memberships is not an array"));continue}l=s.memberships}if(l.length!==0)for(var c of l)try{var u,d=new gu(o,c);if(d.callId!==""||d.scope!=="m.room"){Ve.info("Ignoring user-scoped call");continue}if(d.isExpired()){Ve.info("Ignoring expired device membership ".concat(d.sender,"/").concat(d.deviceId));continue}if(!e.hasMembershipState((u=d.sender)!==null&&u!==void 0?u:"",Be.Join)){Ve.info("Ignoring membership of user ".concat(d.sender," who is not in the room."));continue}i.push(d)}catch(f){Ve.warn("Couldn't construct call membership: ",f)}}}return i.sort((f,p)=>f.createdTs()-p.createdTs()),i.length>1&&Ve.debug("Call memberships in room ".concat(e.roomId,", in order: "),i.map(f=>[f.createdTs(),f.sender])),i}static roomSessionForRoom(e,t){var n=nc.callMembershipsForRoom(t);return new nc(e,t,n)}constructor(e,t,n){var i,o;super(),i=this,this.client=e,this.room=t,this.memberships=n,v(this,"_callId",void 0),v(this,"relativeExpiry",void 0),v(this,"joinConfig",void 0),v(this,"membershipServerSideExpiryTimeoutOverride",void 0),v(this,"membershipId",void 0),v(this,"memberEventTimeout",void 0),v(this,"expiryTimeout",void 0),v(this,"keysEventUpdateTimeout",void 0),v(this,"makeNewKeyTimeout",void 0),v(this,"setNewKeyTimeouts",new Set),v(this,"ownFocusActive",void 0),v(this,"ownFociPreferred",void 0),v(this,"updateCallMembershipRunning",!1),v(this,"needCallMembershipUpdate",!1),v(this,"manageMediaKeys",!1),v(this,"useLegacyMemberEvents",!0),v(this,"encryptionKeys",new Map),v(this,"lastEncryptionKeyUpdateRequest",void 0),v(this,"disconnectDelayId",void 0),v(this,"lastMembershipFingerprints",void 0),v(this,"currentEncryptionKeyIndex",-1),v(this,"statistics",{counters:{roomEventEncryptionKeysSent:0,roomEventEncryptionKeysReceived:0},totals:{roomEventEncryptionKeysReceivedTotalAge:0}}),v(this,"sendEncryptionKeysEvent",function(){var a=w(function*(l){if(i.keysEventUpdateTimeout!==void 0&&(clearTimeout(i.keysEventUpdateTimeout),i.keysEventUpdateTimeout=void 0),i.lastEncryptionKeyUpdateRequest=Date.now(),!!i.isJoined()){Ve.info("Sending encryption keys event. indexToSend=".concat(l));var c=i.client.getUserId(),u=i.client.getDeviceId();if(!c)throw new Error("No userId");if(!u)throw new Error("No deviceId");var d=i.getKeysForParticipant(c,u);if(!d){Ve.warn("Tried to send encryption keys event but no keys found!");return}if(typeof l!="number"&&i.currentEncryptionKeyIndex===-1){Ve.warn("Tried to send encryption keys event but no current key index found!");return}var f=l??i.currentEncryptionKeyIndex,p=d[f];try{var h={keys:[{index:f,key:Rm(p)}],device_id:u,call_id:"",sent_ts:Date.now()};i.statistics.counters.roomEventEncryptionKeysSent+=1,yield i.client.sendEvent(i.room.roomId,V.CallEncryptionKeysPrefix,h),Ve.debug("Embedded-E2EE-LOG updateEncryptionKeyEvent participantId=".concat(c,":").concat(u," numKeys=").concat(d.length," currentKeyIndex=").concat(i.currentEncryptionKeyIndex," keyIndexToSend=").concat(f),i.encryptionKeys)}catch(y){var m=y;if(m.event&&i.client.cancelPendingEvent(m.event),i.keysEventUpdateTimeout===void 0){var E=Aw(m,5e3);Ve.warn("Failed to send m.call.encryption_key, retrying in ".concat(E),y),i.keysEventUpdateTimeout=setTimeout(i.sendEncryptionKeysEvent,E)}else Ve.info("Not scheduling key resend as another re-send is already pending")}}});return function(l){return a.apply(this,arguments)}}()),v(this,"onCallEncryption",a=>{var l=a.getSender(),c=a.getContent(),u=c.device_id,d=c.call_id;if(!l){Ve.warn("Received m.call.encryption_keys with no userId: callId=".concat(d));return}if(d!==""){Ve.warn("Received m.call.encryption_keys with unsupported callId: userId=".concat(l,", deviceId=").concat(u,", callId=").concat(d));return}if(!Array.isArray(c.keys)){Ve.warn("Received m.call.encryption_keys where keys wasn't an array: callId=".concat(d));return}if(l===this.client.getUserId()&&u===this.client.getDeviceId()){Ve.info("Ignoring our own keys event");return}this.statistics.counters.roomEventEncryptionKeysReceived+=1;var f=Date.now()-(typeof c.sent_ts=="number"?c.sent_ts:a.getTs());this.statistics.totals.roomEventEncryptionKeysReceivedTotalAge+=f;for(var p of c.keys){if(!p){Ve.info("Ignoring false-y key in keys event");continue}var h=p.key,m=p.index;!h||m===void 0||m===null||d===void 0||d===null||typeof u!="string"||typeof d!="string"||typeof h!="string"||typeof m!="number"?Ve.warn("Malformed call encryption_key: userId=".concat(l,", deviceId=").concat(u,", encryptionKeyIndex=").concat(m," callId=").concat(d)):(Ve.debug("Embedded-E2EE-LOG onCallEncryption userId=".concat(l,":").concat(u," encryptionKeyIndex=").concat(m," age=").concat(f,"ms"),this.encryptionKeys),this.setEncryptionKey(l,u,m,h,a.getTs()))}}),v(this,"isMyMembership",a=>a.sender===this.client.getUserId()&&a.deviceId===this.client.getDeviceId()),v(this,"onMembershipUpdate",()=>{var a,l,c=this.memberships;this.memberships=nc.callMembershipsForRoom(this.room),this._callId=(a=this._callId)!==null&&a!==void 0?a:(l=this.memberships[0])===null||l===void 0?void 0:l.callId;var u=c.length!=this.memberships.length||c.some((S,R)=>!gu.equal(S,this.memberships[R]));if(u&&(Ve.info("Memberships for call in room ".concat(this.room.roomId," have changed: emitting")),this.emit(hl.MembershipsChanged,c,this.memberships),this.isJoined()&&!this.memberships.some(this.isMyMembership)&&(Ve.warn("Missing own membership: force re-join"),this.triggerCallMembershipEventUpdate())),this.manageMediaKeys&&this.isJoined()&&this.makeNewKeyTimeout===void 0){var d=new Set(c.filter(S=>!this.isMyMembership(S)).map(py)),f=new Set(this.memberships.filter(S=>!this.isMyMembership(S)).map(py)),p=Array.from(d).some(S=>!f.has(S)),h=Array.from(f).some(S=>!d.has(S)),m=this.lastMembershipFingerprints;if(this.storeLastMembershipFingerprints(),p)Ve.debug("Member(s) have left: queueing sender key rotation"),this.makeNewKeyTimeout=setTimeout(this.onRotateKeyTimeout,this.makeKeyDelay);else if(h)Ve.debug("New member(s) have joined: re-sending keys"),this.requestSendCurrentKey();else if(m){var E=this.lastMembershipFingerprints,y=Array.from(m).some(S=>!E.has(S))||Array.from(E).some(S=>!m.has(S));y&&(Ve.debug("Member(s) have updated/reconnected: re-sending keys to everyone"),this.requestSendCurrentKey())}}this.setExpiryTimer()}),v(this,"triggerCallMembershipEventUpdate",w(function*(){if(i.updateCallMembershipRunning){i.needCallMembershipUpdate=!0;return}i.updateCallMembershipRunning=!0;try{do i.needCallMembershipUpdate=!1,yield i.updateCallMembershipEvent();while(i.needCallMembershipUpdate)}finally{i.updateCallMembershipRunning=!1}})),v(this,"delayDisconnection",w(function*(){try{var a=i.disconnectDelayId;yield pl(()=>i.client._unstable_updateDelayedEvent(a,sp.Restart)),i.scheduleDelayDisconnection()}catch(l){Ve.error("Failed to delay our disconnection event:",l)}})),v(this,"onRotateKeyTimeout",()=>{if(this.manageMediaKeys){this.makeNewKeyTimeout=void 0,Ve.info("Making new sender key for key rotation");var a=this.makeNewSenderKey(!0);this.sendEncryptionKeysEvent(a)}}),this._callId=(o=n[0])===null||o===void 0?void 0:o.callId;var s=this.room.getLiveTimeline().getState(we.FORWARDS);s==null||s.on(Me.Members,this.onMembershipUpdate),this.setExpiryTimer()}isJoined(){return this.relativeExpiry!==void 0}stop(){var e=this;return w(function*(){yield e.leaveRoomSession(1e3),e.expiryTimeout&&(clearTimeout(e.expiryTimeout),e.expiryTimeout=void 0),e.memberEventTimeout&&(clearTimeout(e.memberEventTimeout),e.memberEventTimeout=void 0);var t=e.room.getLiveTimeline().getState(we.FORWARDS);t==null||t.off(Me.Members,e.onMembershipUpdate)})()}joinRoomSession(e,t,n){var i,o;if(this.isJoined()){Ve.info("Already joined to session in room ".concat(this.room.roomId,": ignoring join call"));return}this.ownFocusActive=t,this.ownFociPreferred=e,this.joinConfig=n,this.relativeExpiry=this.membershipExpiryTimeout,this.manageMediaKeys=(i=n==null?void 0:n.manageMediaKeys)!==null&&i!==void 0?i:this.manageMediaKeys,this.useLegacyMemberEvents=(o=n==null?void 0:n.useLegacyMemberEvents)!==null&&o!==void 0?o:this.useLegacyMemberEvents,this.membershipId=Ei(5),Ve.info("Joining call session in room ".concat(this.room.roomId," with manageMediaKeys=").concat(this.manageMediaKeys)),n!=null&&n.manageMediaKeys&&(this.makeNewSenderKey(),this.requestSendCurrentKey()),this.triggerCallMembershipEventUpdate(),this.emit(hl.JoinStateChanged,!0)}leaveRoomSession(){var e=arguments,t=this;return w(function*(){var n=e.length>0&&e[0]!==void 0?e[0]:void 0;if(!t.isJoined())return Ve.info("Not joined to session in room ".concat(t.room.roomId,": ignoring leave call")),!1;var i=t.client.getUserId(),o=t.client.getDeviceId();if(!i)throw new Error("No userId");if(!o)throw new Error("No deviceId");t.encryptionKeys.set(ap(i,o),[]),t.makeNewKeyTimeout!==void 0&&(clearTimeout(t.makeNewKeyTimeout),t.makeNewKeyTimeout=void 0);for(var s of t.setNewKeyTimeouts)clearTimeout(s);if(t.setNewKeyTimeouts.clear(),Ve.info("Leaving call session in room ".concat(t.room.roomId)),t.joinConfig=void 0,t.relativeExpiry=void 0,t.ownFocusActive=void 0,t.manageMediaKeys=!1,t.membershipId=void 0,t.emit(hl.JoinStateChanged,!1),n){var a=yield Promise.race([t.triggerCallMembershipEventUpdate(),As(n,"timeout")]);return a!=="timeout"}else return yield t.triggerCallMembershipEventUpdate(),!0})()}getActiveFocus(){if(this.ownFocusActive&&zN(this.ownFocusActive)&&this.ownFocusActive.focus_selection==="oldest_membership"){var e=this.getOldestMembership();return e==null?void 0:e.getPreferredFoci()[0]}if(!this.ownFocusActive){var t=this.getOldestMembership();return t==null?void 0:t.getPreferredFoci()[0]}}reemitEncryptionKeys(){this.encryptionKeys.forEach((e,t)=>{e.forEach((n,i)=>{this.emit(hl.EncryptionKeyChanged,n.key,i,t)})})}getKeysForParticipant(e,t){return this.getKeysForParticipantInternal(e,t)}getKeysForParticipantInternal(e,t){var n;return(n=this.encryptionKeys.get(ap(e,t)))===null||n===void 0?void 0:n.map(i=>i.key)}getEncryptionKeys(){return Array.from(this.encryptionKeys.entries()).map(e=>{var[t,n]=e;return[t,n.map(i=>i.key)]}).values()}getNewEncryptionKeyIndex(){return this.currentEncryptionKeyIndex===-1?0:(this.currentEncryptionKeyIndex+1)%256}setEncryptionKey(e,t,n,i,o){var s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!1,a=Dr(i),l=ap(e,t);this.encryptionKeys.has(l)||this.encryptionKeys.set(l,[]);var c=this.encryptionKeys.get(l),u=c[n];if(u){if(u.timestamp>o){Ve.info("Ignoring new key at index ".concat(n," for ").concat(l," as it is older than existing known key"));return}if(_7(u.key,a)){u.timestamp=o;return}}if(c[n]={key:a,timestamp:o},s){var d=setTimeout(()=>{this.setNewKeyTimeouts.delete(d),Ve.info("Delayed-emitting key changed event for ".concat(l," idx ").concat(n)),e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=n),this.emit(hl.EncryptionKeyChanged,a,n,l)},this.useKeyDelay);this.setNewKeyTimeouts.add(d)}else e===this.client.getUserId()&&t===this.client.getDeviceId()&&(this.currentEncryptionKeyIndex=n),this.emit(hl.EncryptionKeyChanged,a,n,l)}makeNewSenderKey(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.client.getUserId(),n=this.client.getDeviceId();if(!t)throw new Error("No userId");if(!n)throw new Error("No deviceId");var i=Wz(16),o=this.getNewEncryptionKeyIndex();return Ve.info("Generated new key at index "+o),this.setEncryptionKey(t,n,o,i,Date.now(),e),o}requestSendCurrentKey(){if(this.manageMediaKeys){if(this.lastEncryptionKeyUpdateRequest&&this.lastEncryptionKeyUpdateRequest+this.updateEncryptionKeyThrottle>Date.now()){Ve.info("Last encryption key event sent too recently: postponing"),this.keysEventUpdateTimeout===void 0&&(this.keysEventUpdateTimeout=setTimeout(this.sendEncryptionKeysEvent,this.updateEncryptionKeyThrottle));return}this.sendEncryptionKeysEvent()}}setExpiryTimer(){this.expiryTimeout&&(clearTimeout(this.expiryTimeout),this.expiryTimeout=void 0);var e;for(var t of this.memberships){var n=t.getMsUntilExpiry();n!==void 0&&(e===void 0||n<e)&&(e=n)}e!=null&&(this.expiryTimeout=setTimeout(this.onMembershipUpdate,e))}getOldestMembership(){return this.memberships[0]}getFocusInUse(){var e=this.getOldestMembership();if((e==null?void 0:e.getFocusSelection())==="oldest_membership")return e.getPreferredFoci()[0]}storeLastMembershipFingerprints(){this.lastMembershipFingerprints=new Set(this.memberships.filter(e=>!this.isMyMembership(e)).map(e=>"".concat(py(e),":").concat(e.membershipID,":").concat(e.createdTs())))}makeMyMembershipLegacy(e,t){if(this.relativeExpiry===void 0)throw new Error("Tried to create our own membership event when we're not joined!");if(this.membershipId===void 0)throw new Error("Tried to create our own membership event when we have no membership ID!");var n=t==null?void 0:t.createdTs();return b7({call_id:"",scope:"m.room",application:"m.call",device_id:e,expires:this.relativeExpiry,expires_ts:this.relativeExpiry+(n??Date.now()),foci_active:this.ownFociPreferred,membershipID:this.membershipId},n?{created_ts:n}:{})}makeMyMembership(e){var t;return{call_id:"",scope:"m.room",application:"m.call",device_id:e,focus_active:{type:"livekit",focus_selection:"oldest_membership"},foci_preferred:(t=this.ownFociPreferred)!==null&&t!==void 0?t:[]}}membershipEventNeedsUpdate(e,t){if(t&&t.getMsUntilExpiry()===void 0)return!1;if(!this.isJoined())return!!e;if(!t)return!0;var n=t.getMsUntilExpiry();return n!==void 0&&n<this.membershipExpiryTimeout/2?(this.relativeExpiry+=this.membershipExpiryTimeout,!0):!1}makeNewMembership(e){return this.isJoined()?this.makeMyMembership(e):{}}makeNewLegacyMemberships(e,t,n,i){var o=l=>{var c;try{c=new gu(n,l)}catch{return!1}return!c.isExpired()},s=l=>(l.created_ts===void 0&&(l.created_ts=n.getTs()),l),a=e.filter(o).filter(l=>l.device_id!==t);return a=a.map(s),this.isJoined()&&a.push(this.makeMyMembershipLegacy(t,i)),{memberships:a}}updateCallMembershipEvent(){var e=this;return w(function*(){e.memberEventTimeout&&(clearTimeout(e.memberEventTimeout),e.memberEventTimeout=void 0);var t=e.room.getLiveTimeline().getState(we.FORWARDS);if(!t)throw new Error("Couldn't get room state for room "+e.room.roomId);var n=e.client.getUserId(),i=e.client.getDeviceId();if(!n||!i)throw new Error("User ID or device ID was null!");var o=t.events.get(V.GroupCallMemberPrefix),s=e.stateEventsContainOngoingLegacySession(o),a={};if(s){var l,c=o==null?void 0:o.get(n),u=(l=c==null?void 0:c.getContent())!==null&&l!==void 0?l:{},d,f=Array.isArray(u.memberships)?u.memberships:[],p=f.find(k=>k.device_id===i);try{c&&p&&is(p)&&p.membershipID===e.membershipId&&(d=new gu(c,p))}catch(k){Ve.warn("Our previous call membership was invalid - this shouldn't happen.",k)}if(d&&Ve.debug("".concat(d.getMsUntilExpiry()," until our membership expires")),!e.membershipEventNeedsUpdate(p,d)){e.memberEventTimeout=setTimeout(e.triggerCallMembershipEventUpdate,e.memberEventCheckPeriod);return}a=e.makeNewLegacyMemberships(f,i,c,d)}else a=e.makeNewMembership(i);try{if(s)yield e.client.sendStateEvent(e.room.roomId,V.GroupCallMemberPrefix,a,n),e.isJoined()&&(e.memberEventTimeout=setTimeout(e.triggerCallMembershipEventUpdate,e.memberEventCheckPeriod));else if(e.isJoined()){var h=e.makeMembershipStateKey(n,i),m=function(){var k=w(function*(){try{var x=yield pl(()=>e.client._unstable_sendDelayedStateEvent(e.room.roomId,{delay:e.membershipServerSideExpiryTimeout},V.GroupCallMemberPrefix,{},h));e.disconnectDelayId=x.delay_id}catch(O){if(O instanceof hr&&O.errcode==="M_UNKNOWN"&&O.data["org.matrix.msc4140.errcode"]==="M_MAX_DELAY_EXCEEDED"){var T=O.data["org.matrix.msc4140.max_delay"];if(typeof T=="number"&&e.membershipServerSideExpiryTimeout>T)return e.membershipServerSideExpiryTimeoutOverride=T,m()}Ve.error("Failed to prepare delayed disconnection event:",O)}});return function(){return k.apply(this,arguments)}}();if(yield m(),yield pl(()=>e.client.sendStateEvent(e.room.roomId,V.GroupCallMemberPrefix,a,h)),e.disconnectDelayId!==void 0)try{var E=e.disconnectDelayId;yield pl(()=>e.client._unstable_updateDelayedEvent(E,sp.Restart))}catch(k){Ve.warn("Failed to update delayed disconnection event, prepare it again:",k),e.disconnectDelayId=void 0,yield m()}e.disconnectDelayId!==void 0&&e.scheduleDelayDisconnection()}else{var y=!1;if(e.disconnectDelayId!==void 0){try{var S=e.disconnectDelayId;yield pl(()=>e.client._unstable_updateDelayedEvent(S,sp.Send)),y=!0}catch(k){Ve.error("Failed to send our delayed disconnection event:",k)}e.disconnectDelayId=void 0}y||(yield pl(()=>e.client.sendStateEvent(e.room.roomId,V.GroupCallMemberPrefix,{},e.makeMembershipStateKey(n,i))))}Ve.info("Sent updated call member event.")}catch(k){var R=e.callMemberEventRetryDelayMinimum+Math.random()*e.callMemberEventRetryJitter;Ve.warn("Failed to send call member event (retrying in ".concat(R,"): ").concat(k)),yield As(R),yield e.triggerCallMembershipEventUpdate()}})()}scheduleDelayDisconnection(){this.memberEventTimeout=setTimeout(this.delayDisconnection,this.membershipKeepAlivePeriod)}stateEventsContainOngoingLegacySession(e){if(!(e!=null&&e.size))return this.useLegacyMemberEvents;var t=!1,n=!1;for(var i of e.values()){var o=i.getContent();if(Array.isArray(o.memberships)){for(var s of o.memberships)if(!new gu(i,s).isExpired())return!0}else Object.keys(o).length>0&&(t||(t=!0),n||(n=!("focus_active"in o)))}return t&&!n?!1:this.useLegacyMemberEvents}makeMembershipStateKey(e,t){var n="".concat(e,"_").concat(t);return/^org\.matrix\.msc(3757|3779)\b/.exec(this.room.getVersion())?n:"_".concat(n)}}function pl(r){return v_.apply(this,arguments)}function v_(){return v_=w(function*(r){for(var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;;)try{return yield r()}catch(o){if(e>0&&o instanceof _c&&o.isRateLimitError()){e--;var t=void 0,n=5e3;try{var i;t=(i=o.getRetryAfterMs())!==null&&i!==void 0?i:n,Ve.info("Rate limited by server, retrying in ".concat(t,"ms"))}catch(s){Ve.warn("Error while retrieving a rate-limit retry delay, retrying after default delay of ".concat(n),s),t=n}yield As(t)}else throw o}}),v_.apply(this,arguments)}var yu=b.getChild("MatrixRTCSessionManager"),Wk=function(r){return r.SessionStarted="session_started",r.SessionEnded="session_ended",r}({});class E7 extends Tt{constructor(e){super(),this.client=e,v(this,"roomSessions",new Map),v(this,"onTimeline",t=>{this.consumeCallEncryptionEvent(t)}),v(this,"onRoom",t=>{this.refreshRoom(t)}),v(this,"onRoomState",(t,n)=>{var i=this.client.getRoom(t.getRoomId());if(!i){yu.error("Got room state event for unknown room ".concat(t.getRoomId(),"!"));return}t.getType()==V.GroupCallMemberPrefix&&this.refreshRoom(i)})}start(){for(var e of(t=this.client.getRooms())!==null&&t!==void 0?t:[]){var t,n=nc.roomSessionForRoom(this.client,e);n.memberships.length>0&&this.roomSessions.set(e.roomId,n)}this.client.on(be.Room,this.onRoom),this.client.on(pe.Timeline,this.onTimeline),this.client.on(Me.Events,this.onRoomState)}stop(){for(var e of this.roomSessions.values())e.stop();this.roomSessions.clear(),this.client.off(be.Room,this.onRoom),this.client.off(pe.Timeline,this.onTimeline),this.client.off(Me.Events,this.onRoomState)}getActiveRoomSession(e){return this.roomSessions.get(e.roomId)}getRoomSession(e){return this.roomSessions.has(e.roomId)||this.roomSessions.set(e.roomId,nc.roomSessionForRoom(this.client,e)),this.roomSessions.get(e.roomId)}consumeCallEncryptionEvent(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;if(yield n.client.decryptEventIfNeeded(e),e.isDecryptionFailure()){i?yu.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason)):(yu.warn("Decryption failed for event ".concat(e.getId(),": ").concat(e.decryptionFailureReason," will retry once only")),setTimeout(()=>n.consumeCallEncryptionEvent(e,!0),1e3));return}else i&&yu.info("Decryption succeeded for event ".concat(e.getId()," after retry"));if(e.getType()!==V.CallEncryptionKeysPrefix)return Promise.resolve();var o=n.client.getRoom(e.getRoomId());if(!o)return yu.error("Got room state event for unknown room ".concat(e.getRoomId(),"!")),Promise.resolve();n.getRoomSession(o).onCallEncryption(e)})()}refreshRoom(e){var t=!this.roomSessions.has(e.roomId),n=this.getRoomSession(e),i=n.memberships.length>0&&!t;n.onMembershipUpdate();var o=n.memberships.length>0;i&&!o?this.emit(Wk.SessionEnded,e.roomId,this.roomSessions.get(e.roomId)):!i&&o&&this.emit(Wk.SessionStarted,e.roomId,this.roomSessions.get(e.roomId))}}function vy(r){return e=>{var t,n;return((t=e.content)===null||t===void 0||(t=t["m.relates_to"])===null||t===void 0?void 0:t.event_id)!==r||((n=e.content)===null||n===void 0||(n=n["m.relates_to"])===null||n===void 0?void 0:n.rel_type)===vt.name}}function YN(r){return m_.apply(this,arguments)}function m_(){return m_=w(function*(r){if(!globalThis.crypto.subtle)throw new Error("Crypto.subtle is not available: insecure context?");var e=new TextEncoder().encode(r),t=yield globalThis.crypto.subtle.digest("SHA-256",e);return t}),m_.apply(this,arguments)}var w7=["server","limit","since"];function qk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Cr(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?qk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):qk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var T7=3e3,R7=$N(),Gk=10*60*1e3,C7=new Bt("last_seen_user_agent","org.matrix.msc3852.last_seen_user_agent"),Cc=function(r){return r.Chronological="chronological",r.Detached="detached",r}({}),k7=new hm("m.get_login_token","org.matrix.msc3882.get_login_token"),JN="uk.half-shot.msc2666",XN="uk.half-shot.msc2666.mutual_rooms",QN="uk.half-shot.msc2666.query_mutual_rooms",Wi="org.matrix.msc4140",ZN="uk.tcpip.msc4133",Di="$",be=function(r){return r.Sync="sync",r.Event="event",r.ToDeviceEvent="toDeviceEvent",r.AccountData="accountData",r.Room="Room",r.DeleteRoom="deleteRoom",r.SyncUnexpectedError="sync.unexpectedError",r.ClientWellKnown="WellKnown.client",r.ReceivedVoipEvent="received_voip_event",r.UndecryptableToDeviceEvent="toDeviceEvent.undecryptable",r.TurnServers="turnServers",r.TurnServersError="turnServers.error",r}({}),I7=new Bt("action","org.matrix.msc3824.action");class qc extends Tt{constructor(e){var t,n,i,o;super(),i=this,v(this,"logger",void 0),v(this,"reEmitter",new Vc(this)),v(this,"olmVersion",null),v(this,"usingExternalCrypto",!1),v(this,"_store",void 0),v(this,"deviceId",void 0),v(this,"credentials",void 0),v(this,"pickleKey",void 0),v(this,"scheduler",void 0),v(this,"clientRunning",!1),v(this,"timelineSupport",!1),v(this,"urlPreviewCache",{}),v(this,"identityServer",void 0),v(this,"http",void 0),v(this,"crypto",void 0),v(this,"cryptoBackend",void 0),v(this,"cryptoCallbacks",void 0),v(this,"callEventHandler",void 0),v(this,"groupCallEventHandler",void 0),v(this,"supportsCallTransfer",!1),v(this,"forceTURN",!1),v(this,"iceCandidatePoolSize",0),v(this,"idBaseUrl",void 0),v(this,"baseUrl",void 0),v(this,"isVoipWithNoMediaAllowed",void 0),v(this,"useLivekitForGroupCalls",void 0),v(this,"canSupportVoip",!1),v(this,"peekSync",null),v(this,"isGuestAccount",!1),v(this,"ongoingScrollbacks",{}),v(this,"notifTimelineSet",null),v(this,"cryptoStore",void 0),v(this,"verificationMethods",void 0),v(this,"fallbackICEServerAllowed",!1),v(this,"syncApi",void 0),v(this,"roomNameGenerator",void 0),v(this,"pushRules",void 0),v(this,"syncLeftRoomsPromise",void 0),v(this,"syncedLeftRooms",!1),v(this,"clientOpts",void 0),v(this,"clientWellKnownIntervalID",void 0),v(this,"canResetTimelineCallback",void 0),v(this,"canSupport",new Map),v(this,"pushProcessor",new hi(this)),v(this,"serverVersionsPromise",void 0),v(this,"clientWellKnown",void 0),v(this,"clientWellKnownPromise",void 0),v(this,"turnServers",[]),v(this,"turnServersExpiry",0),v(this,"checkTurnServersIntervalID",void 0),v(this,"exportedOlmDeviceToImport",void 0),v(this,"txnCtr",0),v(this,"mediaHandler",new l7(this)),v(this,"sessionId",void 0),v(this,"eventsBeingEncrypted",new Set),v(this,"useE2eForGroupCall",!0),v(this,"toDeviceMessageQueue",void 0),v(this,"livekitServiceURL",void 0),v(this,"_secretStorage",void 0),v(this,"ignoredInvites",void 0),v(this,"matrixRTC",void 0),v(this,"serverCapabilitiesService",void 0),v(this,"startCallEventHandler",()=>{this.isInitialSyncComplete()&&(qb()&&(this.callEventHandler.start(),this.groupCallEventHandler.start()),this.off(be.Sync,this.startCallEventHandler))}),v(this,"startMatrixRTC",()=>{this.isInitialSyncComplete()&&(this.matrixRTC.start(),this.off(be.Sync,this.startMatrixRTC))}),v(this,"fixupRoomNotifications",()=>{if(this.isInitialSyncComplete()){var a,l=((a=this.getRooms())!==null&&a!==void 0?a:[]).filter(d=>d.getUnreadNotificationCount(it.Total)>0);for(var c of l){var u=this.getSafeUserId();c.fixupNotifications(u)}this.off(be.Sync,this.fixupRoomNotifications)}}),this.logger=(t=e.logger)!==null&&t!==void 0?t:b,e.baseUrl=ey(e.baseUrl),e.idBaseUrl=ey(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=(n=e.usingExternalCrypto)!==null&&n!==void 0?n:!1,this.store=e.store||new xz,this.deviceId=e.deviceId||null,this.sessionId=Ei(10);var s=e.userId||null;this.credentials={userId:s},this.http=new cN(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenRefreshFunction:e.tokenRefreshFunction,prefix:Pt.V3,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader,logger:this.logger}),e.deviceToImport?this.deviceId?this.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?this.logger.warn("not importing device because user ID is provided to constructor independently of exported data"):e.deviceToImport.deviceId?(this.deviceId=e.deviceToImport.deviceId,this.credentials.userId=e.deviceToImport.userId,this.exportedOlmDeviceToImport=e.deviceToImport.olmDevice):this.logger.warn("not importing device because no device ID in exported data"):e.pickleKey&&(this.pickleKey=e.pickleKey),this.useLivekitForGroupCalls=!!e.useLivekitForGroupCalls,this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction(function(){var a=w(function*(l){var c=i.getRoom(l.getRoomId());l.status!==je.SENDING&&i.updatePendingEventStatus(c,l,je.SENDING);var u=yield i.sendEventHttpRequest(l);return c&&c.updatePendingEvent(l,je.SENT,u.event_id),u});return function(l){return a.apply(this,arguments)}}()),qb()&&(this.callEventHandler=new Xz(this),this.groupCallEventHandler=new Qz(this),this.canSupportVoip=!0,this.on(be.Sync,this.startCallEventHandler)),this.matrixRTC=new E7(this),this.serverCapabilitiesService=new dN(this.http),this.on(be.Sync,this.fixupRoomNotifications),this.timelineSupport=!!e.timelineSupport,this.cryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=e.iceCandidatePoolSize===void 0?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,e.useE2eForGroupCall!==void 0&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.livekitServiceURL=e.livekitServiceURL,this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new m7(this),this.on(ot.Decrypted,a=>{eL(this,a)}),this.ignoredInvites=new g7(this),this._secretStorage=new Vd(this,(o=e.cryptoCallbacks)!==null&&o!==void 0?o:{}),this.setMaxListeners(0)}set store(e){this._store=e,this._store.setUserCreator(t=>ko.createUser(t,this))}get store(){return this._store}startClient(e){var t=this;return w(function*(){if(!t.clientRunning){t.clientRunning=!0,t.on(be.Sync,t.startMatrixRTC);var n=t.getUserId();n&&t.store.storeUser(new ko(n)),t.canSupportVoip&&(t.checkTurnServersIntervalID=setInterval(()=>{t.checkTurnServers()},Gk),t.checkTurnServers()),t.syncApi&&(t.logger.error("Still have sync object whilst not running: stopping old one"),t.syncApi.stop());try{yield t.getVersions();var{threads:i,list:o,fwdPagination:s}=yield t.doesServerSupportThread();Et.setServerSideSupport(i),Et.setServerSideListSupport(o),Et.setServerSideFwdPaginationSupport(s)}catch(a){t.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",a)}t.clientOpts=e??{},t.clientOpts.slidingSync?t.syncApi=new GN(t.clientOpts.slidingSync,t,t.clientOpts,t.buildSyncApiOptions()):t.syncApi=new Au(t,t.clientOpts,t.buildSyncApiOptions()),t.syncApi.sync().catch(a=>t.logger.info("Sync startup aborted with an error:",a)),t.clientOpts.clientWellKnownPollPeriod!==void 0&&(t.clientWellKnownIntervalID=setInterval(()=>{t.fetchClientWellKnown()},1e3*t.clientOpts.clientWellKnownPollPeriod),t.fetchClientWellKnown()),t.toDeviceMessageQueue.start(),t.serverCapabilitiesService.start()}})()}buildSyncApiOptions(){return{crypto:this.crypto,cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>this.canResetTimelineCallback?this.canResetTimelineCallback(e):!1}}stopClient(){var e,t,n,i,o;(e=this.cryptoBackend)===null||e===void 0||e.stop(),this.off(be.Sync,this.startMatrixRTC),this.clientRunning&&(this.logger.debug("stopping MatrixClient"),this.clientRunning=!1,(t=this.syncApi)===null||t===void 0||t.stop(),this.syncApi=void 0,(n=this.peekSync)===null||n===void 0||n.stopPeeking(),(i=this.callEventHandler)===null||i===void 0||i.stop(),(o=this.groupCallEventHandler)===null||o===void 0||o.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())}rehydrateDevice(){var e=this;return w(function*(){if(e.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(e.cryptoCallbacks.getDehydrationKey){var t=yield e.getDehydratedDevice();if(t){if(!t.device_data||!t.device_id){e.logger.info("no dehydrated device found");return}var n=new globalThis.Olm.Account;try{var i=t.device_data;if(i.algorithm!==ip){e.logger.warn("Wrong algorithm for dehydrated device");return}e.logger.debug("unpickling dehydrated device");var o=yield e.cryptoCallbacks.getDehydrationKey(i,l=>{n.unpickle(new Uint8Array(l),i.account)});n.unpickle(o,i.account),e.logger.debug("unpickled device");var s=yield e.http.authedRequest(Z.Post,"/dehydrated_device/claim",void 0,{device_id:t.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"});if(s.success){e.deviceId=t.device_id,e.logger.info("using dehydrated device");var a=e.pickleKey||"DEFAULT_KEY";return e.exportedOlmDeviceToImport={pickledAccount:n.pickle(a),sessions:[],pickleKey:a},n.free(),e.deviceId}else{n.free(),e.logger.info("not using dehydrated device");return}}catch(l){n.free(),e.logger.warn("could not unpickle",l)}}}})()}getDehydratedDevice(){var e=this;return w(function*(){try{return yield e.http.authedRequest(Z.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(t){e.logger.info("could not get dehydrated device",t);return}})()}setDehydrationKey(e,t,n){var i=this;return w(function*(){if(!i.crypto){i.logger.warn("not dehydrating device if crypto is not enabled");return}return i.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,n)})()}createDehydratedDevice(e,t,n){var i=this;return w(function*(){if(!i.crypto){i.logger.warn("not dehydrating device if crypto is not enabled");return}return yield i.crypto.dehydrationManager.setKey(e,t,n),i.crypto.dehydrationManager.dehydrateDevice()})()}exportDevice(){var e=this;return w(function*(){if(!e.crypto){e.logger.warn("not exporting device if crypto is not enabled");return}return{userId:e.credentials.userId,deviceId:e.deviceId,olmDevice:yield e.crypto.olmDevice.export()}})()}clearStores(){var e=this;if(this.clientRunning)throw new Error("Cannot clear stores while client is running");var t=[];t.push(this.store.deleteAllData()),this.cryptoStore&&t.push(this.cryptoStore.deleteAllData());var n=function(){var i=w(function*(){var o;try{if(o=globalThis.indexedDB,!o)return}catch{return}var s=function*(c){var u=new Promise((d,f)=>{e.logger.info("Removing IndexedDB instance ".concat(c));var p=o.deleteDatabase(c);p.onsuccess=h=>{e.logger.info("Removed IndexedDB instance ".concat(c)),d(0)},p.onerror=h=>{e.logger.warn("Failed to remove IndexedDB instance ".concat(c,":"),h),d(0)},p.onblocked=h=>{e.logger.info("cannot yet remove IndexedDB instance ".concat(c))}});yield u};for(var a of["".concat(hy,"::matrix-sdk-crypto"),"".concat(hy,"::matrix-sdk-crypto-meta")])yield*s(a)});return function(){return i.apply(this,arguments)}}();return t.push(n()),Promise.all(t).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getSafeUserId(){var e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):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 Kd(this,e)}createGroupCall(e,t,n,i,o,s){var a=this;return w(function*(){if(a.getGroupCallForRoom(e))throw new Error("".concat(e," already has an existing group call"));var l=a.getRoom(e);if(!l)throw new Error("Cannot find room ".concat(e));return new Lw(a,l,t,n,i,void 0,o||a.isVoipWithNoMediaAllowed,s,a.isVoipWithNoMediaAllowed,a.useLivekitForGroupCalls,a.livekitServiceURL).create()})()}getLivekitServiceURL(){return this.livekitServiceURL}setLivekitServiceURL(e){this.livekitServiceURL=e}waitUntilRoomReadyForGroupCalls(e){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(e)}getGroupCallForRoom(e){return this.groupCallEventHandler.groupCalls.get(e)||null}getSyncState(){var e,t;return(e=(t=this.syncApi)===null||t===void 0?void 0:t.getSyncState())!==null&&e!==void 0?e:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){var e=this.getSyncState();return e?e===ct.Prepared||e===ct.Syncing:!1}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),(e=(t=this.syncApi)===null||t===void 0?void 0:t.retryImmediately())!==null&&e!==void 0?e:!1}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(){var e=this;return w(function*(){var t=e.serverCapabilitiesService.getCachedCapabilities();return t||e.serverCapabilitiesService.fetchCapabilities()})()}getCachedCapabilities(){return this.serverCapabilitiesService.getCachedCapabilities()}fetchCapabilities(){return this.serverCapabilitiesService.fetchCapabilities()}initCrypto(){var e=this;return w(function*(){if(!$N())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(e.cryptoBackend){e.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}if(!e.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");e.logger.debug("Crypto: Starting up crypto store..."),yield e.cryptoStore.startup();var t=e.getUserId();if(t===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(e.deviceId===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");var n=new mv(e,t,e.deviceId,e.store,e.cryptoStore,e.verificationMethods);e.reEmitter.reEmit(n,[et.KeyBackupFailed,et.KeyBackupSessionsRemaining,et.RoomKeyRequest,et.RoomKeyRequestCancellation,et.Warning,et.DevicesUpdated,et.WillUpdateDevices,et.DeviceVerificationChanged,et.UserTrustStatusChanged,et.KeysChanged]),e.logger.debug("Crypto: initialising crypto object..."),yield n.init({exportedOlmDevice:e.exportedOlmDeviceToImport,pickleKey:e.pickleKey}),delete e.exportedOlmDeviceToImport,e.olmVersion=mv.getOlmVersion(),n.registerEventHandlers(e),e.cryptoBackend=e.crypto=n,e.crypto.uploadDeviceKeys().catch(i=>{e.logger.error("Error uploading device keys",i)})})()}initRustCrypto(){var e=arguments,t=this;return w(function*(){var n,i=e.length>0&&e[0]!==void 0?e[0]:{};if(t.cryptoBackend){t.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");return}var o=t.getUserId();if(o===null)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");var s=t.getDeviceId();if(s===null)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");t.logger.debug("Downloading Rust crypto library");var a=yield FD(()=>import("./index-Dc8BJYf_.js"),[]),l=yield a.initRustCrypto({logger:t.logger,http:t.http,userId:o,deviceId:s,secretStorage:t.secretStorage,cryptoCallbacks:t.cryptoCallbacks,storePrefix:i.useIndexedDB===!1?null:hy,storeKey:i.storageKey,storePassphrase:i.storagePassword,legacyCryptoStore:t.cryptoStore,legacyPickleKey:(n=t.pickleKey)!==null&&n!==void 0?n:"DEFAULT_KEY",legacyMigrationProgressListener:(c,u)=>{t.emit(Yt.LegacyCryptoStoreMigrationProgress,c,u)}});l.setSupportedVerificationMethods(t.verificationMethods),t.cryptoBackend=l,t.on(Ar.Membership,l.onRoomMembership.bind(l)),t.on(be.Event,c=>{l.onLiveEventFromSync(c)}),t.reEmitter.reEmit(l,[Yt.VerificationRequestReceived,Yt.UserTrustStatusChanged,Yt.KeyBackupStatus,Yt.KeyBackupSessionsRemaining,Yt.KeyBackupFailed,Yt.KeyBackupDecryptionKeyCached,Yt.KeysChanged,Yt.DevicesUpdated,Yt.WillUpdateDevices])})()}get secretStorage(){return this._secretStorage}getCrypto(){return this.cryptoBackend}isCryptoEnabled(){return!!this.cryptoBackend}getDeviceEd25519Key(){var e,t;return(e=(t=this.crypto)===null||t===void 0?void 0:t.getDeviceEd25519Key())!==null&&e!==void 0?e:null}getDeviceCurve25519Key(){var e,t;return(e=(t=this.crypto)===null||t===void 0?void 0:t.getDeviceCurve25519Key())!==null&&e!==void 0?e:null}uploadKeys(){var e=this;return w(function*(){e.logger.warn("MatrixClient.uploadKeys is deprecated")})()}downloadKeys(e,t){return this.crypto?this.crypto.downloadKeys(e,t):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(e)||[]}getStoredDevice(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(e,t)||null}setDeviceVerified(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=this.setDeviceVerification(e,t,n,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),i}setDeviceBlocked(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return this.setDeviceVerification(e,t,null,n,null)}setDeviceKnown(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return this.setDeviceVerification(e,t,null,null,n)}setDeviceVerification(e,t,n,i,o){var s=this;return w(function*(){if(!s.crypto)throw new Error("End-to-end encryption disabled");yield s.crypto.setDeviceVerification(e,t,n,i,o)})()}requestVerificationDM(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerificationDM(e,t)}findVerificationRequestDMInProgress(e){if(this.cryptoBackend){if(!this.crypto)return}else throw new Error("End-to-end encryption disabled");return this.crypto.findVerificationRequestDMInProgress(e)}getVerificationRequestsToDeviceInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getVerificationRequestsToDeviceInProgress(e)}requestVerification(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerification(e,t)}beginKeyVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(e,t,n)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}setGlobalBlacklistUnverifiedDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices=e,e}getGlobalBlacklistUnverifiedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices}setGlobalErrorOnUnknownDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.globalErrorOnUnknownDevices=e}getGlobalErrorOnUnknownDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalErrorOnUnknownDevices}getCrossSigningId(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:qw.Master;if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(e)}getStoredCrossSigningForUser(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getStoredCrossSigningForUser(e)}checkUserTrust(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkDeviceTrust(e,t)}checkIfOwnDeviceCrossSigned(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkIfOwnDeviceCrossSigned(e)}checkOwnCrossSigningTrust(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkOwnCrossSigningTrust(e)}checkCrossSigningPrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(e,t)}legacyDeviceVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,n)}prepareToEncrypt(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.prepareToEncrypt(e)}userHasCrossSigningKeys(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.userHasCrossSigningKeys()}isCrossSigningReady(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.isCrossSigningReady()}bootstrapCrossSigning(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.bootstrapCrossSigning(e)}getCryptoTrustCrossSignedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.setTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getEventEncryptionInfo(e)}createRecoveryKeyFromPassphrase(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.createRecoveryKeyFromPassphrase(e)}isSecretStorageReady(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.isSecretStorageReady()}bootstrapSecretStorage(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.bootstrapSecretStorage(e)}addSecretStorageKey(e,t,n){return this.secretStorage.addKey(e,t,n)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}storeSecret(e,t,n){return this.secretStorage.store(e,t,n)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStoragePrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(e,t)}getEventSenderDeviceInfo(e){var t=this;return w(function*(){return t.crypto?t.crypto.getEventSenderDeviceInfo(e):null})()}isEventSenderVerified(e){var t=this;return w(function*(){var n=yield t.getEventSenderDeviceInfo(e);return n?n.isVerified():!1})()}getOutgoingRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");var t=e.getWireContent(),n={session_id:t.session_id,sender_key:t.sender_key,algorithm:t.algorithm,room_id:e.getRoomId()};return!n.session_id||!n.sender_key||!n.algorithm||!n.room_id?Promise.resolve(null):this.crypto.cryptoStore.getOutgoingRoomKeyRequest(n)}cancelAndResendEventRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");return e.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(e,t)}isRoomEncrypted(e){var t,n,i=this.getRoom(e);return i?i.hasEncryptionStateEvent()?!0:(t=(n=this.crypto)===null||n===void 0?void 0:n.isRoomEncrypted(e))!==null&&t!==void 0?t:!1:!1}encryptAndSendToDevices(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.encryptAndSendToDevices(e,t)}forceDiscardSession(e){if(!this.cryptoBackend)throw new Error("End-to-End encryption disabled");this.cryptoBackend.forceDiscardSession(e)}exportRoomKeys(){return this.cryptoBackend?this.cryptoBackend.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(e,t){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.importRoomKeys(e,t)}checkKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.checkKeyBackup()}getKeyBackupVersion(){var e=this;return w(function*(){var t;try{t=yield e.http.authedRequest(Z.Get,"/room_keys/version",void 0,void 0,{prefix:Pt.V3})}catch(n){if(n.errcode==="M_NOT_FOUND")return null;throw n}return xa.checkBackupVersion(t),t})()}isKeyBackupTrusted(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.isKeyBackupTrusted(e)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(e)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}prepareKeyBackupVersion(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{secureSecretStorage:!1};if(!n.crypto)throw new Error("End-to-end encryption disabled");var{algorithm:o,auth_data:s,recovery_key:a,privateKey:l}=yield n.crypto.backupManager.prepareKeyBackupVersion(e);return i.secureSecretStorage&&(yield n.secretStorage.store("m.megolm_backup.v1",Zr(l)),n.logger.info("Key backup private key stored in secret storage")),{algorithm:o,auth_data:s,recovery_key:a}})()}isKeyBackupKeyStored(){return Promise.resolve(this.secretStorage.isStored("m.megolm_backup.v1"))}createKeyBackupVersion(e){var t=this;return w(function*(){if(!t.crypto)throw new Error("End-to-end encryption disabled");yield t.crypto.backupManager.createKeyBackupVersion(e);var n={algorithm:e.algorithm,auth_data:e.auth_data};yield t.crypto.signObject(n.auth_data),t.cryptoCallbacks.getCrossSigningKey&&t.crypto.crossSigningInfo.getId()&&(yield t.crypto.crossSigningInfo.signObject(n.auth_data,"master"));var i=yield t.http.authedRequest(Z.Post,"/room_keys/version",void 0,n);return yield t.checkKeyBackup(),t.getKeyBackupEnabled()||t.logger.error("Key backup not usable even though we just created it"),i})()}deleteKeyBackupVersion(e){var t=this;return w(function*(){if(!t.cryptoBackend)throw new Error("End-to-end encryption disabled");yield t.cryptoBackend.deleteKeyBackupVersion(e)})()}makeKeyBackupPath(e,t,n){var i;t!==void 0?i=Se("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):e!==void 0?i=Se("/room_keys/keys/$roomId",{$roomId:e}):i="/room_keys/keys";var o=n===void 0?void 0:{version:n};return{path:i,queryData:o}}sendKeyBackup(e,t,n,i){var o=this;return w(function*(){if(!o.crypto)throw new Error("End-to-end encryption disabled");var s=o.makeKeyBackupPath(e,t,n);yield o.http.authedRequest(Z.Put,s.path,s.queryData,i,{prefix:Pt.V3})})()}scheduleAllGroupSessionsForBackup(){var e=this;return w(function*(){if(!e.crypto)throw new Error("End-to-end encryption disabled");yield e.crypto.backupManager.scheduleAllGroupSessionsForBackup()})()}flagAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.flagAllGroupSessionsForBackup()}isValidRecoveryKey(e){try{return od(e),!0}catch{return!1}}keyBackupKeyFromPassword(e,t){return Tk(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return od(e)}restoreKeyBackupWithPassword(e,t,n,i,o){var s=this;return w(function*(){var a=yield Tk(i.auth_data,e);return s.restoreKeyBackup(a,t,n,i,o)})()}restoreKeyBackupWithSecretStorage(e,t,n,i){var o=this;return w(function*(){if(!o.cryptoBackend)throw new Error("End-to-end encryption disabled");var s=yield o.secretStorage.get("m.megolm_backup.v1"),a=op(s);if(a){var l=yield o.secretStorage.getKey();yield o.secretStorage.store("m.megolm_backup.v1",a,[l[0]])}var c=Dr(a||s);return o.restoreKeyBackup(c,t,n,e,i)})()}restoreKeyBackupWithRecoveryKey(e,t,n,i,o){var s=od(e);return this.restoreKeyBackup(s,t,n,i,o)}restoreKeyBackupWithCache(e,t,n,i){var o=this;return w(function*(){if(!o.cryptoBackend)throw new Error("End-to-end encryption disabled");var s=yield o.cryptoBackend.getSessionBackupPrivateKey();if(!s)throw new Error("Couldn't get key");return o.restoreKeyBackup(s,e,t,n,i)})()}restoreKeyBackup(e,t,n,i,o){var s=this;return w(function*(){var a=o==null?void 0:o.cacheCompleteCallback,l=o==null?void 0:o.progressCallback;if(!s.cryptoBackend)throw new Error("End-to-end encryption disabled");if(!i.version)throw new Error("Backup version must be defined");var c=i.version,u=0,d=0,f=0,p=s.makeKeyBackupPath(t,n,c),h=yield s.cryptoBackend.getBackupDecryptor(i,e),m=!h.sourceTrusted;try{if(!(e instanceof Uint8Array))throw new Error("restoreKeyBackup expects Uint8Array, got ".concat(e));s.cryptoBackend.storeSessionBackupPrivateKey(e,c).catch(x=>{s.logger.warn("Error caching session backup key:",x)}).then(a),l&&l({stage:"fetch"});var E=yield s.http.authedRequest(Z.Get,p.path,p.queryData,void 0,{prefix:Pt.V3});if(l&&l({stage:"load_keys"}),E.rooms)u=s.getTotalKeyCount(E),yield s.handleDecryptionOfAFullBackup(E,h,200,function(){var x=w(function*(T){try{var O=i.version;yield s.cryptoBackend.importBackedUpRoomKeys(T,O,{untrusted:m}),f+=T.length}catch(C){d+=T.length,b.error("Error importing keys from backup",C)}l&&l({total:u,successes:f,stage:"load_keys",failures:d})});return function(T){return x.apply(this,arguments)}}());else if(E.sessions){var y=E.sessions;u=Object.keys(y).length;var S=yield h.decryptSessions(y);for(var R of S)R.room_id=t;yield s.cryptoBackend.importBackedUpRoomKeys(S,c,{progressCallback:l,untrusted:m}),f=S.length}else{u=1;try{var[k]=yield h.decryptSessions({[n]:E});k.room_id=t,k.session_id=n,yield s.cryptoBackend.importBackedUpRoomKeys([k],c,{progressCallback:l,untrusted:m}),f=1}catch(x){s.logger.debug("Failed to decrypt megolm session from backup",x)}}}finally{h.free()}return yield s.cryptoBackend.checkKeyBackupAndEnable(),{total:u,imported:f}})()}getTotalKeyCount(e){var t=e.rooms,n=0;for(var i of Object.values(t))i.sessions&&(n+=Object.keys(i.sessions).length);return n}handleDecryptionOfAFullBackup(e,t,n,i){return w(function*(){var o=e.rooms,s=0,a=new Map,l=function(){var h=w(function*(m){var E=[];for(var y of m.keys()){var S=yield t.decryptSessions(m.get(y));for(var R in S){var k=S[R];k.room_id=y,E.push(k)}}yield i(E)});return function(E){return h.apply(this,arguments)}}();for(var[c,u]of Object.entries(o))if(u.sessions){a.set(c,{});for(var[d,f]of Object.entries(u.sessions)){var p=a.get(c);p[d]=f,s+=1,s>=n&&(yield l(a),a=new Map,a.set(c,{}),s=0)}}s>0&&(yield l(a))})()}deleteKeysFromBackup(e,t,n){var i=this;return w(function*(){var o=i.makeKeyBackupPath(e,t,n);yield i.http.authedRequest(Z.Delete,o.path,o.queryData,void 0,{prefix:Pt.V3})})()}getMediaConfig(){return this.http.authedRequest(Z.Get,"/config",void 0,void 0,{prefix:Zl.V3})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=this.store.getRooms(),n=new Set;for(var i of t){var o,s=(o=i.findPredecessor(e))===null||o===void 0?void 0:o.roomId;s&&n.add(s)}return t.filter(a=>{var l=a.currentState.getStateEvents(V.RoomTombstone,"");return!(l&&n.has(a.roomId))})}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t){var n=Se("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return aN(5,()=>this.http.authedRequest(Z.Put,n,void 0,t))}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var t=this;return w(function*(){if(t.isInitialSyncComplete()){var n=t.store.getAccountData(e);return n?n.getContent():null}var i=Se("/user/$userId/account_data/$type",{$userId:t.credentials.userId,$type:e});try{return yield t.http.authedRequest(Z.Get,i)}catch(s){var o;if(((o=s.data)===null||o===void 0?void 0:o.errcode)==="M_NOT_FOUND")return null;throw s}})()}deleteAccountData(e){var t=this;return w(function*(){var n=t.canSupport.get(dr.AccountDataDeletion);if(n===lr.Unsupported){yield t.setAccountData(e,{});return}var i=Se("/user/$userId/account_data/$type",{$userId:t.getSafeUserId(),$type:e}),o=n===lr.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield t.http.authedRequest(Z.Delete,i,void 0,void 0,o)})()}getIgnoredUsers(){var e=this.getAccountData("m.ignored_user_list");return!e||!e.getContent()||!e.getContent().ignored_users?[]:Object.keys(e.getContent().ignored_users)}setIgnoredUsers(e){var t={ignored_users:{}};return e.forEach(n=>{t.ignored_users[n]={}}),this.setAccountData("m.ignored_user_list",t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};i.syncRoom===void 0&&(i.syncRoom=!0);var o=n.getRoom(e);if(o!=null&&o.hasMembershipState(n.credentials.userId,Be.Join))return o;var s=Promise.resolve();if(i.inviteSignUrl){var a=new URL(i.inviteSignUrl);a.searchParams.set("mxid",n.credentials.userId),s=n.http.requestOtherUrl(Z.Post,a)}var l={};i.viaServers&&(l.server_name=i.viaServers,l.via=i.viaServers);var c={},u=yield s;u&&(c.third_party_signed=u);var d=Se("/join/$roomid",{$roomid:e}),f=yield n.http.authedRequest(Z.Post,d,l,c),p=f.room_id,h=n.getRoom(p);if(h!=null&&h.hasMembershipState(n.credentials.userId,Be.Join))return h;var m=new Au(n,n.clientOpts,n.buildSyncApiOptions()),E=m.createRoom(p);return i.syncRoom,E})()}knockRoom(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=this.getRoom(e);if(n!=null&&n.hasMembershipState(this.credentials.userId,Be.Knock))return Promise.resolve({room_id:n.roomId});var i=Se("/knock/$roomIdOrAlias",{$roomIdOrAlias:e}),o={};t.viaServers&&(o.server_name=t.viaServers,o.via=t.viaServers);var s={};return t.reason&&(s.reason=t.reason),this.http.authedRequest(Z.Post,i,o,s)}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,je.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![je.QUEUED,je.NOT_SENT,je.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===je.ENCRYPTING?this.eventsBeingEncrypted.delete(e.getId()):this.scheduler&&e.status===je.QUEUED&&this.scheduler.removeEventFromQueue(e);var t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,je.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,V.RoomName,{name:t})}setRoomTopic(e,t,n){var i=XD(t,n);return this.sendStateEvent(e,V.RoomTopic,i)}getRoomTags(e){var t=Se("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(Z.Get,t)}setRoomTag(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=Se("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(Z.Put,i,void 0,n)}deleteRoomTag(e,t){var n=Se("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(Z.Delete,n)}setRoomAccountData(e,t,n){var i=Se("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(Z.Put,i,void 0,n)}setPowerLevel(e,t,n){var i=this;return w(function*(){var o,s;if(i.clientRunning&&i.isInitialSyncComplete()){var a;s=(a=i.getRoom(e))===null||a===void 0||(a=a.currentState)===null||a===void 0||(a=a.getStateEvents(V.RoomPowerLevels,""))===null||a===void 0?void 0:a.getContent()}if(!s)try{s=yield i.getStateEvent(e,V.RoomPowerLevels,"")}catch(u){if(u instanceof hr&&u.errcode==="M_NOT_FOUND")s={};else throw u}s=ym(s),(o=s)!==null&&o!==void 0&&o.users||(s.users={});var l=Array.isArray(t)?t:[t];for(var c of l)n==null?delete s.users[c]:s.users[c]=n;return i.sendStateEvent(e,V.RoomPowerLevels,s,"")})()}unstable_createLiveBeacon(e,t){var n=this;return w(function*(){return n.unstable_setLiveBeacon(e,t)})()}unstable_setLiveBeacon(e,t){var n=this;return w(function*(){return n.sendStateEvent(e,xw.name,t,n.getUserId())})()}sendEvent(e,t,n,i,o){var s,a,l,c;return!(t!=null&&t.startsWith(Di))&&t!==null?(c=i,l=n,a=t,s=null):(c=o,l=i,a=n,s=t),this.addThreadRelationIfNeeded(l,s,e),this.sendCompleteEvent(e,s,{type:a,content:l},c)}addThreadRelationIfNeeded(e,t,n){var i;if(t&&!((i=e["m.relates_to"])!==null&&i!==void 0&&i.rel_type)){var o,s,a=!!((o=e["m.relates_to"])!==null&&o!==void 0&&o["m.in_reply_to"]);e["m.relates_to"]=Cr(Cr({},e["m.relates_to"]),{},{rel_type:vt.name,event_id:t,is_falling_back:!a});var l=(s=this.getRoom(n))===null||s===void 0?void 0:s.getThread(t);if(l&&!a){var c,u;e["m.relates_to"]["m.in_reply_to"]={event_id:(c=(u=l.lastReply(d=>d.isRelation(vt.name)&&!d.status))===null||u===void 0?void 0:u.getId())!==null&&c!==void 0?c:t}}}}sendCompleteEvent(e,t,n,i,o){var s,a;typeof i=="string"?a=i:(s=i,a=o),a||(a=this.makeTxnId());var l=new pr(Object.assign(n,{event_id:"~"+e+":"+a,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:new Date().getTime()})),c=this.getRoom(e),u=t?c==null?void 0:c.getThread(t):void 0;u&&l.setThread(u),s||(this.reEmitter.reEmit(l,[ot.Replaced,ot.VisibilityChange]),c==null||c.reEmitter.reEmit(l,[ot.BeforeRedaction]));var d=l.getAssociatedId();if(d!=null&&d.startsWith("~")){var f=c==null?void 0:c.getPendingEvents().find(h=>h.getId()===d);f==null||f.once(ot.LocalEventIdReplaced,()=>{l.updateAssociatedId(f.getId())})}var p=l.getType();return this.logger.debug("sendEvent of type ".concat(p," in ").concat(e," with txnId ").concat(a).concat(s?" (delayed event)":"")),l.setTxnId(a),l.setStatus(je.SENDING),s?this.encryptAndSendEvent(c,l,s):(c==null||c.addPendingEvent(l,a),l.status===je.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(c,l))}encryptAndSendEvent(e,t,n){var i=this;return w(function*(){if(n)return i.sendEventHttpRequest(t,n);try{var o;i.eventsBeingEncrypted.add(t.getId());try{yield i.encryptEventIfNeeded(t,e??void 0)}finally{o=!i.eventsBeingEncrypted.delete(t.getId())}if(o)return{};t.status===je.ENCRYPTING&&i.updatePendingEventStatus(e,t,je.SENDING);var s=null;return i.scheduler&&(s=i.scheduler.queueEvent(t),s&&i.scheduler.getQueueForEvent(t).length>1&&i.updatePendingEventStatus(e,t,je.QUEUED)),s||(s=i.sendEventHttpRequest(t),e&&(s=s.then(a=>(e.updatePendingEvent(t,je.SENT,a.event_id),a)))),yield s}catch(a){i.logger.error("Error sending event",a);try{t.error=a,i.updatePendingEventStatus(e,t,je.NOT_SENT)}catch(l){i.logger.error("Exception in error handler!",l)}throw a instanceof hr&&(a.event=t),a}})()}encryptEventIfNeeded(e,t){var n=this;return w(function*(){if(t&&(yield n.shouldEncryptEventForRoom(e,t))&&!(!n.cryptoBackend&&n.usingExternalCrypto)){if(!n.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");n.updatePendingEventStatus(t,e,je.ENCRYPTING),yield n.cryptoBackend.encryptEvent(e,t)}})()}shouldEncryptEventForRoom(e,t){var n=this;return w(function*(){var i;return e.isEncrypted()||e.getType()===V.Reaction||e.isRedaction()?!1:!!(t.hasEncryptionStateEvent()||(yield(i=n.cryptoBackend)===null||i===void 0?void 0:i.isEncryptionEnabledInRoom(t.roomId)))})()}getEncryptedIfNeededEventType(e,t){var n;return t===V.Reaction?t:(n=this.getRoom(e))!==null&&n!==void 0&&n.hasEncryptionStateEvent()?V.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,n){e?e.updatePendingEvent(t,n):t.setStatus(n)}sendEventHttpRequest(e,t){var n=e.getTxnId();n||(n=this.makeTxnId(),e.setTxnId(n));var i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:n},o;if(e.isState()){var s="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(s="/rooms/$roomId/state/$eventType/$stateKey"),o=Se(s,i)}else if(e.isRedaction()&&e.event.redacts){var a="/rooms/$roomId/redact/$redactsEventId/$txnId";o=Se(a,Cr({$redactsEventId:e.event.redacts},i))}else o=Se("/rooms/$roomId/send/$eventType/$txnId",i);var l=e.getWireContent();return t?this.http.authedRequest(Z.Put,o,Hk(t),l):this.http.authedRequest(Z.Put,o,void 0,l).then(c=>(this.logger.debug("Event sent to ".concat(e.getRoomId()," with event id ").concat(c.event_id)),c))}redactEvent(e,t,n,i,o){var s,a,l;(s=n)!==null&&s!==void 0&&s.startsWith(Di)||(o=i,i=n,n=t,t=null);var c=(a=o)===null||a===void 0?void 0:a.reason,u={reason:c};if(((l=o)===null||l===void 0?void 0:l.with_rel_types)!==void 0){if(this.canSupport.get(dr.RelationBasedRedactions)===lr.Unsupported)throw new Error("Server does not support relation based redactions "+"roomId ".concat(e," eventId ").concat(n," txnId: ").concat(i," threadId ").concat(t));var d=this.canSupport.get(dr.RelationBasedRedactions)===lr.Stable?Mb.stable:Mb.unstable;u[d]=o.with_rel_types}return this.sendCompleteEvent(e,t,{type:V.RoomRedaction,content:u,redacts:n},i)}sendMessage(e,t,n,i){typeof t!="string"&&t!==null&&(i=n,n=t,t=null);var o=V.RoomMessage,s=n;return this.sendEvent(e,t,o,s,i)}sendTextMessage(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=GD(n);return this.sendMessage(e,t,s,i)}sendNotice(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=HD(n);return this.sendMessage(e,t,s,i)}sendEmoteMessage(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=zD(n);return this.sendMessage(e,t,s,i)}sendImageMessage(e,t,n,i){var o,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Image";!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(s=i||"Image",i=n,n=t,t=null);var a={msgtype:xi.Image,url:n,info:i,body:s};return this.sendMessage(e,t,a)}sendStickerMessage(e,t,n,i){var o,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:"Sticker";!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(s=i||"Sticker",i=n,n=t,t=null);var a={url:n,info:i,body:s};return this.sendEvent(e,t,V.Sticker,a)}sendHtmlMessage(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=$D(n,i);return this.sendMessage(e,t,s)}sendHtmlNotice(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=WD(n,i);return this.sendMessage(e,t,s)}sendHtmlEmote(e,t,n,i){var o;!((o=t)!==null&&o!==void 0&&o.startsWith(Di))&&t!==null&&(i=n,n=t,t=null);var s=qD(n,i);return this.sendMessage(e,t,s)}_unstable_sendDelayedEvent(e,t,n,i,o,s){var a=this;return w(function*(){if(!(yield a.doesServerSupportUnstableFeature(Wi)))throw Error("Server does not support the delayed events API");return a.addThreadRelationIfNeeded(o,n,e),a.sendCompleteEvent(e,n,{type:i,content:o},t,s)})()}_unstable_sendDelayedStateEvent(e,t,n,i){var o=arguments,s=this;return w(function*(){var a=o.length>4&&o[4]!==void 0?o[4]:"",l=o.length>5&&o[5]!==void 0?o[5]:{};if(!(yield s.doesServerSupportUnstableFeature(Wi)))throw Error("Server does not support the delayed events API");var c={$roomId:e,$eventType:n,$stateKey:a},u=Se("/rooms/$roomId/state/$eventType",c);return a!==void 0&&(u=Se(u+"/$stateKey",c)),s.http.authedRequest(Z.Put,u,Hk(t),i,l)})()}_unstable_getDelayedEvents(e){var t=this;return w(function*(){if(!(yield t.doesServerSupportUnstableFeature(Wi)))throw Error("Server does not support the delayed events API");var n=e?{from:e}:void 0;return yield t.http.authedRequest(Z.Get,"/delayed_events",n,void 0,{prefix:"".concat(Pt.Unstable,"/").concat(Wi)})})()}_unstable_updateDelayedEvent(e,t){var n=this;return w(function*(){if(!(yield n.doesServerSupportUnstableFeature(Wi)))throw Error("Server does not support the delayed events API");var i=Se("/delayed_events/$delayId",{$delayId:e}),o={action:t};return yield n.http.authedRequest(Z.Post,i,void 0,o,{prefix:"".concat(Pt.Unstable,"/").concat(Wi)})})()}sendReceipt(e,t,n){var i=arguments,o=this;return w(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:!1;if(o.isGuest())return Promise.resolve({});var a=Se("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),l=!s&&o.supportsThreads(),c=l?Cr(Cr({},n),{},{thread_id:kc(e)}):n,u=o.http.authedRequest(Z.Post,a,void 0,c||{}),d=o.getRoom(e.getRoomId());return d&&o.credentials.userId&&d.addLocalEchoReceipt(o.credentials.userId,e,t,s),u})()}sendReadReceipt(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:Xr.Read,o=t.length>2&&t[2]!==void 0?t[2]:!1;if(e){var s=e.getId(),a=n.getRoom(e.getRoomId());if(a!=null&&a.hasPendingEvent(s))throw new Error("Cannot set read receipt to a pending event (".concat(s,")"));return n.sendReceipt(e,i,{},o)}})()}setRoomReadMarkers(e,t,n,i){var o=this;return w(function*(){var s=o.getRoom(e);if(s!=null&&s.hasPendingEvent(t))throw new Error("Cannot set read marker to a pending event (".concat(t,")"));var a;if(n){if(a=n.getId(),s!=null&&s.hasPendingEvent(a))throw new Error("Cannot set read receipt to a pending event (".concat(a,")"));s==null||s.addLocalEchoReceipt(o.credentials.userId,n,Xr.Read)}var l;if(i){if(l=i.getId(),s!=null&&s.hasPendingEvent(l))throw new Error("Cannot set read receipt to a pending event (".concat(l,")"));s==null||s.addLocalEchoReceipt(o.credentials.userId,i,Xr.ReadPrivate)}return yield o.setRoomReadMarkersHttpRequest(e,t,a,l)})()}getUrlPreview(e,t){t=Math.floor(t/6e4)*6e4;var n=new URL(e);n.hash="",e=n.toString();var i=t+"_"+e;if(i in this.urlPreviewCache)return this.urlPreviewCache[i];var o=this.http.authedRequest(Z.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:Zl.V3,priority:"low"});return this.urlPreviewCache[i]=o,o}sendTyping(e,t,n){if(this.isGuest())return Promise.resolve({});var i=Se("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),o={typing:t};return t&&(o.timeout=n||2e4),this.http.authedRequest(Z.Put,i,void 0,o)}getRoomUpgradeHistory(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=this.getRoom(e);if(!i)return[];var o=this.findPredecessorRooms(i,t,n),s=this.findSuccessorRooms(i,t,n);return[...o,i,...s]}findPredecessorRooms(e,t,n){for(var i,o=[],s=new Set([e.roomId]),a=(i=e.findPredecessor(n))===null||i===void 0?void 0:i.roomId;a!==null;){var l;if(a){if(s.has(a))break;s.add(a)}var c=this.getRoom(a);if(c===null)break;if(t){var u=c.currentState.getStateEvents(V.RoomTombstone,"");if(!u||u.getContent().replacement_room!==e.roomId)break}o.splice(0,0,c),e=c,a=(l=e.findPredecessor(n))===null||l===void 0?void 0:l.roomId}return o}findSuccessorRooms(e,t,n){for(var i=[],o=e.currentState.getStateEvents(V.RoomTombstone,"");o;){var s=this.getRoom(o.getContent().replacement_room);if(!s||s.roomId===e.roomId)break;if(t){var a,l=(a=s.findPredecessor(n))===null||a===void 0?void 0:a.roomId;if(!l||l!==e.roomId)break}i.push(s);var c=new Set(i.map(u=>u.roomId));if(c.size<i.length)return i.slice(0,i.length-1);e=s,o=e.currentState.getStateEvents(V.RoomTombstone,"")}return i}invite(e,t,n){return this.membershipChange(e,t,Be.Invite,n)}inviteByEmail(e,t){return this.inviteByThreePid(e,"email",t)}inviteByThreePid(e,t,n){var i=this;return w(function*(){var o,s=Se("/rooms/$roomId/invite",{$roomId:e}),a=i.getIdentityServerUrl(!0);if(!a)return Promise.reject(new hr({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));var l={id_server:a,medium:t,address:n};if((o=i.identityServer)!==null&&o!==void 0&&o.getAccessToken){var c=yield i.identityServer.getAccessToken();c&&(l.id_access_token=c)}return i.http.authedRequest(Z.Post,s,void 0,l)})()}leave(e){return this.membershipChange(e,void 0,Be.Leave)}leaveRoomChain(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,n=this.getRoomUpgradeHistory(e),i=n;if(!t){i=[];for(var o of n)if(i.push(o),o.roomId===e)break}var s={},a=[],l=u=>this.leave(u).then(()=>{delete s[u]}).catch(d=>{s[u]=d});for(var c of i)a.push(l(c.roomId));return Promise.all(a).then(()=>s)}ban(e,t,n){return this.membershipChange(e,t,Be.Ban,n)}forget(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!0,o=Se("/rooms/$room_id/forget",{$room_id:e}),s=yield n.http.authedRequest(Z.Post,o);return i&&(n.store.removeRoom(e),n.emit(be.DeleteRoom,e)),s})()}unban(e,t){var n=Se("/rooms/$roomId/unban",{$roomId:e}),i={user_id:t};return this.http.authedRequest(Z.Post,n,void 0,i)}kick(e,t,n){var i=Se("/rooms/$roomId/kick",{$roomId:e}),o={user_id:t,reason:n};return this.http.authedRequest(Z.Post,i,void 0,o)}membershipChange(e,t,n,i){var o=Se("/rooms/$room_id/$membership",{$room_id:e,$membership:n});return this.http.authedRequest(Z.Post,o,void 0,{user_id:t,reason:i})}getPushActionsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushActions()||t){var{actions:n,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(n,i)}return e.getPushActions()}getPushDetailsForEvent(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;if(!e.getPushDetails()||t){var{actions:n,rule:i}=this.pushProcessor.actionsAndRuleForEvent(e);e.setPushDetails(n,i)}return e.getPushDetails()}setProfileInfo(e,t){var n=Se("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(Z.Put,n,void 0,t)}setDisplayName(e){var t=this;return w(function*(){var n=yield t.setProfileInfo("displayname",{displayname:e}),i=t.getUser(t.getUserId());return i&&(i.displayName=e,i.emit(ar.DisplayName,i.events.presence,i)),n})()}setAvatarUrl(e){var t=this;return w(function*(){var n=yield t.setProfileInfo("avatar_url",{avatar_url:e}),i=t.getUser(t.getUserId());return i&&(i.avatarUrl=e,i.emit(ar.AvatarUrl,i.events.presence,i)),n})()}mxcUrlToHttp(e,t,n,i,o,s,a){return bm(this.baseUrl,e,t,n,i,o,s,a)}setSyncPresence(e){var t=this;return w(function*(){var n;(n=t.syncApi)===null||n===void 0||n.setPresence(e)})()}setPresence(e){var t=this;return w(function*(){var n=Se("/presence/$userId/status",{$userId:t.credentials.userId}),i=["offline","online","unavailable"];if(i.indexOf(e.presence)===-1)throw new Error("Bad presence value: "+e.presence);yield t.http.authedRequest(Z.Put,n,void 0,e)})()}getPresence(e){var t=Se("/presence/$userId/status",{$userId:e});return this.http.authedRequest(Z.Get,t)}scrollback(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:30,n=0,i=this.ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){var o=Date.now()-i.errorTs;n=Math.max(T7-o,0)}if(e.oldState.paginationToken===null)return Promise.resolve(e);var s=this.store.scrollback(e,t).length;if(s===t)return Promise.resolve(e);t=t-s;var a=new Promise((l,c)=>{As(n).then(()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,Ge.Backward)).then(u=>{var d,f,p=u.chunk.map(this.getEventMapper());if(u.state){var h=u.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(h)}var[m,E,y]=e.partitionThreadedEvents(p);this.processAggregatedTimelineEvents(e,m),e.addEventsToTimeline(m,!0,e.getLiveTimeline()),this.processThreadEvents(e,E,!0),y.forEach(S=>e.relations.aggregateChildEvent(S)),e.oldState.paginationToken=(d=u.end)!==null&&d!==void 0?d:null,u.chunk.length===0&&(e.oldState.paginationToken=null),this.store.storeEvents(e,p,(f=u.end)!==null&&f!==void 0?f:null,!0),delete this.ongoingScrollbacks[e.roomId],l(e)}).catch(u=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},c(u)})});return i={promise:a},this.ongoingScrollbacks[e.roomId]=i,a}getEventMapper(e){return s7(this,e||{})}getEventTimeline(e,t){var n=this;return w(function*(){var i,o,s,a;if(!n.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!(e!=null&&e.room))throw new Error("getEventTimeline only supports room timelines");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);if(e.thread&&n.supportsThreads())return n.getThreadTimeline(e,t);var l=Se("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),c=void 0;(i=n.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(c={filter:JSON.stringify(gn.LAZY_LOADING_MESSAGES_FILTER)});var u=yield n.http.authedRequest(Z.Get,l,c);if(!u.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);var d=n.getEventMapper(),f=d(u.event);if(f.isRelation(vt.name)){n.logger.warn("Tried loading a regular timeline at the position of a thread event");return}var p=[...u.events_after.reverse().map(d),f,...u.events_before.map(d)],h=e.getTimelineForEvent(p[0].getId());h?h.getState(we.BACKWARDS).setUnknownStateEvents(u.state.map(d)):(h=e.addTimeline(),h.initialiseState(u.state.map(d)),h.getState(we.FORWARDS).paginationToken=u.end);var[m,E,y]=e.room.partitionThreadedEvents(p);return e.addEventsToTimeline(m,!0,h,u.start),n.processThreadEvents(e.room,E,!0),n.processAggregatedTimelineEvents(e.room,m),y.forEach(S=>e.relations.aggregateChildEvent(S)),(o=(s=e.getTimelineForEvent(t))!==null&&s!==void 0?s:(a=e.room.findThreadForEvent(f))===null||a===void 0?void 0:a.liveTimeline)!==null&&o!==void 0?o:h})()}getThreadTimeline(e,t){var n=this;return w(function*(){var i;if(!n.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 o=Se("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),s={limit:"0"};(i=n.clientOpts)!==null&&i!==void 0&&i.lazyLoadMembers&&(s.filter=JSON.stringify(gn.LAZY_LOADING_MESSAGES_FILTER));var a=yield n.http.authedRequest(Z.Get,o,s),l=n.getEventMapper(),c=l(a.event);if(e.canContain(c)){var u=n.canSupport.get(dr.RelationsRecursion)!==lr.Unsupported;if(Et.hasServerSideSupport)if(Et.hasServerSideFwdPaginationSupport){var d,f,p;if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");var h=e.thread,m=yield n.fetchRelations(e.room.roomId,h.id,null,null,{dir:Ge.Backward,from:a.start,recurse:u||void 0}),E=yield n.fetchRelations(e.room.roomId,h.id,null,null,{dir:Ge.Forward,from:a.end,recurse:u||void 0}),y=[...E.chunk.reverse().filter(vy(h.id)).map(l),c,...m.chunk.filter(vy(h.id)).map(l)];for(var S of y){var R;yield(R=e.thread)===null||R===void 0?void 0:R.processEvent(S)}var k=e.getTimelineForEvent(c.getId());if(k?k.getState(we.BACKWARDS).setUnknownStateEvents(a.state.map(l)):(k=e.addTimeline(),k.initialiseState(a.state.map(l))),e.addEventsToTimeline(y,!0,k,E.next_batch),!m.next_batch){var x=yield n.fetchRoomEvent(e.room.roomId,h.id);e.addEventsToTimeline([l(x)],!0,k,null)}return k.setPaginationToken((d=m.next_batch)!==null&&d!==void 0?d:null,Ge.Backward),k.setPaginationToken((f=E.next_batch)!==null&&f!==void 0?f:null,Ge.Forward),n.processAggregatedTimelineEvents(e.room,y),(p=e.getTimelineForEvent(t))!==null&&p!==void 0?p:k}else{for(var T,O=e.thread,C=yield n.fetchRelations(e.room.roomId,O.id,vt.name,null,{dir:Ge.Backward,from:a.start,recurse:u||void 0}),N=[],F=a.end;F;){var H,ie=yield n.fetchRelations(e.room.roomId,O.id,vt.name,null,{dir:Ge.Forward,from:F,recurse:u||void 0});F=(H=ie.next_batch)!==null&&H!==void 0?H:null,N.push(...ie.chunk)}var $=[...N.reverse().map(l),c,...C.chunk.map(l)];for(var X of $){var oe;yield(oe=e.thread)===null||oe===void 0?void 0:oe.processEvent(X)}var re=e.getLiveTimeline();if(re.getState(we.BACKWARDS).setUnknownStateEvents(a.state.map(l)),e.addEventsToTimeline($,!0,re,null),!C.next_batch){var ae=yield n.fetchRoomEvent(e.room.roomId,O.id);e.addEventsToTimeline([l(ae)],!0,re,null)}return re.setPaginationToken((T=C.next_batch)!==null&&T!==void 0?T:null,Ge.Backward),re.setPaginationToken(null,Ge.Forward),n.processAggregatedTimelineEvents(e.room,$),re}}})()}getLatestTimeline(e){var t=this;return w(function*(){if(!t.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!e.room)throw new Error("getLatestTimeline only supports room timelines");var n;if(e.threadListType!==null){var i,o=yield t.createThreadListMessagesRequest(e.room.roomId,null,1,Ge.Backward,e.threadListType,e.getFilter());n=(i=o.chunk)===null||i===void 0?void 0:i[0]}else if(e.thread&&Et.hasServerSideSupport){var s,a=t.canSupport.get(dr.RelationsRecursion)!==lr.Unsupported,l=yield t.fetchRelations(e.room.roomId,e.thread.id,vt.name,null,{dir:Ge.Backward,limit:1,recurse:a||void 0});n=(s=l.chunk)===null||s===void 0?void 0:s[0]}else{var c,u,d=Se("/rooms/$roomId/messages",{$roomId:e.room.roomId}),f={dir:"b"};(c=t.clientOpts)!==null&&c!==void 0&&c.lazyLoadMembers&&(f.filter=JSON.stringify(gn.LAZY_LOADING_MESSAGES_FILTER));var p=yield t.http.authedRequest(Z.Get,d,f);n=(u=p.chunk)===null||u===void 0?void 0:u[0]}if(!n)throw new Error("No message returned when trying to construct getLatestTimeline");return t.getEventTimeline(e,n.event_id)})()}createMessagesRequest(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,o=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0,a=Se("/rooms/$roomId/messages",{$roomId:e}),l={limit:i.toString(),dir:o};t&&(l.from=t);var c=null;if((n=this.clientOpts)!==null&&n!==void 0&&n.lazyLoadMembers&&(c=Object.assign({},gn.LAZY_LOADING_MESSAGES_FILTER)),s){var u;c=c||{},Object.assign(c,(u=s.getRoomTimelineFilterComponent())===null||u===void 0?void 0:u.toJSON())}return c&&(l.filter=JSON.stringify(c)),this.http.authedRequest(Z.Get,a,l)}createThreadListMessagesRequest(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:30,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Ge.Backward,s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:di.All,a=arguments.length>5?arguments[5]:void 0,l=Se("/rooms/$roomId/threads",{$roomId:e}),c={limit:i.toString(),dir:o,include:tL(s)};t&&(c.from=t);var u={};if((n=this.clientOpts)!==null&&n!==void 0&&n.lazyLoadMembers&&(u=Cr({},gn.LAZY_LOADING_MESSAGES_FILTER)),a){var d;u=Cr(Cr({},u),(d=a.getRoomTimelineFilterComponent())===null||d===void 0?void 0:d.toJSON())}Object.keys(u).length&&(c.filter=JSON.stringify(u));var f={prefix:Et.hasServerSideListSupport===Vr.Stable?Pt.V1:"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(Z.Get,l,c,void 0,f).then(p=>{var h;return Cr(Cr({},p),{},{chunk:(h=p.chunk)===null||h===void 0?void 0:h.reverse(),start:p.prev_batch,end:p.next_batch})})}paginateEventTimeline(e,t){var n=this,i=e.getTimelineSet()===this.notifTimelineSet,o=this.getRoom(e.getRoomId()),s=e.getTimelineSet().threadListType,a=e.getTimelineSet().thread;t=t||{};var l=t.backwards||!1;if(i&&!l)throw new Error("paginateNotifTimeline can only paginate backwards");var c=l?we.BACKWARDS:we.FORWARDS,u=e.getPaginationToken(c),d=e.paginationRequests[c];if(d)return d;var f,p,h;if(i){var m;f="/notifications",p={limit:((m=t.limit)!==null&&m!==void 0?m:30).toString(),only:"highlight"},u&&u!=="end"&&(p.from=u),h=this.http.authedRequest(Z.Get,f,p).then(function(){var k=w(function*(x){var T=x.next_token,O=[];x.notifications=x.notifications.filter(mi);for(var C=0;C<x.notifications.length;C++){var N=x.notifications[C],F=n.getEventMapper()(N.event);n.getPushDetailsForEvent(F,!0),F.event.room_id=N.room_id,O[C]=F}var H=e.getTimelineSet();return H.addEventsToTimeline(O,l,e,T),n.processAggregatedTimelineEvents(H.room,O),l&&!x.next_token&&e.setPaginationToken(null,c),!!x.next_token});return function(x){return k.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}else if(s!==null){if(!o)throw new Error("Unknown room "+e.getRoomId());if(!Et.hasServerSideFwdPaginationSupport&&c===Ge.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");h=this.createThreadListMessagesRequest(e.getRoomId(),u,t.limit,c,s,e.getFilter()).then(k=>{if(k.state){var x=e.getState(c),T=k.state.filter(mi).map(this.getEventMapper());x.setUnknownStateEvents(T)}var O=k.end,C=k.chunk.filter(mi).map(this.getEventMapper()),N=e.getTimelineSet();return N.addEventsToTimeline(C,l,e,O),this.processAggregatedTimelineEvents(o,C),this.processThreadRoots(o,C,l),l&&k.end==k.start&&e.setPaginationToken(null,c),k.end!==k.start}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}else if(a){var E,y,S=this.getRoom((E=e.getRoomId())!==null&&E!==void 0?E:void 0);if(!S)throw new Error("Unknown room "+e.getRoomId());var R=this.canSupport.get(dr.RelationsRecursion)!==lr.Unsupported;h=this.fetchRelations((y=e.getRoomId())!==null&&y!==void 0?y:"",a.id,null,null,{dir:c,limit:t.limit,from:u??void 0,recurse:R||void 0}).then(function(){var k=w(function*(x){var T=n.getEventMapper(),O=x.chunk.filter(mi).filter(vy(a.id)).map(T);for(var C of O.slice().reverse()){yield a==null?void 0:a.processEvent(C);var N=C.getSender();(!l||(a==null?void 0:a.getEventReadUpTo(N))===null)&&S.addLocalEchoReceipt(N,C,Xr.Read)}var F=x.next_batch,H=e.getTimelineSet();if(H.addEventsToTimeline(O,l,e,F??null),!F&&l){var ie,$,X=(ie=a.rootEvent)!==null&&ie!==void 0?ie:T(yield n.fetchRoomEvent(($=e.getRoomId())!==null&&$!==void 0?$:"",a.id));H.addEventsToTimeline([X],!0,e,null)}return n.processAggregatedTimelineEvents(H.room,O),l&&!F&&e.setPaginationToken(null,c),!!F});return function(x){return k.apply(this,arguments)}}()).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}else{if(!o)throw new Error("Unknown room "+e.getRoomId());h=this.createMessagesRequest(e.getRoomId(),u,t.limit,c,e.getFilter()).then(k=>{if(k.state){var x=e.getState(c),T=k.state.filter(mi).map(this.getEventMapper());x.setUnknownStateEvents(T)}var O=k.end,C=k.chunk.filter(mi).map(this.getEventMapper()),N=e.getTimelineSet(),[F,,H]=o.partitionThreadedEvents(C);N.addEventsToTimeline(F,l,e,O),this.processAggregatedTimelineEvents(o,F),this.processThreadRoots(o,F.filter($=>$.getServerAggregatedRelation(vt.name)),!1),H.forEach($=>o.relations.aggregateChildEvent($));var ie=k.end===void 0||k.end===k.start;return l&&ie&&e.setPaginationToken(null,c),!ie}).finally(()=>{e.paginationRequests[c]=null}),e.paginationRequests[c]=h}return h}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20;return(t=this.peekSync)===null||t===void 0||t.stopPeeking(),this.peekSync=new Au(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e,n)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){var n=this.sendStateEvent(e,V.RoomGuestAccess,{guest_access:t.allowJoin?gv.CanJoin:gv.Forbidden},""),i=Promise.resolve();return t.allowRead&&(i=this.sendStateEvent(e,V.RoomHistoryVisibility,{history_visibility:Jw.WorldReadable},"")),Promise.all([i,n]).then()}requestRegisterEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestRegisterMsisdnToken(e,t,n,i,o){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:o})}requestAdd3pidEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestAdd3pidMsisdnToken(e,t,n,i,o){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:o})}requestPasswordEmailToken(e,t,n,i){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:i})}requestPasswordMsisdnToken(e,t,n,i,o){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:i,next_link:o})}requestTokenFromEndpoint(e,t){var n=this;return w(function*(){var i=Object.assign({},t);return n.http.request(Z.Post,e,void 0,i)})()}getRoomPushRule(e,t){if(this.pushRules){var n;return(n=this.pushRules[e])===null||n===void 0||(n=n.room)===null||n===void 0?void 0:n.find(i=>i.rule_id===t)}else throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,n){var i,o=!1,s=this.getRoomPushRule(e,t);if(s!=null&&s.actions.includes(ks.DontNotify)&&(o=!0),!n)o&&(i=this.deletePushRule(e,Er.RoomSpecific,s.rule_id));else if(!s)i=this.addPushRule(e,Er.RoomSpecific,t,{actions:[ks.DontNotify]});else if(!o){var a=Hs();this.deletePushRule(e,Er.RoomSpecific,s.rule_id).then(()=>{this.addPushRule(e,Er.RoomSpecific,t,{actions:[ks.DontNotify]}).then(()=>{a.resolve()}).catch(l=>{a.reject(l)})}).catch(l=>{a.reject(l)}),i=a.promise}if(i)return new Promise((l,c)=>{i.then(()=>{this.getPushRules().then(u=>{this.pushRules=u,l()}).catch(u=>{c(u)})}).catch(u=>{this.getPushRules().then(d=>{this.pushRules=d,c(u)}).catch(d=>{c(u)})})})}searchMessageText(e){var t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){var t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:qN.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},n={_query:t,results:[],highlights:[]};return this.search({body:t}).then(i=>this.processRoomEventsSearch(n,i))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;var t={body:e._query,next_batch:e.next_batch},n=this.search(t,e.abortSignal).then(i=>this.processRoomEventsSearch(e,i)).finally(()=>{e.pendingRequest=void 0});return e.pendingRequest=n,n}processRoomEventsSearch(e,t){var n,i,o=t.search_categories.room_events;e.count=o.count,e.next_batch=o.next_batch;var s=new Set(o.highlights);e.highlights.forEach(h=>{s.add(h)}),e.highlights=Array.from(s);for(var a=this.getEventMapper(),l=(n=(i=o.results)===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0,c=0;c<l;c++){var u=Pm.fromJson(o.results[c],a),d=this.getRoom(u.context.getEvent().getRoomId());if(d)for(var f of u.context.getTimeline()){var p=d.getMember(f.getSender());!f.sender&&p&&(f.sender=p)}e.results.push(u)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;var e=new Au(this,this.clientOpts,this.buildSyncApiOptions());return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then(()=>{this.logger.debug("Marking success of sync left room request"),this.syncedLeftRooms=!0}).finally(()=>{this.syncLeftRoomsPromise=void 0}),this.syncLeftRoomsPromise}createFilter(e){var t=Se("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(Z.Post,t,void 0,e).then(n=>{var i=gn.fromJson(this.credentials.userId,n.filter_id,e);return this.store.storeFilter(i),i})}getFilter(e,t,n){if(n){var i=this.store.getFilter(e,t);if(i)return Promise.resolve(i)}var o=Se("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(Z.Get,o).then(s=>{var a=gn.fromJson(e,t,s);return this.store.storeFilter(a),a})}getOrCreateFilter(e,t){var n=this;return w(function*(){var i=n.store.getFilterIdByName(e),o;if(i){try{var s=yield n.getFilter(n.credentials.userId,i,!0);if(s){var a=s.getDefinition(),l=t.getDefinition();Va(a,l)&&(o=i)}}catch(u){if(u.errcode!=="M_UNKNOWN"&&u.errcode!=="M_NOT_FOUND")throw u}o||n.store.setFilterIdByName(e,void 0)}if(o)return o;var c=yield n.createFilter(t.getDefinition());return n.store.setFilterIdByName(e,c.filterId),c.filterId})()}getOpenIdToken(){var e=Se("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(Z.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(Z.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return this.checkTurnServersIntervalID!==void 0}checkTurnServers(){var e=this;return w(function*(){if(e.canSupportVoip){var t=!1,n=e.turnServersExpiry-Date.now();if(n>Gk)e.logger.debug("TURN creds are valid for another "+n+" ms: not fetching new ones."),t=!0;else{e.logger.debug("Fetching new TURN credentials");try{var i=yield e.turnServer();if(i.uris){e.logger.debug("Got TURN URIs: "+i.uris+" refresh in "+i.ttl+" secs");var o={urls:i.uris,username:i.username,credential:i.password};e.turnServers=[o],e.turnServersExpiry=Date.now()+i.ttl*1e3,t=!0,e.emit(be.TurnServers,e.turnServers)}}catch(s){e.logger.error("Failed to get TURN URIs",s),s.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(be.TurnServersError,s,!0)):e.emit(be.TurnServersError,s,!1)}}return t}})()}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){var e=Se("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(Z.Get,e,void 0,void 0,{prefix:""}).then(t=>t.admin)}whoisSynapseUser(e){var t=Se("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(Z.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){var t=Se("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(Z.Post,t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e=this;return w(function*(){var t;e.clientWellKnownPromise=Ke.getRawClientConfig((t=e.getDomain())!==null&&t!==void 0?t:void 0),e.clientWellKnown=yield e.clientWellKnownPromise,e.emit(be.ClientWellKnown,e.clientWellKnown)})()}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){var e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter(n=>{var[i,o]=n;return e.includes(typeof o)}).reduce((n,i)=>{var[o,s]=i;return n[o]=s,n},{});return this.store.storeClientOptions(t)}_unstable_getSharedRooms(e){var t=this;return w(function*(){var n=yield t.doesServerSupportUnstableFeature(JN),i=yield t.doesServerSupportUnstableFeature(XN),o=yield t.doesServerSupportUnstableFeature(QN);if(!n&&!i&&!o)throw Error("Server does not support the Mutual Rooms API");var s,a;o?(s="/uk.half-shot.msc2666/user/mutual_rooms",a={user_id:e}):(s=Se("/uk.half-shot.msc2666/user/".concat(i?"mutual_rooms":"shared_rooms","/$userId"),{$userId:e}),a={});var l=[],c=null;do{var u={};c!=null&&o&&(u.batch_token=c);var d=yield t.http.authedRequest(Z.Get,s,Cr(Cr({},a),u),void 0,{prefix:Pt.Unstable});l.push(...d.joined),d.next_batch_token!==void 0?c=d.next_batch_token:c=null}while(c!=null);return l})()}getVersions(){var e=this;return w(function*(){if(e.serverVersionsPromise)return e.serverVersionsPromise;e.serverVersionsPromise=e.http.authedRequest(Z.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch(n=>{throw e.serverVersionsPromise=void 0,n});var t=yield e.serverVersionsPromise;return e.canSupport=yield Cz(t),e.serverVersionsPromise})()}isVersionSupported(e){var t=this;return w(function*(){var{versions:n}=yield t.getVersions();return n&&n.includes(e)})()}doesServerSupportUnstableFeature(e){var t=this;return w(function*(){var n=yield t.getVersions();if(!n)return!1;var i=n.unstable_features;return i&&!!i[e]})()}doesServerForceEncryptionForPreset(e){var t=this;return w(function*(){var n=yield t.getVersions();if(!n)return!1;var i=n.unstable_features,o=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return i&&!!i["io.element.e2ee_forced.".concat(o)]})()}doesServerSupportThread(){var e=this;return w(function*(){if(yield e.isVersionSupported("v1.4"))return{threads:Vr.Stable,list:Vr.Stable,fwdPagination:Vr.Stable};try{var[t,n,i,o,s,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:lp(n,t),list:lp(o,i),fwdPagination:lp(a,s)}}catch{return{threads:Vr.None,list:Vr.None,fwdPagination:Vr.None}}})()}hasLazyLoadMembersEnabled(){var e;return!!((e=this.clientOpts)!==null&&e!==void 0&&e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,n,i){var o=arguments,s=this;return w(function*(){var a,l,c=o.length>4&&o[4]!==void 0?o[4]:{dir:Ge.Backward},u=i?s.getEncryptedIfNeededEventType(e,i):null,[d,f]=yield Promise.all([s.fetchRoomEvent(e,t),s.fetchRelations(e,t,n,u,c)]),p=s.getEventMapper(),h=d?p(d):void 0,m=f.chunk.map(p);if(u===V.RoomMessageEncrypted){var E=h?m.concat(h):m;yield Promise.all(E.map(y=>s.decryptEventIfNeeded(y))),i!==null&&(m=m.filter(y=>y.getType()===i))}return h&&n===Nt.Replace&&(m=m.filter(y=>y.getSender()===h.getSender())),{originalEvent:h??null,events:m,nextBatch:(a=f.next_batch)!==null&&a!==void 0?a:null,prevBatch:(l=f.prev_batch)!==null&&l!==void 0?l:null}})()}getCrossSigningCacheCallbacks(){var e;return(e=this.crypto)===null||e===void 0?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return Ei(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.isCryptoEnabled()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case Xb.IS:return this.http.getUrl("/terms",void 0,ho.V2,t);case Xb.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(){var e,t,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return n&&((e=this.idBaseUrl)!==null&&e!==void 0&&e.startsWith("http://")||(t=this.idBaseUrl)!==null&&t!==void 0&&t.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=ey(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(Z.Get,"/register/available",{username:e}).then(t=>t.available).catch(t=>t.errcode==="M_USER_IN_USE"?!1:Promise.reject(t))}register(e,t,n,i,o,s,a){n&&(i.session=n);var l={auth:i,refresh_token:!0};return e!=null&&(l.username=e),t!=null&&(l.password=t),s!=null&&(l.guest_access_token=s),a!=null&&(l.inhibit_login=a),this.registerRequest(l)}registerGuest(){var{body:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.registerRequest(e||{},"guest")}registerRequest(e,t){var n={};return t&&(n.kind=t),this.http.request(Z.Post,"/register",n,e)}refreshToken(e){var t=n=>this.http.authedRequest(Z.Post,"/refresh",void 0,{refresh_token:e},{prefix:n,inhibitLogoutEmit:!0});return t(Pt.V3).catch(n=>{if(n.errcode==="M_UNRECOGNIZED")return t(Pt.V1);throw n})}loginFlows(){return this.http.request(Z.Get,"/login")}login(e,t){return this.http.authedRequest(Z.Post,"/login",void 0,Cr(Cr({},t),{},{type:e})).then(n=>(n.access_token&&n.user_id&&(this.http.opts.accessToken=n.access_token,this.credentials={userId:n.user_id}),n))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"sso",n=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,o="/login/"+t+"/redirect";n&&(o+="/"+n);var s={redirectUrl:e,[I7.unstable]:i};return this.http.getUrl(o,s).href}loginWithToken(e){return this.login("m.login.token",{token:e})}logout(){var e=arguments,t=this;return w(function*(){var n,i=e.length>0&&e[0]!==void 0?e[0]:!1;if((n=t.crypto)!==null&&n!==void 0&&(n=n.backupManager)!==null&&n!==void 0&&n.getKeyBackupEnabled())try{for(;(yield t.crypto.backupManager.backupPendingKeys(200))>0;);}catch(o){t.logger.error("Key backup request failed when logging out. Some keys may be missing from backup",o)}return i&&(t.stopClient(),t.http.abort()),t.http.authedRequest(Z.Post,"/logout")})()}deactivateAccount(e,t){var n={};return e&&(n.auth=e),t!==void 0&&(n.erase=t),this.http.authedRequest(Z.Post,"/account/deactivate",void 0,n)}requestLoginToken(e){var t=this;return w(function*(){var n={auth:e};return t.http.authedRequest(Z.Post,"/login/get_token",void 0,n,{prefix:Pt.V1})})()}getFallbackAuthUrl(e,t){var n=Se("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(n,{session:t}).href}createRoom(e){var t=this;return w(function*(){var n,i=(e.invite_3pid||[]).filter(a=>!a.id_access_token);if(i.length>0&&(n=t.identityServer)!==null&&n!==void 0&&n.getAccessToken){var o=yield t.identityServer.getAccessToken();if(o)for(var s of i)s.id_access_token=o}return t.http.authedRequest(Z.Post,"/createRoom",void 0,e)})()}fetchRelations(e,t,n,i){var o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{dir:Ge.Backward},s=o;Et.hasServerSideFwdPaginationSupport===Vr.Experimental&&(s=gC("dir","org.matrix.msc3715.dir",s)),this.canSupport.get(dr.RelationsRecursion)===lr.Unstable&&(s=gC("recurse","org.matrix.msc3981.recurse",s));var a=_b(s),l="/rooms/$roomId/relations/$eventId";n!==null?(l+="/$relationType",i!==null&&(l+="/$eventType")):i!==null&&(this.logger.warn("eventType: ".concat(i,` ignored when fetching
294
- relations as relationType is null`)),i=null);var c=Se(l+"?"+a,{$roomId:e,$eventId:t,$relationType:n,$eventType:i});return this.http.authedRequest(Z.Get,c,void 0,void 0,{prefix:Pt.V1})}roomState(e){var t=Se("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(Z.Get,t)}fetchRoomEvent(e,t){var n=Se("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(Z.Get,n)}members(e,t,n,i){var o={};t&&(o.membership=t),n&&(o.not_membership=n),i&&(o.at=i);var s=_b(o),a=Se("/rooms/$roomId/members?"+s,{$roomId:e});return this.http.authedRequest(Z.Get,a)}upgradeRoom(e,t){var n=Se("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(Z.Post,n,void 0,{new_version:t})}getStateEvent(e,t,n){var i={$roomId:e,$eventType:t,$stateKey:n},o=Se("/rooms/$roomId/state/$eventType",i);return n!==void 0&&(o=Se(o+"/$stateKey",i)),this.http.authedRequest(Z.Get,o)}sendStateEvent(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"",o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},s={$roomId:e,$eventType:t,$stateKey:i},a=Se("/rooms/$roomId/state/$eventType",s);return i!==void 0&&(a=Se(a+"/$stateKey",s)),this.http.authedRequest(Z.Put,a,void 0,n,o)}roomInitialSync(e,t){var n,i=Se("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(Z.Get,i,{limit:(n=t==null?void 0:t.toString())!==null&&n!==void 0?n:"30"})}setRoomReadMarkersHttpRequest(e,t,n,i){var o=this;return w(function*(){var s=Se("/rooms/$roomId/read_markers",{$roomId:e}),a={[Xr.FullyRead]:t,[Xr.Read]:n};return((yield o.doesServerSupportUnstableFeature("org.matrix.msc2285.stable"))||(yield o.isVersionSupported("v1.4")))&&(a[Xr.ReadPrivate]=i),o.http.authedRequest(Z.Post,s,void 0,a)})()}getJoinedRooms(){var e=Se("/joined_rooms",{});return this.http.authedRequest(Z.Get,e)}getJoinedRoomMembers(e){var t=Se("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(Z.Get,t)}publicRooms(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{server:t,limit:n,since:i}=e,o=BH(e,w7);if(Object.keys(o).length===0){var s={server:t,limit:n,since:i};return this.http.authedRequest(Z.Get,"/publicRooms",s)}else{var a={server:t},l=Cr({limit:n,since:i},o);return this.http.authedRequest(Z.Post,"/publicRooms",a,l)}}createAlias(e,t){var n=Se("/directory/room/$alias",{$alias:e}),i={room_id:t};return this.http.authedRequest(Z.Put,n,void 0,i)}deleteAlias(e){var t=Se("/directory/room/$alias",{$alias:e});return this.http.authedRequest(Z.Delete,t)}getLocalAliases(e){var t=Se("/rooms/$roomId/aliases",{$roomId:e}),n=Pt.V3;return this.http.authedRequest(Z.Get,t,void 0,void 0,{prefix:n})}getRoomIdForAlias(e){var t=Se("/directory/room/$alias",{$alias:e});return this.http.authedRequest(Z.Get,t)}getRoomDirectoryVisibility(e){var t=Se("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(Z.Get,t)}setRoomDirectoryVisibility(e,t){var n=Se("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(Z.Put,n,void 0,{visibility:t})}searchUserDirectory(e){var{term:t,limit:n}=e,i={search_term:t};return n!==void 0&&(i.limit=n),this.http.authedRequest(Z.Post,"/user_directory/search",void 0,i)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){var n=t?Se("/profile/$userId/$info",{$userId:e,$info:t}):Se("/profile/$userId",{$userId:e});return this.http.authedRequest(Z.Get,n)}doesServerSupportExtendedProfiles(){var e=this;return w(function*(){return e.doesServerSupportUnstableFeature(ZN)})()}getExtendedProfileRequestPrefix(){var e=this;return w(function*(){return(yield e.doesServerSupportUnstableFeature("uk.tcpip.msc4133.stable"))?Pt.V3:"/_matrix/client/unstable/uk.tcpip.msc4133"})()}getExtendedProfile(e){var t=this;return w(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");return t.http.authedRequest(Z.Get,Se("/profile/$userId",{$userId:e}),void 0,void 0,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}getExtendedProfileProperty(e,t){var n=this;return w(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=yield n.http.authedRequest(Z.Get,Se("/profile/$userId/$key",{$userId:e,$key:t}),void 0,void 0,{prefix:yield n.getExtendedProfileRequestPrefix()});return i[t]})()}setExtendedProfileProperty(e,t){var n=this;return w(function*(){if(!(yield n.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var i=n.getUserId();yield n.http.authedRequest(Z.Put,Se("/profile/$userId/$key",{$userId:i,$key:e}),void 0,{[e]:t},{prefix:yield n.getExtendedProfileRequestPrefix()})})()}deleteExtendedProfileProperty(e){var t=this;return w(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var n=t.getUserId();yield t.http.authedRequest(Z.Delete,Se("/profile/$userId/$key",{$userId:n,$key:e}),void 0,void 0,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}patchExtendedProfile(e){var t=this;return w(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var n=t.getUserId();return t.http.authedRequest(Z.Patch,Se("/profile/$userId",{$userId:n}),{},e,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}setExtendedProfile(e){var t=this;return w(function*(){if(!(yield t.doesServerSupportExtendedProfiles()))throw new Error("Server does not support extended profiles");var n=t.getUserId();yield t.http.authedRequest(Z.Put,Se("/profile/$userId",{$userId:n}),{},e,{prefix:yield t.getExtendedProfileRequestPrefix()})})()}getThreePids(){return this.http.authedRequest(Z.Get,"/account/3pid")}addThreePidOnly(e){var t=this;return w(function*(){var n="/account/3pid/add";return t.http.authedRequest(Z.Post,n,void 0,e)})()}bindThreePid(e){var t=this;return w(function*(){var n="/account/3pid/bind";return t.http.authedRequest(Z.Post,n,void 0,e)})()}unbindThreePid(e,t){var n=this;return w(function*(){var i="/account/3pid/unbind",o={medium:e,address:t,id_server:n.getIdentityServerUrl(!0)};return n.http.authedRequest(Z.Post,i,void 0,o)})()}deleteThreePid(e,t){var n="/account/3pid/delete";return this.http.authedRequest(Z.Post,n,void 0,{medium:e,address:t})}setPassword(e,t,n){var i="/account/password",o={auth:e,new_password:t,logout_devices:n};return this.http.authedRequest(Z.Post,i,void 0,o)}getDevices(){return this.http.authedRequest(Z.Get,"/devices")}getDevice(e){var t=Se("/devices/$device_id",{$device_id:e});return this.http.authedRequest(Z.Get,t)}setDeviceDetails(e,t){var n=Se("/devices/$device_id",{$device_id:e});return this.http.authedRequest(Z.Put,n,void 0,t)}deleteDevice(e,t){var n=Se("/devices/$device_id",{$device_id:e}),i={};return t&&(i.auth=t),this.http.authedRequest(Z.Delete,n,void 0,i)}deleteMultipleDevices(e,t){var n={devices:e};t&&(n.auth=t);var i="/delete_devices";return this.http.authedRequest(Z.Post,i,void 0,n)}getPushers(){var e=this;return w(function*(){var t=yield e.http.authedRequest(Z.Get,"/pushers");return(yield e.doesServerSupportUnstableFeature("org.matrix.msc3881"))||(t.pushers=t.pushers.map(n=>(n.hasOwnProperty(Ab.name)||(n[Ab.name]=!0),n))),t})()}setPusher(e){var t="/pushers/set";return this.http.authedRequest(Z.Post,t,void 0,e)}removePusher(e,t){var n="/pushers/set",i={pushkey:e,app_id:t,kind:null};return this.http.authedRequest(Z.Post,n,void 0,i)}setLocalNotificationSettings(e,t){var n="".concat(UD.name,".").concat(e);return this.setAccountData(n,t)}getPushRules(){return this.http.authedRequest(Z.Get,"/pushrules/").then(e=>(this.setPushRules(e),this.pushRules))}setPushRules(e){this.pushRules=hi.rewriteDefaultRules(e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,n,i){var o=Se("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Put,o,void 0,i)}deletePushRule(e,t,n){var i=Se("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Delete,i)}setPushRuleEnabled(e,t,n,i){var o=Se("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Put,o,void 0,{enabled:i})}setPushRuleActions(e,t,n,i){var o=Se("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this.http.authedRequest(Z.Put,o,void 0,{actions:i})}search(e,t){var{body:n,next_batch:i}=e,o={};return i&&(o.next_batch=i),this.http.authedRequest(Z.Post,"/search",o,n,{abortSignal:t})}uploadKeysRequest(e,t){return this.http.authedRequest(Z.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(Z.Post,"/keys/signatures/upload",void 0,e)}downloadKeysForUsers(e){var{token:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n={device_keys:{}};return t!==void 0&&(n.token=t),e.forEach(i=>{n.device_keys[i]=[]}),this.http.authedRequest(Z.Post,"/keys/query",void 0,n)}claimOneTimeKeys(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"signed_curve25519",n=arguments.length>2?arguments[2]:void 0,i={};t===void 0&&(t="signed_curve25519");for(var[o,s]of e){var a=i[o]||{};Qi(i,o,a),Qi(a,s,t)}var l={one_time_keys:i};n&&(l.timeout=n);var c="/keys/claim";return this.http.authedRequest(Z.Post,c,void 0,l)}getKeyChanges(e,t){var n={from:e,to:t};return this.http.authedRequest(Z.Get,"/keys/changes",n)}uploadDeviceSigningKeys(e,t){var n=Object.assign({},t);return e&&Object.assign(n,{auth:e}),this.http.authedRequest(Z.Post,"/keys/device_signing/upload",void 0,n,{prefix:Pt.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");var t=this.http.getUrl("/account/register",void 0,ho.V2,this.idBaseUrl);return this.http.requestOtherUrl(Z.Post,t,e)}requestEmailToken(e,t,n,i,o){var s={client_secret:t,email:e,send_attempt:n==null?void 0:n.toString()};return i&&(s.next_link=i),this.http.idServerRequest(Z.Post,"/validate/email/requestToken",s,ho.V2,o)}requestMsisdnToken(e,t,n,i,o,s){var a={client_secret:n,country:e,phone_number:t,send_attempt:i==null?void 0:i.toString()};return o&&(a.next_link=o),this.http.idServerRequest(Z.Post,"/validate/msisdn/requestToken",a,ho.V2,s)}submitMsisdnToken(e,t,n,i){var o={sid:e,client_secret:t,token:n};return this.http.idServerRequest(Z.Post,"/validate/msisdn/submitToken",o,ho.V2,i??void 0)}submitMsisdnTokenOtherUrl(e,t,n,i){var o={sid:t,client_secret:n,token:i};return this.http.requestOtherUrl(Z.Post,e,o)}getIdentityHashDetails(e){return this.http.idServerRequest(Z.Get,"/hash_details",void 0,ho.V2,e)}identityHashedLookup(e,t){var n=this;return w(function*(){var i={},o=yield n.getIdentityHashDetails(t);if(!o||!o.lookup_pepper||!o.algorithms)throw new Error("Unsupported identity server: bad response");i.pepper=o.lookup_pepper;var s={};if(o.algorithms.includes("sha256"))i.addresses=yield Promise.all(e.map(function(){var f=w(function*(p){var h=p[0].toLowerCase(),m=p[1].toLowerCase(),E=yield YN("".concat(h," ").concat(m," ").concat(i.pepper)),y=Cm(E);return s[y]=p[0],y});return function(p){return f.apply(this,arguments)}}())),i.algorithm="sha256";else if(o.algorithms.includes("none"))i.addresses=e.map(f=>{var p=f[0].toLowerCase(),h=f[1].toLowerCase(),m="".concat(p," ").concat(h);return s[m]=f[0],m}),i.algorithm="none";else throw new Error("Unsupported identity server: unknown hash algorithm");var a=yield n.http.idServerRequest(Z.Post,"/lookup",i,ho.V2,t);if(!(a!=null&&a.mappings))return[];var l=[];for(var c of Object.keys(a.mappings)){var u=a.mappings[c],d=s[c];if(!d)throw new Error("Identity server returned more results than expected");l.push({address:d,mxid:u})}return l})()}lookupThreePid(e,t,n){var i=this;return w(function*(){var o=yield i.identityHashedLookup([[t,e]],n),s=o.find(l=>l.address===t);if(!s)return{};var a={address:t,medium:e,mxid:s.mxid};return a})()}bulkLookupThreePids(e,t){var n=this;return w(function*(){var i=yield n.identityHashedLookup(e.map(l=>[l[1],l[0]]),t),o=[],s=function*(c){var u=e.find(d=>d[1]===c.address);if(!u)throw new Error("Identity sever returned unexpected results");o.push([u[0],c.address,c.mxid])};for(var a of i)yield*s(a);return{threepids:o}})()}getIdentityAccount(e){return this.http.idServerRequest(Z.Get,"/account",void 0,ho.V2,e)}sendToDevice(e,t,n){var i=Se("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:n||this.makeTxnId()}),o={messages:ms(t)},s=new Map;for(var[a,l]of t)s.set(a,Array.from(l.keys()));return this.logger.debug("PUT ".concat(i),s),this.http.authedRequest(Z.Put,i,void 0,o)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(Z.Get,"/thirdparty/protocols").then(e=>{if(!e||typeof e!="object")throw new Error("/thirdparty/protocols did not return an object: ".concat(e));return e})}getThirdpartyLocation(e,t){var n=Se("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(Z.Get,n,t)}getThirdpartyUser(e,t){var n=Se("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(Z.Get,n,t)}getTerms(e,t){var n=this.termsUrlForService(e,t);return this.http.requestOtherUrl(Z.Get,n)}agreeToTerms(e,t,n,i){var o=this.termsUrlForService(e,t),s={Authorization:"Bearer "+n};return this.http.requestOtherUrl(Z.Post,o,{user_accepts:i},{headers:s})}reportEvent(e,t,n,i){var o=Se("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(Z.Post,o,void 0,{score:n,reason:i})}getRoomHierarchy(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,o=arguments.length>4?arguments[4]:void 0,s=Se("/rooms/$roomId/hierarchy",{$roomId:e}),a={suggested_only:String(i),max_depth:n==null?void 0:n.toString(),from:o,limit:t==null?void 0:t.toString()};return this.http.authedRequest(Z.Get,s,a,void 0,{prefix:Pt.V1}).catch(l=>{if(l.errcode==="M_UNRECOGNIZED")return this.http.authedRequest(Z.Get,s,a,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw l})}unstableCreateFileTree(e){var t=this;return w(function*(){var{room_id:n}=yield t.createRoom({name:e,preset:Yw.PrivateChat,power_level_content_override:Cr(Cr({},a7),{},{users:{[t.getUserId()]:100}}),creation_content:{[av]:Ql.Space},initial_state:[{type:xb.name,state_key:Pb.name,content:{[Ob.name]:!0}},{type:V.RoomEncryption,state_key:"",content:{algorithm:bn}}]});return new jk(t,n)})()}unstableGetFileTreeSpace(e){var t,n,i=this.getRoom(e);if((i==null?void 0:i.getMyMembership())!==Be.Join)return null;var o=i.currentState.getStateEvents(V.RoomCreate,""),s=i.currentState.getStateEvents(xb.name,Pb.name);if(!o)throw new Error("Expected single room create event");return!(s!=null&&(t=s.getContent())!==null&&t!==void 0&&t[Ob.name])||((n=o.getContent())===null||n===void 0?void 0:n[av])!==Ql.Space?null:new jk(this,e)}slidingSync(e,t,n){var i={};e.pos&&(i.pos=e.pos,delete e.pos),e.timeout&&(i.timeout=e.timeout,delete e.timeout);var o=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(Z.Post,"/sync",i,e,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:t,localTimeoutMs:o,abortSignal:n})}supportsThreads(){var e;return((e=this.clientOpts)===null||e===void 0?void 0:e.threadSupport)||!1}supportsIntentionalMentions(){return this.canSupport.get(dr.IntentionalMentions)!==lr.Unsupported}getRoomSummary(e,t){var n=this;return w(function*(){var i={prefix:"/_matrix/client/unstable/im.nheko.summary"};try{var o=Se("/summary/$roomid",{$roomid:e});return yield n.http.authedRequest(Z.Get,o,{via:t},void 0,i)}catch(a){if(a instanceof hr&&a.errcode==="M_UNRECOGNIZED"){var s=Se("/rooms/$roomid/summary",{$roomid:e});return yield n.http.authedRequest(Z.Get,s,{via:t},void 0,i)}else throw a}})()}processThreadEvents(e,t,n){e.processThreadedEvents(t,n)}processThreadRoots(e,t,n){this.supportsThreads()&&e.processThreadRoots(t,n)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){t!=null&&t.length&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}whoami(){var e=this;return w(function*(){return e.http.authedRequest(Z.Get,"/account/whoami")})()}timestampToEvent(e,t,n){var i=this;return w(function*(){var o=Se("/rooms/$roomId/timestamp_to_event",{$roomId:e}),s={ts:t.toString(),dir:n};try{return yield i.http.authedRequest(Z.Get,o,s,void 0,{prefix:Pt.V1})}catch(a){if(a.errcode==="M_UNRECOGNIZED"&&(a.httpStatus===400||a.httpStatus===404||a.httpStatus===405))return yield i.http.authedRequest(Z.Get,o,s,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw a}})()}getAuthIssuer(){var e=this;return w(function*(){return e.http.request(Z.Get,"/auth_issuer",void 0,void 0,{prefix:Pt.Unstable+"/org.matrix.msc2965"})})()}}v(qc,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY");function Hk(r){return Object.fromEntries(Object.entries(r).map(e=>{var[t,n]=e;return["".concat(Wi,".").concat(t),n]}))}function eL(r,e){var t,n=r.getUserId(),i=e.getId(),o=r.getRoom(e.getRoomId());if(!(!o||!n||!i)){if(!o.findEventById(i)){b.info("Decrypted event ".concat(e.getId()," is not in room ").concat(o.roomId,": ignoring"));return}var s=!!e.threadRootId&&!e.isThreadRoot,a;if(s){var l=o.getThread(e.threadRootId);a=l?l.hasUserReadEvent(n,i):!0}else a=o.hasUserReadEvent(n,i);if(!a){var c=r.getPushActionsForEvent(e,!0),u=!!(c!=null&&(t=c.tweaks)!==null&&t!==void 0&&t.highlight);if(u){var d=o.getUnreadCountForEventContext(it.Highlight,e)+1;s?o.setThreadUnreadNotificationCount(e.threadRootId,it.Highlight,d):o.setUnreadNotificationCount(it.Highlight,d)}var f=!!(c!=null&&c.notify);if(f){var p=o.getUnreadCountForEventContext(it.Total,e)+1;s?o.setThreadUnreadNotificationCount(e.threadRootId,it.Total,p):o.setUnreadNotificationCount(it.Total,p)}}}}function kc(r){return qd(r)?Tf:r.threadRootId}function qd(r){if(!r.threadRootId||r.isThreadRoot)return!0;if(!r.isRelation())return b.warn("Event is not a relation or a thread root, but still has a threadRootId! id=".concat(r.getId())),!0;if(r.isRelation(vt.name))return!1;var e=r.relationEventId===r.threadRootId;return e}function zk(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Yk(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?zk(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):zk(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Qr=function(r){return r.New="Thread.new",r.Update="Thread.update",r.NewReply="Thread.newReply",r.ViewThread="Thread.viewThread",r.Delete="Thread.delete",r}({}),Vr=function(r){return r[r.None=0]="None",r[r.Experimental=1]="Experimental",r[r.Stable=2]="Stable",r}({});function lp(r,e){return r?Vr.Stable:e?Vr.Experimental:Vr.None}class Et extends tN{constructor(e,t,n){var i,o;if(super(),i=this,this.id=e,this.rootEvent=t,v(this,"timelineSet",void 0),v(this,"_currentUserParticipated",!1),v(this,"reEmitter",void 0),v(this,"lastEvent",void 0),v(this,"replyCount",0),v(this,"lastPendingEvent",void 0),v(this,"pendingReplyCount",0),v(this,"room",void 0),v(this,"client",void 0),v(this,"pendingEventOrdering",void 0),v(this,"processRootEventPromise",void 0),v(this,"initialEventsFetched",!Et.hasServerSideSupport),v(this,"initalEventFetchProm",void 0),v(this,"replayEvents",[]),v(this,"onTimelineReset",w(function*(){yield i.processRootEventPromise,i.processRootEventPromise=void 0})),v(this,"onBeforeRedaction",(s,a)=>{s!=null&&s.isRelation(vt.name)&&this.room.eventShouldLiveIn(s).threadId===this.id&&s.getId()!==this.id&&!a.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(Qr.Update,this))}),v(this,"onRedaction",function(){var s=w(function*(a,l,c){if(c===i.id)if(i.replyCount<=0){for(var u of i.timeline)i.clearEventMetadata(u);i.lastEvent=i.rootEvent,i._currentUserParticipated=!1,i.emit(Qr.Delete,i)}else{var d;((d=i.lastEvent)===null||d===void 0?void 0:d.getId())===a.getAssociatedId()&&(yield i.processRootEventPromise,i.processRootEventPromise=void 0),yield i.updateThreadMetadata()}});return function(a,l,c){return s.apply(this,arguments)}}()),v(this,"onTimelineEvent",(s,a,l)=>{if(!l){var c=s.getSender();c&&a&&this.shouldSendLocalEchoReceipt(c,s)&&a.addLocalEchoReceipt(c,s,Xr.Read),s.getId()!==this.id&&s.isRelation(vt.name)&&this.replyCount++}this.onEcho(s,l??!1)}),v(this,"onLocalEcho",s=>{this.onEcho(s,!1)}),v(this,"onEcho",function(){var s=w(function*(a,l){a.threadRootId===i.id&&i.lastEvent!==a&&(yield i.updateThreadMetadata(),a.isRelation(vt.name)&&(l||(i.lastEvent=void 0,i.emit(Qr.NewReply,i,a))))});return function(a,l){return s.apply(this,arguments)}}()),this.setMaxListeners(1e3),!(n!=null&&n.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=n.room,this.client=n.client,this.pendingEventOrdering=(o=n.pendingEventOrdering)!==null&&o!==void 0?o:Cc.Chronological,this.timelineSet=new Bl(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new Vc(this),this.reEmitter.reEmit(this.timelineSet,[pe.Timeline,pe.TimelineReset]),this.room.on(ot.BeforeRedaction,this.onBeforeRedaction),this.room.on(pe.Redaction,this.onRedaction),this.room.on(pe.LocalEchoUpdated,this.onLocalEcho),this.room.on(pe.TimelineReset,this.onTimelineReset),this.timelineSet.on(pe.Timeline,this.onTimelineEvent),this.processReceipts(n.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}fetchRootEvent(){var e=this;return w(function*(){try{var t=yield e.client.fetchRoomEvent(e.roomId,e.id),n=e.client.getEventMapper();e.rootEvent=n(t)}catch(i){b.error("Failed to fetch thread root to construct thread with",i)}yield e.processEvent(e.rootEvent)})()}static setServerSideSupport(e){Et.hasServerSideSupport=e,e!==Vr.Stable&&(ic.setPreferUnstable(!0),oc.setPreferUnstable(!0),vt.setPreferUnstable(!0))}static setServerSideListSupport(e){Et.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){Et.hasServerSideFwdPaginationSupport=e}shouldSendLocalEchoReceipt(e,t){var n,i=(n=this.client.canSupport.get(dr.RelationsRecursion))!==null&&n!==void 0?n:lr.Unsupported;if(i===lr.Unsupported){var o,s=(o=this.getReadReceiptForUserId(e))===null||o===void 0?void 0:o.eventId;if(s){var a=this.findEventById(s);if(a&&a.getTs()>t.getTs())return!1}}return!0}get roomState(){return this.room.getLiveTimeline().getState(we.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState})}insertEventIntoTimeline(e){var t=e.getId();t&&(this.findEventById(t)||this.timelineSet.insertEventIntoTimeline(e,this.liveTimeline,this.roomState))}addEvents(e,t){e.forEach(n=>this.addEvent(n,t,!1)),this.updateThreadMetadata()}addEvent(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;this.setEventMetadata(e);var i=this.lastReply(),o=!i||e.localTimestamp>=i.localTimestamp;if(!Et.hasServerSideSupport)this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e);else if(e.isRelation(Nt.Annotation)||e.isRelation(Nt.Replace)){this.addRelatedThreadEvent(e,t);return}else!t&&o?(this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e)):t?this.addEventToTimeline(e,t):this.insertEventIntoTimeline(e);e.getId()!==this.id&&e.isRelation(vt.name)&&!t&&o&&(this.lastEvent=void 0),n&&(this.emit(Qr.NewReply,this,e),this.updateThreadMetadata())}addRelatedThreadEvent(e,t){var n,i;if(this.initialEventsFetched){var s,a=(s=this.client.canSupport.get(dr.RelationsRecursion))!==null&&s!==void 0?s:lr.Unsupported;a===lr.Unsupported?this.insertEventIntoTimeline(e):this.addEventToTimeline(e,t)}else{var o;(o=this.replayEvents)===null||o===void 0||o.push(e)}(n=this.timelineSet.relations)===null||n===void 0||n.aggregateParentEvent(e),(i=this.timelineSet.relations)===null||i===void 0||i.aggregateChildEvent(e,this.timelineSet)}processEvent(e){var t=this;return w(function*(){e&&(t.setEventMetadata(e),yield t.fetchEditsWhereNeeded(e))})()}processReceipts(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];for(var{eventId:t,receiptType:n,userId:i,receipt:o,synthetic:s}of e)this.addReceiptToStructure(t,n,i,o,s)}getRootEventBundledRelationship(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.rootEvent;return e==null?void 0:e.getServerAggregatedRelation(vt.name)}processRootEvent(){var e=this;return w(function*(){var t=e.getRootEventBundledRelationship();if(Et.hasServerSideSupport&&t){e.replyCount=t.count,e._currentUserParticipated=!!t.current_user_participated;var n=e.client.getEventMapper();e.lastEvent=n(Yk(Yk({},t.latest_event),{},{room_id:e.roomId})),e.updatePendingReplyCount(),yield e.processEvent(e.lastEvent)}})()}updatePendingReplyCount(){var e=this.pendingEventOrdering===Cc.Detached?this.room.getPendingEvents():this.events,t=e.filter(n=>{var i;return n.threadRootId===this.id&&n.isRelation(vt.name)&&n.status!==null&&n.getId()!==((i=this.lastEvent)===null||i===void 0?void 0:i.getId())});this.lastPendingEvent=t.length?t[t.length-1]:void 0,this.pendingReplyCount=t.length}resetLiveTimeline(e,t){var n=this;return w(function*(){var i=n.liveTimeline;n.timelineSet.resetLiveTimeline(e??void 0,t??void 0);var o=n.liveTimeline,s,a;if(e){var l=yield n.client.createMessagesRequest(n.roomId,e,1,Ge.Forward);s=l.end}if(t){var c=yield n.client.createMessagesRequest(n.roomId,t,1,Ge.Backward);a=c.start}if(t&&i.getPaginationToken(Ge.Forward)===t){var u;i.setPaginationToken((u=a)!==null&&u!==void 0?u:null,Ge.Forward)}if(e&&o.getPaginationToken(Ge.Backward)===e){var d;o.setPaginationToken((d=s)!==null&&d!==void 0?d:null,Ge.Backward)}})()}updateThreadFromRootEvent(){var e=this;return w(function*(){Et.hasServerSideSupport&&(!e.initialEventsFetched&&!e.lastEvent&&(yield e.processRootEvent()),yield e.fetchRootEvent()),yield e.processRootEvent()})()}updateThreadMetadata(){var e=this;return w(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,e.liveTimeline,null),e.liveTimeline.setPaginationToken(null,Ge.Backward)):(e.initalEventFetchProm=e.client.paginateEventTimeline(e.liveTimeline,{backwards:!0}),yield e.initalEventFetchProm),e.initialEventsFetched=!0;for(var t of e.replayEvents)e.addEvent(t,!1);e.replayEvents=null,e.emit(pe.TimelineReset,e.room,e.timelineSet,!0)}catch(n){b.error("Failed to load start of newly created thread: ",n),e.initialEventsFetched=!1}e.emit(Qr.Update,e)})()}fetchEditsWhereNeeded(){var e=arguments,t=this;return w(function*(){var n,i=(n=t.client.canSupport.get(dr.RelationsRecursion))!==null&&n!==void 0?n:lr.Unsupported;if(i===lr.Unsupported){for(var o=e.length,s=new Array(o),a=0;a<o;a++)s[a]=e[a];return Promise.all(s.filter(x7).map(function(){var l=w(function*(c){try{var u=yield t.client.relations(t.roomId,c.getId(),Nt.Replace,c.getType(),{limit:1});if(u.events.length){var d=u.events[0];c.makeReplaced(d),t.insertEventIntoTimeline(d)}}catch(f){b.error("Failed to load edits for encrypted thread event",f)}});return function(c){return l.apply(this,arguments)}}()))}})()}setEventMetadata(e){e&&(we.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){if(e){var t;e.setThread(void 0),(t=e.event)===null||t===void 0||(t=t.unsigned)===null||t===void 0||(t=t["m.relations"])===null||t===void 0||delete t[vt.name]}}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:i=>i.isRelation(vt.name),t=this.timeline.length-1;t>=0;t--){var n=this.timeline[t];if(e(n))return n}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,t;return(e=(t=this.lastPendingEvent)!==null&&t!==void 0?t:this.lastEvent)!==null&&e!==void 0?e:this.lastReply()}get timeline(){return this.events}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof pr}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(e,t){throw new Error("Unsupported function on the thread model")}getEventReadUpTo(e,t){var n=e===this.client.getUserId(),i=this.timeline[this.timeline.length-1];if(n&&i){var o=i.getTs()<this.room.getOldestThreadedReceiptTs(),s=i.getId();if(o&&s)return s}var a=super.getEventReadUpTo(e,t);if(i){var l=this.room.getLastUnthreadedReceiptFor(e);if(!l)return a;for(var c=((u=this.timeline)===null||u===void 0?void 0:u.length)-1;c>=0;--c){var u,d,f=this.timeline[c];if(f.getId()===a)return a;if(f.getTs()<l.ts)return(d=f.getId())!==null&&d!==void 0?d:a}}return a}hasUserReadEvent(e,t){if(e===this.client.getUserId()){var n,i,o,s,a,l,c=((n=(i=this.lastReply())===null||i===void 0?void 0:i.getTs())!==null&&n!==void 0?n:0)<this.room.getOldestThreadedReceiptTs(),u=(o=(s=this.room.getLastUnthreadedReceiptFor(e))===null||s===void 0?void 0:s.ts)!==null&&o!==void 0?o:0,d=((a=this===null||this===void 0||(l=this.lastReply())===null||l===void 0?void 0:l.getTs())!==null&&a!==void 0?a:0)<u;if(c||d)return!0}return this.room.hasUserReadEvent(e,t)}setUnread(e,t){return this.room.setThreadUnreadNotificationCount(this.id,e,t)}getLastUnthreadedReceiptFor(e){return this.room.getLastUnthreadedReceiptFor(e)}}v(Et,"hasServerSideSupport",Vr.None);v(Et,"hasServerSideListSupport",Vr.None);v(Et,"hasServerSideFwdPaginationSupport",Vr.None);function x7(r){return r.isEncrypted()&&(r.isRelation(vt.name)||r.isThreadRoot)}var ic=new pm("related_by_senders","io.element.relation_senders"),oc=new pm("related_by_rel_types","io.element.relation_types"),vt=new pm("m.thread","io.element.thread"),di=function(r){return r[r.My=0]="My",r[r.All=1]="All",r}({});function tL(r){switch(r){case di.My:return"participated";default:return"all"}}var Jk=Object.freeze({visible:!0}),ot=function(r){return r.Decrypted="Event.decrypted",r.BeforeRedaction="Event.beforeRedaction",r.VisibilityChange="Event.visibilityChange",r.LocalEventIdReplaced="Event.localEventIdReplaced",r.Status="Event.status",r.Replaced="Event.replaced",r.RelationsCreated="Event.relationsCreated",r}({});class pr extends Tt{constructor(){var e,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.event=t,v(this,"pushDetails",{}),v(this,"_replacingEvent",null),v(this,"_localRedactionEvent",null),v(this,"_isCancelled",!1),v(this,"clearEvent",void 0),v(this,"visibility",Jk),v(this,"_hasCachedExtEv",!1),v(this,"_cachedExtEv",void 0),v(this,"_decryptionFailureReason",null),v(this,"senderCurve25519Key",null),v(this,"claimedEd25519Key",null),v(this,"forwardingCurve25519KeyChain",[]),v(this,"untrusted",null),v(this,"decryptionPromise",null),v(this,"retryDecryption",!1),v(this,"txnId",void 0),v(this,"thread",void 0),v(this,"threadId",void 0),v(this,"localTimestamp",void 0),v(this,"sender",null),v(this,"target",null),v(this,"status",null),v(this,"error",null),v(this,"forwardLooking",!0),v(this,"verificationRequest",void 0),v(this,"reEmitter",void 0),["state_key","type","sender","room_id","membership"].forEach(i=>{typeof t[i]=="string"&&(t[i]=Zg(t[i]))}),["membership","avatar_url","displayname"].forEach(i=>{var o;typeof((o=t.content)===null||o===void 0?void 0:o[i])=="string"&&(t.content[i]=Zg(t.content[i]))}),["rel_type"].forEach(i=>{var o;typeof((o=t.content)===null||o===void 0||(o=o["m.relates_to"])===null||o===void 0?void 0:o[i])=="string"&&(t.content["m.relates_to"][i]=Zg(t.content["m.relates_to"][i]))}),this.txnId=t.txn_id;var n=this.getAge();this.localTimestamp=n!==void 0?Date.now()-n:(e=this.getTs())!==null&&e!==void 0?e:Date.now(),this.reEmitter=new Vc(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=ln.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){var e=Object.assign({},this.getContent());if(this.getWireType()===V.RoomMessageEncrypted)for(var[t,n]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||e[t]===void 0&&(e[t]=n);return Object.assign({},this.event,this.clearEvent,{content:e})}getId(){return this.event.event_id}getSender(){return this.event.sender}getType(){return this.clearEvent?this.clearEvent.type:this.event.type}getWireType(){return this.event.type}getRoomId(){return this.event.room_id}getTs(){return this.event.origin_server_ts}getDate(){return this.event.origin_server_ts?new Date(this.event.origin_server_ts):null}getDetails(){var e=this.getRoomId();if(e){var t;return"id=".concat(this.getId()," type=").concat(this.getWireType()," sender=").concat(this.getSender()," room=").concat(e," ts=").concat((t=this.getDate())===null||t===void 0?void 0:t.toISOString())}else{var n=this.getContent()[tn];return"msgid=".concat(n," type=").concat(this.getWireType()," sender=").concat(this.getSender())}}getOriginalContent(){return this._localRedactionEvent?{}:this.clearEvent?this.clearEvent.content||{}:this.event.content||{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?this._replacingEvent.getContent()["m.new_content"]||{}:this.getOriginalContent()}getWireContent(){return this.event.content||{}}get threadRootId(){var e;if(!this.isState()){var t=(e=this.getWireContent())===null||e===void 0?void 0:e["m.relates_to"];if((t==null?void 0:t.rel_type)===vt.name)return t.event_id;if(this.thread)return this.thread.id;if(this.threadId!==void 0)return this.threadId;var n=this.getUnsigned();if(typeof n[lv.name]=="string")return n[lv.name]}}get isThreadRoot(){if(this.isState())return!1;var e=this.getServerAggregatedRelation(vt.name);return!!e||this.threadRootId===this.getId()}get replyEventId(){var e;return(e=this.getWireContent()["m.relates_to"])===null||e===void 0||(e=e["m.in_reply_to"])===null||e===void 0?void 0:e.event_id}get relationEventId(){var e;return(e=this.getWireContent())===null||e===void 0||(e=e["m.relates_to"])===null||e===void 0?void 0:e.event_id}getPrevContent(){return this.getUnsigned().prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return this.event.state_key!==void 0}getMembershipAtEvent(){var e=this.getUnsigned();return jD.findIn(e)}makeEncrypted(e,t,n,i){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=n,this.claimedEd25519Key=i}isBeingDecrypted(){return this.decryptionPromise!=null}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){return this._decryptionFailureReason!==null}get decryptionFailureReason(){return this._decryptionFailureReason}get isEncryptedDisabledForUnverifiedDevices(){return this.decryptionFailureReason===Lt.MEGOLM_KEY_WITHHELD_FOR_UNVERIFIED_DEVICE}shouldAttemptDecryption(){return!(this.isRedacted()||this.isBeingDecrypted()||this.clearEvent||!this.isEncrypted())}attemptDecryption(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};if(!n.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");var o=n.clearEvent&&!n.isDecryptionFailure(),s=i.forceRedecryptIfUntrusted&&n.isKeySourceUntrusted();if(o&&!s)throw new Error("Attempt to decrypt event which has already been decrypted");return n.decryptionPromise?(b.log("Event ".concat(n.getId()," already being decrypted; queueing a retry")),n.retryDecryption=!0,n.decryptionPromise):(n.decryptionPromise=n.decryptionLoop(e,i),n.decryptionPromise)})()}cancelAndResendKeyRequest(e,t){var n=this.getWireContent();return e.requestRoomKey({algorithm:n.algorithm,room_id:this.getRoomId(),session_id:n.session_id,sender_key:n.sender_key},this.getKeyRequestRecipients(t),!0)}getKeyRequestRecipients(e){var t=[{userId:e,deviceId:"*"}];return t}decryptionLoop(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:{};for(yield Promise.resolve();;){n.retryDecryption=!1;var o=void 0;try{var s=yield e.decryptEvent(n);i.isRetry===!0&&b.info("Decrypted event on retry (".concat(n.getDetails(),")")),n.setClearData(s),n._decryptionFailureReason=null}catch(l){var a=l instanceof cr?l.detailedString:String(l);if(o=l,n.retryDecryption){b.log("Error decrypting event (".concat(n.getDetails(),"), but retrying: ").concat(a));continue}b.warn("Error decrypting event (".concat(n.getDetails(),"): ").concat(a)),n.setClearDataForDecryptionFailure(String(l)),n._decryptionFailureReason=l instanceof cr?l.code:Lt.UNKNOWN_ERROR}n.decryptionPromise=null,n.retryDecryption=!1,n.setPushDetails(),i.emit!==!1&&n.emit(ot.Decrypted,n,o);return}})()}setClearData(e){var t,n;this.clearEvent=e.clearEvent,this.senderCurve25519Key=(t=e.senderCurve25519Key)!==null&&t!==void 0?t:null,this.claimedEd25519Key=(n=e.claimedEd25519Key)!==null&&n!==void 0?n:null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.invalidateExtensibleEvent()}setClearDataForDecryptionFailure(e){this.clearEvent={type:V.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: ".concat(e," **")}},this.senderCurve25519Key=null,this.claimedEd25519Key=null,this.forwardingCurve25519KeyChain=[],this.untrusted=!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===V.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(ot.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var t,n,i=(t=e==null?void 0:e.visible)!==null&&t!==void 0?t:!0,o=(n=e==null?void 0:e.reason)!==null&&n!==void 0?n:null,s=!1;(this.visibility.visible!==i||!this.visibility.visible&&this.visibility.reason!==o)&&(s=!0),s&&(i?this.visibility=Jk:this.visibility=Object.freeze({visible:!1,reason:o}),this.emit(ot.VisibilityChange,this,i))}messageVisibility(){return this.visibility}makeRedacted(e,t){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(ot.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(var n in this.event)this.event.hasOwnProperty(n)&&!O7.has(n)&&delete this.event[n];this.isEncrypted()&&(this.clearEvent=void 0);var i=this.getType()in Xk?Xk[this.getType()]:{},o=this.getContent();for(var s in o)o.hasOwnProperty(s)&&!i[s]&&delete o[s];!this.isThreadRoot&&this.threadRootId&&this.threadRootId!==this.getId()&&(this.moveAllRelatedToMainTimeline(t),e.moveToMainTimeline(t)),this.invalidateExtensibleEvent()}moveAllRelatedToMainTimeline(e){var t=this.thread;if(this.moveToMainTimeline(e),t)for(var n of t.events){var i;((i=n.getRelation())===null||i===void 0?void 0:i.event_id)===this.getId()&&n.moveAllRelatedToMainTimeline(e)}}moveToMainTimeline(e){var t;(t=this.thread)===null||t===void 0||t.timelineSet.removeEvent(this.getId()),this.setThread(void 0);var n=e.getLiveTimeline();n.getTimelineSet().insertEventIntoTimeline(this,n,n.getState(we.FORWARDS))}isRedacted(){return!!this.getUnsigned().redacted_because}isRedaction(){return this.getType()===V.RoomRedaction}asVisibilityChange(){if(!Ta.matches(this.getType()))return null;var e=this.getRelation();if(!e||e.rel_type!="m.reference")return null;var t=e.event_id;if(!t)return null;var n=this.getWireContent(),i=!!n.visible,o=n.reason;return o&&typeof o!="string"?null:{visible:i,reason:o,eventId:t}}isVisibilityEvent(){return Ta.matches(this.getType())}getRedactionEvent(){var e,t;if(!this.isRedacted())return null;if((e=this.clearEvent)!==null&&e!==void 0&&e.unsigned){var n,i;return(n=(i=this.clearEvent)===null||i===void 0?void 0:i.unsigned.redacted_because)!==null&&n!==void 0?n:null}else return(t=this.event.unsigned)!==null&&t!==void 0&&t.redacted_because?this.event.unsigned.redacted_because:{}}getPushActions(){return this.pushDetails.actions||null}getPushDetails(){return this.pushDetails}setPushDetails(e,t){this.pushDetails={actions:e,rule:t}}handleRemoteEcho(e){var t=this.getUnsigned(),n=this.getId();this.event=e,t.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=t.redacted_because),this.setStatus(null),this.getId()!==n&&this.emit(ot.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(ot.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(ot.LocalEventIdReplaced,this)}isRelation(e){var t,n=(t=this.getWireContent())===null||t===void 0?void 0:t["m.relates_to"];return this.isState()&&(n!=null&&n.rel_type)&&[Nt.Replace,Nt.Thread].includes(n.rel_type)?!1:!!(n!=null&&n.rel_type&&n.event_id&&(!e||n.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(ot.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return(t=this.getUnsigned()["m.relations"])===null||t===void 0?void 0:t[e]}replacingEventId(){var e=this.getServerAggregatedRelation(Nt.Replace);if(e)return e.event_id;if(this._replacingEvent)return this._replacingEvent.getId()}replacingEvent(){return this._replacingEvent}replacingEventDate(){var e=this.getServerAggregatedRelation(Nt.Replace);if(e){var t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent){var n;return(n=this._replacingEvent.getDate())!==null&&n!==void 0?n:void 0}}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){var e=this.getRelation();if(this.replyEventId)return this.replyEventId;if(e)return e.event_id;if(this.isRedaction())return this.event.redacts}hasAssociation(){return!!this.getAssociatedId()}updateAssociatedId(e){var t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){var e=new pr(JSON.parse(JSON.stringify(this.event)));for(var[t,n]of Object.entries(this))t!=="event"&&(e[t]=n);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;var t=Eb(this.event),n=Eb(e.event);return JSON.stringify(t)===JSON.stringify(n)}toJSON(){var e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setVerificationRequest(e){this.verificationRequest=e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}setThread(e){this.isState()||(this.thread&&this.reEmitter.stopReEmitting(this.thread,[Qr.Update]),this.thread=e,this.setThreadId(e==null?void 0:e.id),e&&this.reEmitter.reEmit(e,[Qr.Update]))}getThread(){return this.thread}setThreadId(e){this.threadId=e}}var O7=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),Xk={[V.RoomMember]:{membership:1},[V.RoomJoinRules]:{join_rule:1},[V.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}},xn=function(r){return r[r.NotStarted=0]="NotStarted",r[r.InProgress=1]="InProgress",r[r.Finished=2]="Finished",r}(xn||{}),Me=function(r){return r.Events="RoomState.events",r.Members="RoomState.members",r.NewMember="RoomState.newMember",r.Update="RoomState.update",r.BeaconLiveness="RoomState.BeaconLiveness",r.Marker="RoomState.Marker",r}({});class Gd extends Tt{constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{status:xn.NotStarted},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;super(),this.roomId=e,this.oobMemberFlags=t,this.isStartTimelineState=n,v(this,"reEmitter",new Vc(this)),v(this,"sentinels",{}),v(this,"displayNameToUserIds",new Map),v(this,"userIdsToDisplayNames",{}),v(this,"tokenToInvite",{}),v(this,"joinedMemberCount",null),v(this,"summaryJoinedMemberCount",null),v(this,"invitedMemberCount",null),v(this,"summaryInvitedMemberCount",null),v(this,"modified",-1),v(this,"members",{}),v(this,"events",new Map),v(this,"paginationToken",null),v(this,"beacons",new Map),v(this,"_liveBeaconIds",[]),this.updateModifiedTime()}getJoinedMemberCount(){return this.summaryJoinedMemberCount!==null?this.summaryJoinedMemberCount:(this.joinedMemberCount===null&&(this.joinedMemberCount=this.getMembers().reduce((e,t)=>t.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,t)=>t.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(t=>!e.includes(t.userId))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;var t=this.sentinels[e];if(t===void 0){t=new cv(this.roomId,e);var n=this.members[e];n!=null&&n.events.member&&t.setMembershipEvent(n.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return t===void 0?[]:null;if(t===void 0)return Array.from(this.events.get(e).values());var n=this.events.get(e).get(t);return n||null}get hasLiveBeacons(){var e;return!!((e=this.liveBeaconIds)!==null&&e!==void 0&&e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){var e=new Gd(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=xn.NotStarted,Array.from(this.events.values()).forEach(n=>{e.setStateEvents(Array.from(n.values()))}),this.oobMemberFlags.status=t,this.summaryInvitedMemberCount!==null&&e.setInvitedMemberCount(this.getInvitedMemberCount()),this.summaryJoinedMemberCount!==null&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==xn.Finished&&this.getMembers().forEach(n=>{if(n.isOutOfBand()){var i;(i=e.getMember(n.userId))===null||i===void 0||i.markOutOfBand()}}),e}setUnknownStateEvents(e){var t=e.filter(n=>!this.events.has(n.getType())||!this.events.get(n.getType()).has(n.getStateKey()));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach(n=>{var i,o;if(!(n.getRoomId()!==this.roomId||!n.isState())){xw.matches(n.getType())&&this.setBeacon(n);var s=this.getStateEventMatching(n),a=s==null||(i=s.event.unsigned)===null||i===void 0?void 0:i.replaces_state,l=s==null?void 0:s.event.event_id,c=(o=n.event.unsigned)===null||o===void 0?void 0:o.replaces_state,u=n.event.event_id;if(this.isStartTimelineState){if(c&&l&&c===l)return}else if(a&&u&&a===u)return;if(this.setStateEvent(n),n.getType()===V.RoomMember){var d;this.updateDisplayNameCache(n.getStateKey(),(d=n.getContent().displayname)!==null&&d!==void 0?d:""),this.updateThirdPartyTokenCache(n)}this.emit(Me.Events,n,this,s)}}),this.onBeaconLivenessChange(),e.forEach(n=>{if(!(n.getRoomId()!==this.roomId||!n.isState()))if(n.getType()===V.RoomMember){var i=n.getStateKey();(n.getContent().membership===Be.Leave||n.getContent().membership===Be.Ban)&&(n.getContent().avatar_url=n.getContent().avatar_url||n.getPrevContent().avatar_url,n.getContent().displayname=n.getContent().displayname||n.getPrevContent().displayname);var o=this.getOrCreateMember(i,n);o.setMembershipEvent(n,this),this.updateMember(o),this.emit(Me.Members,n,this,o)}else if(n.getType()===V.RoomPowerLevels){if(n.getStateKey()!=="")return;var s=Object.values(this.members);s.forEach(a=>{var l=a.getLastModifiedTime();a.setPowerLevelEvent(n),l!==a.getLastModifiedTime()&&this.emit(Me.Members,n,this,a)}),this.sentinels={}}else ND.matches(n.getType())&&this.emit(Me.Marker,n,t)}),this.emit(Me.Update,this)}processBeaconEvents(e,t){var n=this;return w(function*(){if(!(!e.length||!n.beacons.size)){var i=[...n.beacons.values()].reduce((c,u)=>(c[u.beaconInfoId]=u,c),{}),o=(c,u)=>{if(Ib.matches(u.getType())){var d=i[c];d&&d.addLocations([u])}},s=function*(u){var d,f=(d=u.getRelation())===null||d===void 0?void 0:d.event_id;if(!f||!i[f])return{v:void 0};if(!Ib.matches(u.getType())&&!u.isEncrypted())return{v:void 0};try{yield t.decryptEventIfNeeded(u),o(f,u)}catch{u.isDecryptionFailure()&&u.once(ot.Decrypted,w(function*(){o(f,u)}))}},a;for(var l of e)if(a=yield*s(l),a)return a.v}})()}getOrCreateMember(e,t){var n=this.members[e];return n||(n=new cv(this.roomId,e),this.members[e]=n,this.emit(Me.NewMember,t,this,n)),n}setStateEvent(e){this.events.has(e.getType())||this.events.set(e.getType(),new Map),this.events.get(e.getType()).set(e.getStateKey(),e)}setBeacon(e){var t=uv(e);if(this.beacons.has(t)){var n=this.beacons.get(t);if(e.isRedacted()){var i;n.beaconInfoId===((i=e.getRedactionEvent())===null||i===void 0?void 0:i.redacts)&&(n.destroy(),this.beacons.delete(t));return}return n.update(e)}if(!e.isRedacted()){var o=new ZD(e);this.reEmitter.reEmit(o,[kt.New,kt.Update,kt.Destroy,kt.LivenessChange]),this.emit(kt.New,e,o),o.on(kt.LivenessChange,this.onBeaconLivenessChange.bind(this)),o.on(kt.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(o.identifier,o)}}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter(e=>e.isLive).map(e=>e.identifier),this.emit(Me.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,n;return(t=(n=this.events.get(e.getType()))===null||n===void 0?void 0:n.get(e.getStateKey()))!==null&&t!==void 0?t:null}updateMember(e){var t=this.getStateEvents(V.RoomPowerLevels,"");t&&e.setPowerLevelEvent(t),delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===xn.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===xn.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===xn.NotStarted&&(this.oobMemberFlags.status=xn.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===xn.InProgress&&(this.oobMemberFlags.status=xn.NotStarted)}clearOutOfBandMembers(){var e=0;Object.keys(this.members).forEach(t=>{var n=this.members[t];n.isOutOfBand()&&(++e,delete this.members[t])}),b.log("LL: RoomState removed ".concat(e," members...")),this.oobMemberFlags.status=xn.NotStarted}setOutOfBandMembers(e){b.log("LL: RoomState about to set ".concat(e.length," OOB members ...")),this.oobMemberFlags.status===xn.InProgress&&(b.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=xn.Finished,e.forEach(t=>this.setOutOfBandMember(t)),this.emit(Me.Update,this))}setOutOfBandMember(e){if(e.getType()===V.RoomMember){var t=e.getStateKey(),n=this.getMember(t);if(!(n&&!n.isOutOfBand())){var i=this.getOrCreateMember(t,e);i.setMembershipEvent(e,this),i.markOutOfBand(),this.updateDisplayNameCache(i.userId,i.name),this.setStateEvent(e),this.updateMember(i),this.emit(Me.Members,e,this,i)}}}setTypingEvent(e){Object.values(this.members).forEach(function(t){t.setTypingEvent(e)})}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return(t=this.displayNameToUserIds.get(ka(e)))!==null&&t!==void 0?t:[]}maySendRedactionForEvent(e,t){var n=this.getMember(t);if(!n||n.membership===Be.Leave||e.status||e.isRedacted())return!1;var i=this.maySendEvent(V.RoomRedaction,t);return i?e.getSender()===t?!0:this.hasSufficientPowerLevelFor("redact",n.powerLevel):!1}hasSufficientPowerLevelFor(e,t){var n=this.getStateEvents(V.RoomPowerLevels,""),i={};n&&(i=n.getContent());var o=50;return yC(i[e])&&(o=i[e]),t>=o}maySendMessage(e){return this.maySendEventOfType(V.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return t.isGuest()||!t.credentials.userId?!1:this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,n){var i=this.getStateEvents(V.RoomPowerLevels,""),o,s={},a=0,l=0,c=0;if(i){o=i.getContent(),s=o.events||{},Number.isSafeInteger(o.state_default)?a=o.state_default:a=50;var u=o.users&&o.users[t];Number.isSafeInteger(u)?c=u:Number.isSafeInteger(o.users_default)&&(c=o.users_default),Number.isSafeInteger(o.events_default)&&(l=o.events_default)}var d=n?a:l;return Number.isSafeInteger(s[e])&&(d=s[e]),c>=d}mayTriggerNotifOfType(e,t){var n=this.getMember(t);if(!n)return!1;var i=this.getStateEvents(V.RoomPowerLevels,""),o=50;return i&&i.getContent()&&i.getContent().notifications&&yC(i.getContent().notifications[e])&&(o=i.getContent().notifications[e]),n.powerLevel>=o}getJoinRule(){var e,t=this.getStateEvents(V.RoomJoinRules,""),n=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return n.join_rule||WN.Invite}getHistoryVisibility(){var e,t=this.getStateEvents(V.RoomHistoryVisibility,""),n=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return n.history_visibility||Jw.Shared}getGuestAccess(){var e,t=this.getStateEvents(V.RoomGuestAccess,""),n=(e=t==null?void 0:t.getContent())!==null&&e!==void 0?e:{};return n.guest_access||gv.Forbidden}findPredecessor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(e){var t=this.getStateEvents(V.RoomPredecessor,"");if(t){var n=t.getContent(),i=n.predecessor_room_id,o=n.last_known_event_id;typeof o!="string"&&(o=void 0);var s=n.via_servers;if(Array.isArray(s)||(s=void 0),typeof i=="string")return{roomId:i,eventId:o,viaServers:s}}}var a=this.getStateEvents(V.RoomCreate,"");if(a){var l=a.getContent().predecessor;if(l){var c=l.room_id;if(typeof c=="string"){var u=l.event_id;return(typeof u!="string"||u==="")&&(u=void 0),{roomId:c,eventId:u}}}}return null}updateThirdPartyTokenCache(e){if(e.getContent().third_party_invite){var t=(e.getContent().third_party_invite.signed||{}).token;if(t){var n=this.getStateEvents(V.RoomThirdPartyInvite,t);n&&(this.tokenToInvite[t]=e)}}}updateDisplayNameCache(e,t){var n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){var i=ka(n),o=this.displayNameToUserIds.get(i);if(o){var s=o.filter(u=>u!==e);this.displayNameToUserIds.set(i,s)}}this.userIdsToDisplayNames[e]=t;var a=t&&ka(t);if(a){var l,c=(l=this.displayNameToUserIds.get(a))!==null&&l!==void 0?l:[];c.push(e),this.displayNameToUserIds.set(a,c)}}}function Qk(r){var e=typeof r=="string"&&!!r&&r!=="undefined"&&r!=="null";return e||typeof r=="number"}class Mm{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};v(this,"rooms",{}),v(this,"users",{}),v(this,"syncToken",null),v(this,"filters",new Gt(()=>new Map)),v(this,"accountData",new Map),v(this,"localStorage",void 0),v(this,"oobMembers",new Map),v(this,"pendingEvents",{}),v(this,"clientOptions",void 0),v(this,"pendingToDeviceBatches",[]),v(this,"nextToDeviceBatchId",0),v(this,"createUser",void 0),v(this,"onRoomMember",(t,n,i)=>{var o;if(i.membership!==Be.Invite){var s=this.users[i.userId]||((o=this.createUser)===null||o===void 0?void 0:o.call(this,i.userId));i.name&&(s.setDisplayName(i.name),i.events.member&&s.setRawDisplayName(i.events.member.getDirectionalContent().displayname)),i.events.member&&i.events.member.getContent().avatar_url&&s.setAvatarUrl(i.events.member.getContent().avatar_url),this.users[s.userId]=s}}),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(Me.Members,this.onRoomMember),e.currentState.getMembers().forEach(t=>{this.onRoomMember(null,e.currentState,t)})}setUserCreator(e){this.createUser=e}getRoom(e){return this.rooms[e]||null}getRooms(){return Object.values(this.rooms)}removeRoom(e){this.rooms[e]&&this.rooms[e].currentState.removeListener(Me.Members,this.onRoomMember),delete this.rooms[e]}getRoomSummaries(){return Object.values(this.rooms).map(function(e){return e.summary})}storeUser(e){this.users[e.userId]=e}getUser(e){return this.users[e]||null}getUsers(){return Object.values(this.users)}scrollback(e,t){return[]}storeEvents(e,t,n,i){}storeFilter(e){!(e!=null&&e.userId)||!(e!=null&&e.filterId)||this.filters.getOrCreate(e.userId).set(e.filterId,e)}getFilter(e,t){var n;return((n=this.filters.get(e))===null||n===void 0?void 0:n.get(t))||null}getFilterIdByName(e){if(!this.localStorage)return null;var t="mxjssdk_memory_filter_"+e;try{var n=this.localStorage.getItem(t);if(Qk(n))return n}catch{}return null}setFilterIdByName(e,t){if(this.localStorage){var n="mxjssdk_memory_filter_"+e;try{Qk(t)?this.localStorage.setItem(n,t):this.localStorage.removeItem(n)}catch{}}}storeAccountDataEvents(e){e.forEach(t=>{var n=!Object.keys(t.getContent()).length;n?this.accountData.delete(t.getType()):this.accountData.set(t.getType(),t)})}getAccountData(e){return this.accountData.get(e)}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(e){return Promise.resolve()}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return this.rooms={},this.users={},this.syncToken=null,this.filters=new Gt(()=>new Map),this.accountData=new Map,Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers.get(e)||null)}setOutOfBandMembers(e,t){return this.oobMembers.set(e,t),Promise.resolve()}clearOutOfBandMembers(e){return this.oobMembers.delete(e),Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(e){return this.clientOptions=Object.assign({},e),Promise.resolve()}getPendingEvents(e){var t=this;return w(function*(){var n;return(n=t.pendingEvents[e])!==null&&n!==void 0?n:[]})()}setPendingEvents(e,t){var n=this;return w(function*(){n.pendingEvents[e]=t})()}saveToDeviceBatches(e){for(var t of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:t.eventType,txnId:t.txnId,batch:t.batch});return Promise.resolve()}getOldestToDeviceBatch(){var e=this;return w(function*(){return e.pendingToDeviceBatches.length===0?null:e.pendingToDeviceBatches[0]})()}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter(t=>t.id!==e),Promise.resolve()}destroy(){return w(function*(){})()}}var my={},oa={},tl={};Object.defineProperty(tl,"__esModule",{value:!0});tl.WidgetApiDirection=void 0;tl.invertedDirection=P7;var Lu=function(r){return r.ToWidget="toWidget",r.FromWidget="fromWidget",r}({});tl.WidgetApiDirection=Lu;function P7(r){if(r===Lu.ToWidget)return Lu.FromWidget;if(r===Lu.FromWidget)return Lu.ToWidget;throw new Error("Invalid direction")}var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0});Zi.UnstableApiVersion=Zi.MatrixApiVersion=Zi.CurrentApiVersions=void 0;var g_=function(r){return r.Prerelease1="0.0.1",r.Prerelease2="0.0.2",r}({});Zi.MatrixApiVersion=g_;var On=function(r){return r.MSC2762="org.matrix.msc2762",r.MSC2762_UPDATE_STATE="org.matrix.msc2762_update_state",r.MSC2871="org.matrix.msc2871",r.MSC2873="org.matrix.msc2873",r.MSC2931="org.matrix.msc2931",r.MSC2974="org.matrix.msc2974",r.MSC2876="org.matrix.msc2876",r.MSC3819="org.matrix.msc3819",r.MSC3846="town.robin.msc3846",r.MSC3869="org.matrix.msc3869",r.MSC3973="org.matrix.msc3973",r.MSC4039="org.matrix.msc4039",r}({});Zi.UnstableApiVersion=On;var M7=[g_.Prerelease1,g_.Prerelease2,On.MSC2762,On.MSC2762_UPDATE_STATE,On.MSC2871,On.MSC2873,On.MSC2931,On.MSC2974,On.MSC2876,On.MSC3819,On.MSC3846,On.MSC3869,On.MSC3973,On.MSC4039];Zi.CurrentApiVersions=M7;var Su={},Zk;function Xw(){if(Zk)return Su;Zk=1,Object.defineProperty(Su,"__esModule",{value:!0}),Su.PostmessageTransport=void 0;var r=Em,e=jm(),t=["message"];function n(T){"@babel/helpers - typeof";return n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(O){return typeof O}:function(O){return O&&typeof Symbol=="function"&&O.constructor===Symbol&&O!==Symbol.prototype?"symbol":typeof O},n(T)}function i(T,O){if(T==null)return{};var C=o(T,O),N,F;if(Object.getOwnPropertySymbols){var H=Object.getOwnPropertySymbols(T);for(F=0;F<H.length;F++)N=H[F],!(O.indexOf(N)>=0)&&Object.prototype.propertyIsEnumerable.call(T,N)&&(C[N]=T[N])}return C}function o(T,O){if(T==null)return{};var C={},N=Object.keys(T),F,H;for(H=0;H<N.length;H++)F=N[H],!(O.indexOf(F)>=0)&&(C[F]=T[F]);return C}function s(T,O){var C=Object.keys(T);if(Object.getOwnPropertySymbols){var N=Object.getOwnPropertySymbols(T);O&&(N=N.filter(function(F){return Object.getOwnPropertyDescriptor(T,F).enumerable})),C.push.apply(C,N)}return C}function a(T){for(var O=1;O<arguments.length;O++){var C=arguments[O]!=null?arguments[O]:{};O%2?s(Object(C),!0).forEach(function(N){S(T,N,C[N])}):Object.getOwnPropertyDescriptors?Object.defineProperties(T,Object.getOwnPropertyDescriptors(C)):s(Object(C)).forEach(function(N){Object.defineProperty(T,N,Object.getOwnPropertyDescriptor(C,N))})}return T}function l(T,O){if(!(T instanceof O))throw new TypeError("Cannot call a class as a function")}function c(T,O){for(var C=0;C<O.length;C++){var N=O[C];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(T,R(N.key),N)}}function u(T,O,C){return O&&c(T.prototype,O),Object.defineProperty(T,"prototype",{writable:!1}),T}function d(T,O){if(typeof O!="function"&&O!==null)throw new TypeError("Super expression must either be null or a function");T.prototype=Object.create(O&&O.prototype,{constructor:{value:T,writable:!0,configurable:!0}}),Object.defineProperty(T,"prototype",{writable:!1}),O&&f(T,O)}function f(T,O){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(N,F){return N.__proto__=F,N},f(T,O)}function p(T){var O=E();return function(){var N=y(T),F;if(O){var H=y(this).constructor;F=Reflect.construct(N,arguments,H)}else F=N.apply(this,arguments);return h(this,F)}}function h(T,O){if(O&&(n(O)==="object"||typeof O=="function"))return O;if(O!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return m(T)}function m(T){if(T===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return T}function E(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function y(T){return y=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(C){return C.__proto__||Object.getPrototypeOf(C)},y(T)}function S(T,O,C){return O=R(O),O in T?Object.defineProperty(T,O,{value:C,enumerable:!0,configurable:!0,writable:!0}):T[O]=C,T}function R(T){var O=k(T,"string");return n(O)==="symbol"?O:String(O)}function k(T,O){if(n(T)!=="object"||T===null)return T;var C=T[Symbol.toPrimitive];if(C!==void 0){var N=C.call(T,O);if(n(N)!=="object")return N;throw new TypeError("@@toPrimitive must return a primitive value.")}return(O==="string"?String:Number)(T)}var x=function(T){d(C,T);var O=p(C);function C(N,F,H,ie){var $;return l(this,C),$=O.call(this),$.sendDirection=N,$.transportWindow=H,$.inboundWindow=ie,S(m($),"strictOriginCheck",!1),S(m($),"targetOrigin","*"),S(m($),"timeoutSeconds",10),S(m($),"_ready",!1),S(m($),"_widgetId",void 0),S(m($),"outboundRequests",new Map),S(m($),"stopController",new AbortController),S(m($),"handleMessage",function(X){if(!$.stopController.signal.aborted&&X.data&&!($.strictOriginCheck&&X.origin!==globalThis.origin)){var oe=X.data;if(!(!oe.action||!oe.requestId||!oe.widgetId))if(oe.response){if(oe.api!==$.sendDirection)return;$.handleResponse(oe)}else{var re=oe;if(re.api!==(0,e.invertedDirection)($.sendDirection))return;$.handleRequest(re)}}}),$._widgetId=F,$}return u(C,[{key:"ready",get:function(){return this._ready}},{key:"widgetId",get:function(){return this._widgetId||null}},{key:"nextRequestId",get:function(){for(var F="widgetapi-".concat(Date.now()),H=0,ie=F;this.outboundRequests.has(ie);)ie="".concat(F,"-").concat(H++);return this.outboundRequests.set(ie,null),ie}},{key:"sendInternal",value:function(F){console.log("[PostmessageTransport] Sending object to ".concat(this.targetOrigin,": "),F),this.transportWindow.postMessage(F,this.targetOrigin)}},{key:"reply",value:function(F,H){return this.sendInternal(a(a({},F),{},{response:H}))}},{key:"send",value:function(F,H){return this.sendComplete(F,H).then(function(ie){return ie.response})}},{key:"sendComplete",value:function(F,H){var ie=this;if(!this.ready||!this.widgetId)return Promise.reject(new Error("Not ready or unknown widget ID"));var $={api:this.sendDirection,widgetId:this.widgetId,requestId:this.nextRequestId,action:F,data:H};return F===e.WidgetApiToWidgetAction.UpdateVisibility&&($.visible=H.visible),new Promise(function(X,oe){var re=function(Y){Q(),X(Y)},ae=function(Y){Q(),oe(Y)},q=setTimeout(function(){return ae(new Error("Request timed out"))},(ie.timeoutSeconds||1)*1e3),z=function(){return ae(new Error("Transport stopped"))};ie.stopController.signal.addEventListener("abort",z);var Q=function(){ie.outboundRequests.delete($.requestId),clearTimeout(q),ie.stopController.signal.removeEventListener("abort",z)};ie.outboundRequests.set($.requestId,{request:$,resolve:re,reject:ae}),ie.sendInternal($)})}},{key:"start",value:function(){this.inboundWindow.addEventListener("message",this.handleMessage),this._ready=!0}},{key:"stop",value:function(){this._ready=!1,this.stopController.abort(),this.inboundWindow.removeEventListener("message",this.handleMessage)}},{key:"handleRequest",value:function(F){if(this.widgetId){if(this.widgetId!==F.widgetId)return}else this._widgetId=F.widgetId;this.emit("message",new CustomEvent("message",{detail:F}))}},{key:"handleResponse",value:function(F){if(F.widgetId===this.widgetId){var H=this.outboundRequests.get(F.requestId);if(H)if((0,e.isErrorResponse)(F.response)){var ie=F.response.error,$=ie.message,X=i(ie,t);H.reject(new e.WidgetApiResponseError($,X))}else H.resolve(F)}}}]),C}(r.EventEmitter);return Su.PostmessageTransport=x,Su}var Ls={};Object.defineProperty(Ls,"__esModule",{value:!0});Ls.WidgetApiToWidgetAction=Ls.WidgetApiFromWidgetAction=void 0;var A7=function(r){return r.SupportedApiVersions="supported_api_versions",r.Capabilities="capabilities",r.NotifyCapabilities="notify_capabilities",r.ThemeChange="theme_change",r.LanguageChange="language_change",r.TakeScreenshot="screenshot",r.UpdateVisibility="visibility",r.OpenIDCredentials="openid_credentials",r.WidgetConfig="widget_config",r.CloseModalWidget="close_modal",r.ButtonClicked="button_clicked",r.SendEvent="send_event",r.SendToDevice="send_to_device",r.UpdateState="update_state",r.UpdateTurnServers="update_turn_servers",r}({});Ls.WidgetApiToWidgetAction=A7;var D7=function(r){return r.SupportedApiVersions="supported_api_versions",r.ContentLoaded="content_loaded",r.SendSticker="m.sticker",r.UpdateAlwaysOnScreen="set_always_on_screen",r.GetOpenIDCredentials="get_openid",r.CloseModalWidget="close_modal",r.OpenModalWidget="open_modal",r.SetModalButtonEnabled="set_button_enabled",r.SendEvent="send_event",r.SendToDevice="send_to_device",r.WatchTurnServers="watch_turn_servers",r.UnwatchTurnServers="unwatch_turn_servers",r.BeeperReadRoomAccountData="com.beeper.read_room_account_data",r.MSC2876ReadEvents="org.matrix.msc2876.read_events",r.MSC2931Navigate="org.matrix.msc2931.navigate",r.MSC2974RenegotiateCapabilities="org.matrix.msc2974.request_capabilities",r.MSC3869ReadRelations="org.matrix.msc3869.read_relations",r.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",r.MSC4039GetMediaConfigAction="org.matrix.msc4039.get_media_config",r.MSC4039UploadFileAction="org.matrix.msc4039.upload_file",r.MSC4039DownloadFileAction="org.matrix.msc4039.download_file",r.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",r}({});Ls.WidgetApiFromWidgetAction=D7;var Gc={};Object.defineProperty(Gc,"__esModule",{value:!0});Gc.OpenIDRequestState=void 0;var N7=function(r){return r.Allowed="allowed",r.Blocked="blocked",r.PendingUserConfirmation="request",r}({});Gc.OpenIDRequestState=N7;var If={};Object.defineProperty(If,"__esModule",{value:!0});If.MatrixWidgetType=void 0;var L7=function(r){return r.Custom="m.custom",r.JitsiMeet="m.jitsi",r.Stickerpicker="m.stickerpicker",r}({});If.MatrixWidgetType=L7;var xf={};Object.defineProperty(xf,"__esModule",{value:!0});xf.BuiltInModalButtonID=void 0;var U7=function(r){return r.Close="m.close",r}({});xf.BuiltInModalButtonID=U7;var eo={};Object.defineProperty(eo,"__esModule",{value:!0});eo.WidgetEventCapability=eo.EventKind=eo.EventDirection=void 0;function Hd(r){"@babel/helpers - typeof";return Hd=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Hd(r)}function j7(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=F7(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
295
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function F7(r,e){if(r){if(typeof r=="string")return eI(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return eI(r,e)}}function eI(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function B7(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function tI(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,V7(n.key),n)}}function K7(r,e,t){return e&&tI(r.prototype,e),t&&tI(r,t),Object.defineProperty(r,"prototype",{writable:!1}),r}function V7(r){var e=$7(r,"string");return Hd(e)==="symbol"?e:String(e)}function $7(r,e){if(Hd(r)!=="object"||r===null)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(Hd(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(r)}var Pn=function(r){return r.Event="event",r.State="state_event",r.ToDevice="to_device",r.RoomAccount="room_account",r}({});eo.EventKind=Pn;var os=function(r){return r.Send="send",r.Receive="receive",r}({});eo.EventDirection=os;var W7=function(){function r(e,t,n,i,o){B7(this,r),this.direction=e,this.eventType=t,this.kind=n,this.keyStr=i,this.raw=o}return K7(r,[{key:"matchesAsStateEvent",value:function(t,n,i){return this.kind!==Pn.State||this.direction!==t||this.eventType!==n?!1:this.keyStr===null||this.keyStr===i}},{key:"matchesAsToDeviceEvent",value:function(t,n){return!(this.kind!==Pn.ToDevice||this.direction!==t||this.eventType!==n)}},{key:"matchesAsRoomEvent",value:function(t,n){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this.kind!==Pn.Event||this.direction!==t||this.eventType!==n)return!1;if(this.eventType==="m.room.message"){if(this.keyStr===null||this.keyStr===i)return!0}else return!0;return!1}},{key:"matchesAsRoomAccountData",value:function(t,n){return!(this.kind!==Pn.RoomAccount||this.direction!==t||this.eventType!==n)}}],[{key:"forStateEvent",value:function(t,n,i){n=n.replace(/#/g,"\\#"),i=i!=null?"#".concat(i):"";var o="org.matrix.msc2762.".concat(t,".state_event:").concat(n).concat(i);return r.findEventCapabilities([o])[0]}},{key:"forToDeviceEvent",value:function(t,n){var i="org.matrix.msc3819.".concat(t,".to_device:").concat(n);return r.findEventCapabilities([i])[0]}},{key:"forRoomEvent",value:function(t,n){var i="org.matrix.msc2762.".concat(t,".event:").concat(n);return r.findEventCapabilities([i])[0]}},{key:"forRoomMessageEvent",value:function(t,n){n=n??"";var i="org.matrix.msc2762.".concat(t,".event:m.room.message#").concat(n);return r.findEventCapabilities([i])[0]}},{key:"forRoomAccountData",value:function(t,n){var i="com.beeper.capabilities.".concat(t,".room_account_data:").concat(n);return r.findEventCapabilities([i])[0]}},{key:"findEventCapabilities",value:function(t){var n=[],i=j7(t),o;try{for(i.s();!(o=i.n()).done;){var s=o.value,a=null,l=void 0,c=null;if(s.startsWith("org.matrix.msc2762.send.event:")?(a=os.Send,c=Pn.Event,l=s.substring(30)):s.startsWith("org.matrix.msc2762.send.state_event:")?(a=os.Send,c=Pn.State,l=s.substring(36)):s.startsWith("org.matrix.msc3819.send.to_device:")?(a=os.Send,c=Pn.ToDevice,l=s.substring(34)):s.startsWith("org.matrix.msc2762.receive.event:")?(a=os.Receive,c=Pn.Event,l=s.substring(33)):s.startsWith("org.matrix.msc2762.receive.state_event:")?(a=os.Receive,c=Pn.State,l=s.substring(39)):s.startsWith("org.matrix.msc3819.receive.to_device:")?(a=os.Receive,c=Pn.ToDevice,l=s.substring(37)):s.startsWith("com.beeper.capabilities.receive.room_account_data:")&&(a=os.Receive,c=Pn.RoomAccount,l=s.substring(50)),!(a===null||c===null||l===void 0)){var u=l.startsWith("m.room.message#")||c===Pn.State,d=null;if(l.includes("#")&&u){var f=l.split("#"),p=f.findIndex(function(h){return!h.endsWith("\\")});l=f.slice(0,p+1).map(function(h){return h.endsWith("\\")?h.substring(0,h.length-1):h}).join("#"),d=f.slice(p+1).join("#")}n.push(new r(a,l,c,d,s))}}}catch(h){i.e(h)}finally{i.f()}return n}}]),r}();eo.WidgetEventCapability=W7;var Hc={};Object.defineProperty(Hc,"__esModule",{value:!0});Hc.Symbols=void 0;var q7=function(r){return r.AnyRoom="*",r}({});Hc.Symbols=q7;var zc={};Object.defineProperty(zc,"__esModule",{value:!0});zc.UpdateDelayedEventAction=void 0;var G7=function(r){return r.Cancel="cancel",r.Restart="restart",r.Send="send",r}({});zc.UpdateDelayedEventAction=G7;var rI;function H7(){if(rI)return oa;rI=1;function r(A){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(D){return typeof D}:function(D){return D&&typeof Symbol=="function"&&D.constructor===Symbol&&D!==Symbol.prototype?"symbol":typeof D},r(A)}Object.defineProperty(oa,"__esModule",{value:!0}),oa.WidgetApiResponseError=oa.WidgetApi=void 0;var e=Em,t=tl,n=Zi,i=Xw(),o=Ls,s=Gc,a=If,l=xf,c=eo,u=Hc,d=zc;function f(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */f=function(){return A};var A={},D=Object.prototype,P=D.hasOwnProperty,M=Object.defineProperty||function(J,te,ne){J[te]=ne.value},I=typeof Symbol=="function"?Symbol:{},j=I.iterator||"@@iterator",U=I.asyncIterator||"@@asyncIterator",K=I.toStringTag||"@@toStringTag";function G(J,te,ne){return Object.defineProperty(J,te,{value:ne,enumerable:!0,configurable:!0,writable:!0}),J[te]}try{G({},"")}catch{G=function(ne,ue,Ee){return ne[ue]=Ee}}function ee(J,te,ne,ue){var Ee=te&&te.prototype instanceof Re?te:Re,Te=Object.create(Ee.prototype),ze=new Cn(ue||[]);return M(Te,"_invoke",{value:gt(J,ne,ze)}),Te}function se(J,te,ne){try{return{type:"normal",arg:J.call(te,ne)}}catch(ue){return{type:"throw",arg:ue}}}A.wrap=ee;var Ce={};function Re(){}function ge(){}function He(){}var Qe={};G(Qe,j,function(){return this});var $e=Object.getPrototypeOf,me=$e&&$e($e(ye([])));me&&me!==D&&P.call(me,j)&&(Qe=me);var We=He.prototype=Re.prototype=Object.create(Qe);function un(J){["next","throw","return"].forEach(function(te){G(J,te,function(ne){return this._invoke(te,ne)})})}function Rr(J,te){function ne(Ee,Te,ze,dt){var ht=se(J[Ee],J,Te);if(ht.type!=="throw"){var Kt=ht.arg,Ue=Kt.value;return Ue&&r(Ue)=="object"&&P.call(Ue,"__await")?te.resolve(Ue.__await).then(function(pt){ne("next",pt,ze,dt)},function(pt){ne("throw",pt,ze,dt)}):te.resolve(Ue).then(function(pt){Kt.value=pt,ze(Kt)},function(pt){return ne("throw",pt,ze,dt)})}dt(ht.arg)}var ue;M(this,"_invoke",{value:function(Te,ze){function dt(){return new te(function(ht,Kt){ne(Te,ze,ht,Kt)})}return ue=ue?ue.then(dt,dt):dt()}})}function gt(J,te,ne){var ue="suspendedStart";return function(Ee,Te){if(ue==="executing")throw new Error("Generator is already running");if(ue==="completed"){if(Ee==="throw")throw Te;return fe()}for(ne.method=Ee,ne.arg=Te;;){var ze=ne.delegate;if(ze){var dt=vr(ze,ne);if(dt){if(dt===Ce)continue;return dt}}if(ne.method==="next")ne.sent=ne._sent=ne.arg;else if(ne.method==="throw"){if(ue==="suspendedStart")throw ue="completed",ne.arg;ne.dispatchException(ne.arg)}else ne.method==="return"&&ne.abrupt("return",ne.arg);ue="executing";var ht=se(J,te,ne);if(ht.type==="normal"){if(ue=ne.done?"completed":"suspendedYield",ht.arg===Ce)continue;return{value:ht.arg,done:ne.done}}ht.type==="throw"&&(ue="completed",ne.method="throw",ne.arg=ht.arg)}}}function vr(J,te){var ne=te.method,ue=J.iterator[ne];if(ue===void 0)return te.delegate=null,ne==="throw"&&J.iterator.return&&(te.method="return",te.arg=void 0,vr(J,te),te.method==="throw")||ne!=="return"&&(te.method="throw",te.arg=new TypeError("The iterator does not provide a '"+ne+"' method")),Ce;var Ee=se(ue,J.iterator,te.arg);if(Ee.type==="throw")return te.method="throw",te.arg=Ee.arg,te.delegate=null,Ce;var Te=Ee.arg;return Te?Te.done?(te[J.resultName]=Te.value,te.next=J.nextLoc,te.method!=="return"&&(te.method="next",te.arg=void 0),te.delegate=null,Ce):Te:(te.method="throw",te.arg=new TypeError("iterator result is not an object"),te.delegate=null,Ce)}function mr(J){var te={tryLoc:J[0]};1 in J&&(te.catchLoc=J[1]),2 in J&&(te.finallyLoc=J[2],te.afterLoc=J[3]),this.tryEntries.push(te)}function Rt(J){var te=J.completion||{};te.type="normal",delete te.arg,J.completion=te}function Cn(J){this.tryEntries=[{tryLoc:"root"}],J.forEach(mr,this),this.reset(!0)}function ye(J){if(J){var te=J[j];if(te)return te.call(J);if(typeof J.next=="function")return J;if(!isNaN(J.length)){var ne=-1,ue=function Ee(){for(;++ne<J.length;)if(P.call(J,ne))return Ee.value=J[ne],Ee.done=!1,Ee;return Ee.value=void 0,Ee.done=!0,Ee};return ue.next=ue}}return{next:fe}}function fe(){return{value:void 0,done:!0}}return ge.prototype=He,M(We,"constructor",{value:He,configurable:!0}),M(He,"constructor",{value:ge,configurable:!0}),ge.displayName=G(He,K,"GeneratorFunction"),A.isGeneratorFunction=function(J){var te=typeof J=="function"&&J.constructor;return!!te&&(te===ge||(te.displayName||te.name)==="GeneratorFunction")},A.mark=function(J){return Object.setPrototypeOf?Object.setPrototypeOf(J,He):(J.__proto__=He,G(J,K,"GeneratorFunction")),J.prototype=Object.create(We),J},A.awrap=function(J){return{__await:J}},un(Rr.prototype),G(Rr.prototype,U,function(){return this}),A.AsyncIterator=Rr,A.async=function(J,te,ne,ue,Ee){Ee===void 0&&(Ee=Promise);var Te=new Rr(ee(J,te,ne,ue),Ee);return A.isGeneratorFunction(te)?Te:Te.next().then(function(ze){return ze.done?ze.value:Te.next()})},un(We),G(We,K,"Generator"),G(We,j,function(){return this}),G(We,"toString",function(){return"[object Generator]"}),A.keys=function(J){var te=Object(J),ne=[];for(var ue in te)ne.push(ue);return ne.reverse(),function Ee(){for(;ne.length;){var Te=ne.pop();if(Te in te)return Ee.value=Te,Ee.done=!1,Ee}return Ee.done=!0,Ee}},A.values=ye,Cn.prototype={constructor:Cn,reset:function(te){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(Rt),!te)for(var ne in this)ne.charAt(0)==="t"&&P.call(this,ne)&&!isNaN(+ne.slice(1))&&(this[ne]=void 0)},stop:function(){this.done=!0;var te=this.tryEntries[0].completion;if(te.type==="throw")throw te.arg;return this.rval},dispatchException:function(te){if(this.done)throw te;var ne=this;function ue(Kt,Ue){return ze.type="throw",ze.arg=te,ne.next=Kt,Ue&&(ne.method="next",ne.arg=void 0),!!Ue}for(var Ee=this.tryEntries.length-1;Ee>=0;--Ee){var Te=this.tryEntries[Ee],ze=Te.completion;if(Te.tryLoc==="root")return ue("end");if(Te.tryLoc<=this.prev){var dt=P.call(Te,"catchLoc"),ht=P.call(Te,"finallyLoc");if(dt&&ht){if(this.prev<Te.catchLoc)return ue(Te.catchLoc,!0);if(this.prev<Te.finallyLoc)return ue(Te.finallyLoc)}else if(dt){if(this.prev<Te.catchLoc)return ue(Te.catchLoc,!0)}else{if(!ht)throw new Error("try statement without catch or finally");if(this.prev<Te.finallyLoc)return ue(Te.finallyLoc)}}}},abrupt:function(te,ne){for(var ue=this.tryEntries.length-1;ue>=0;--ue){var Ee=this.tryEntries[ue];if(Ee.tryLoc<=this.prev&&P.call(Ee,"finallyLoc")&&this.prev<Ee.finallyLoc){var Te=Ee;break}}Te&&(te==="break"||te==="continue")&&Te.tryLoc<=ne&&ne<=Te.finallyLoc&&(Te=null);var ze=Te?Te.completion:{};return ze.type=te,ze.arg=ne,Te?(this.method="next",this.next=Te.finallyLoc,Ce):this.complete(ze)},complete:function(te,ne){if(te.type==="throw")throw te.arg;return te.type==="break"||te.type==="continue"?this.next=te.arg:te.type==="return"?(this.rval=this.arg=te.arg,this.method="return",this.next="end"):te.type==="normal"&&ne&&(this.next=ne),Ce},finish:function(te){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ue=this.tryEntries[ne];if(ue.finallyLoc===te)return this.complete(ue.completion,ue.afterLoc),Rt(ue),Ce}},catch:function(te){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ue=this.tryEntries[ne];if(ue.tryLoc===te){var Ee=ue.completion;if(Ee.type==="throw"){var Te=Ee.arg;Rt(ue)}return Te}}throw new Error("illegal catch attempt")},delegateYield:function(te,ne,ue){return this.delegate={iterator:ye(te),resultName:ne,nextLoc:ue},this.method==="next"&&(this.arg=void 0),Ce}},A}function p(A,D,P,M,I,j,U){try{var K=A[j](U),G=K.value}catch(ee){P(ee);return}K.done?D(G):Promise.resolve(G).then(M,I)}function h(A){return function(){var D=this,P=arguments;return new Promise(function(M,I){var j=A.apply(D,P);function U(G){p(j,M,I,U,K,"next",G)}function K(G){p(j,M,I,U,K,"throw",G)}U(void 0)})}}function m(A,D){var P=Object.keys(A);if(Object.getOwnPropertySymbols){var M=Object.getOwnPropertySymbols(A);D&&(M=M.filter(function(I){return Object.getOwnPropertyDescriptor(A,I).enumerable})),P.push.apply(P,M)}return P}function E(A){for(var D=1;D<arguments.length;D++){var P=arguments[D]!=null?arguments[D]:{};D%2?m(Object(P),!0).forEach(function(M){k(A,M,P[M])}):Object.getOwnPropertyDescriptors?Object.defineProperties(A,Object.getOwnPropertyDescriptors(P)):m(Object(P)).forEach(function(M){Object.defineProperty(A,M,Object.getOwnPropertyDescriptor(P,M))})}return A}function y(A,D){var P=typeof Symbol<"u"&&A[Symbol.iterator]||A["@@iterator"];if(!P){if(Array.isArray(A)||(P=S(A))||D){P&&(A=P);var M=0,I=function(){};return{s:I,n:function(){return M>=A.length?{done:!0}:{done:!1,value:A[M++]}},e:function(ee){throw ee},f:I}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
296
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var j=!0,U=!1,K;return{s:function(){P=P.call(A)},n:function(){var ee=P.next();return j=ee.done,ee},e:function(ee){U=!0,K=ee},f:function(){try{!j&&P.return!=null&&P.return()}finally{if(U)throw K}}}}function S(A,D){if(A){if(typeof A=="string")return R(A,D);var P=Object.prototype.toString.call(A).slice(8,-1);if(P==="Object"&&A.constructor&&(P=A.constructor.name),P==="Map"||P==="Set")return Array.from(A);if(P==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(P))return R(A,D)}}function R(A,D){(D==null||D>A.length)&&(D=A.length);for(var P=0,M=new Array(D);P<D;P++)M[P]=A[P];return M}function k(A,D,P){return D=O(D),D in A?Object.defineProperty(A,D,{value:P,enumerable:!0,configurable:!0,writable:!0}):A[D]=P,A}function x(A,D){for(var P=0;P<D.length;P++){var M=D[P];M.enumerable=M.enumerable||!1,M.configurable=!0,"value"in M&&(M.writable=!0),Object.defineProperty(A,O(M.key),M)}}function T(A,D,P){return D&&x(A.prototype,D),Object.defineProperty(A,"prototype",{writable:!1}),A}function O(A){var D=C(A,"string");return r(D)==="symbol"?D:String(D)}function C(A,D){if(r(A)!=="object"||A===null)return A;var P=A[Symbol.toPrimitive];if(P!==void 0){var M=P.call(A,D);if(r(M)!=="object")return M;throw new TypeError("@@toPrimitive must return a primitive value.")}return(D==="string"?String:Number)(A)}function N(A,D){if(!(A instanceof D))throw new TypeError("Cannot call a class as a function")}function F(A,D){if(typeof D!="function"&&D!==null)throw new TypeError("Super expression must either be null or a function");A.prototype=Object.create(D&&D.prototype,{constructor:{value:A,writable:!0,configurable:!0}}),Object.defineProperty(A,"prototype",{writable:!1}),D&&q(A,D)}function H(A){var D=re();return function(){var M=z(A),I;if(D){var j=z(this).constructor;I=Reflect.construct(M,arguments,j)}else I=M.apply(this,arguments);return ie(this,I)}}function ie(A,D){if(D&&(r(D)==="object"||typeof D=="function"))return D;if(D!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return $(A)}function $(A){if(A===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return A}function X(A){var D=typeof Map=="function"?new Map:void 0;return X=function(M){if(M===null||!ae(M))return M;if(typeof M!="function")throw new TypeError("Super expression must either be null or a function");if(typeof D<"u"){if(D.has(M))return D.get(M);D.set(M,I)}function I(){return oe(M,arguments,z(this).constructor)}return I.prototype=Object.create(M.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}),q(I,M)},X(A)}function oe(A,D,P){return re()?oe=Reflect.construct.bind():oe=function(I,j,U){var K=[null];K.push.apply(K,j);var G=Function.bind.apply(I,K),ee=new G;return U&&q(ee,U.prototype),ee},oe.apply(null,arguments)}function re(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function ae(A){return Function.toString.call(A).indexOf("[native code]")!==-1}function q(A,D){return q=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(M,I){return M.__proto__=I,M},q(A,D)}function z(A){return z=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(P){return P.__proto__||Object.getPrototypeOf(P)},z(A)}function Q(A){return new le(A,0)}function Ie(A){return function(){return new Y(A.apply(this,arguments))}}function Y(A){var D,P;function M(j,U){try{var K=A[j](U),G=K.value,ee=G instanceof le;Promise.resolve(ee?G.v:G).then(function(se){if(ee){var Ce=j==="return"?"return":"next";if(!G.k||se.done)return M(Ce,se);se=A[Ce](se).value}I(K.done?"return":"normal",se)},function(se){M("throw",se)})}catch(se){I("throw",se)}}function I(j,U){switch(j){case"return":D.resolve({value:U,done:!0});break;case"throw":D.reject(U);break;default:D.resolve({value:U,done:!1})}(D=D.next)?M(D.key,D.arg):P=null}this._invoke=function(j,U){return new Promise(function(K,G){var ee={key:j,arg:U,resolve:K,reject:G,next:null};P?P=P.next=ee:(D=P=ee,M(j,U))})},typeof A.return!="function"&&(this.return=void 0)}Y.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Y.prototype.next=function(A){return this._invoke("next",A)},Y.prototype.throw=function(A){return this._invoke("throw",A)},Y.prototype.return=function(A){return this._invoke("return",A)};function le(A,D){this.v=A,this.k=D}var B=function(A){F(P,A);var D=H(P);function P(M,I){var j;return N(this,P),j=D.call(this,M),j.data=I,j}return T(P)}(X(Error));oa.WidgetApiResponseError=B,B.prototype.name=B.name;var W=function(A){F(P,A);var D=H(P);function P(){var M,I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,j=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(N(this,P),M=D.call(this),k($(M),"transport",void 0),k($(M),"capabilitiesFinished",!1),k($(M),"supportsMSC2974Renegotiate",!1),k($(M),"requestedCapabilities",[]),k($(M),"approvedCapabilities",void 0),k($(M),"cachedClientVersions",void 0),k($(M),"turnServerWatchers",0),!globalThis.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");return M.transport=new i.PostmessageTransport(t.WidgetApiDirection.FromWidget,I,globalThis.parent,globalThis),M.transport.targetOrigin=j,M.transport.on("message",M.handleMessage.bind($(M))),M}return T(P,[{key:"hasCapability",value:function(I){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(I):this.requestedCapabilities.includes(I)}},{key:"requestCapability",value:function(I){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(I)}},{key:"requestCapabilities",value:function(I){var j=y(I),U;try{for(j.s();!(U=j.n()).done;){var K=U.value;this.requestCapability(K)}}catch(G){j.e(G)}finally{j.f()}}},{key:"requestCapabilityForRoomTimeline",value:function(I){this.requestCapability("org.matrix.msc2762.timeline:".concat(I))}},{key:"requestCapabilityToSendState",value:function(I,j){this.requestCapability(c.WidgetEventCapability.forStateEvent(c.EventDirection.Send,I,j).raw)}},{key:"requestCapabilityToReceiveState",value:function(I,j){this.requestCapability(c.WidgetEventCapability.forStateEvent(c.EventDirection.Receive,I,j).raw)}},{key:"requestCapabilityToSendToDevice",value:function(I){this.requestCapability(c.WidgetEventCapability.forToDeviceEvent(c.EventDirection.Send,I).raw)}},{key:"requestCapabilityToReceiveToDevice",value:function(I){this.requestCapability(c.WidgetEventCapability.forToDeviceEvent(c.EventDirection.Receive,I).raw)}},{key:"requestCapabilityToSendEvent",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomEvent(c.EventDirection.Send,I).raw)}},{key:"requestCapabilityToReceiveEvent",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomEvent(c.EventDirection.Receive,I).raw)}},{key:"requestCapabilityToSendMessage",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomMessageEvent(c.EventDirection.Send,I).raw)}},{key:"requestCapabilityToReceiveMessage",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomMessageEvent(c.EventDirection.Receive,I).raw)}},{key:"requestCapabilityToReceiveRoomAccountData",value:function(I){this.requestCapability(c.WidgetEventCapability.forRoomAccountData(c.EventDirection.Receive,I).raw)}},{key:"requestOpenIDConnectToken",value:function(){var I=this;return new Promise(function(j,U){I.transport.sendComplete(o.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then(function(K){var G=K.response;if(G.state===s.OpenIDRequestState.Allowed)j(G);else if(G.state===s.OpenIDRequestState.Blocked)U(new Error("User declined to verify their identity"));else if(G.state===s.OpenIDRequestState.PendingUserConfirmation){var ee=function se(Ce){Ce.preventDefault();var Re=Ce.detail;Re.data.original_request_id===K.requestId&&(Re.data.state===s.OpenIDRequestState.Allowed?(j(Re.data),I.transport.reply(Re,{})):Re.data.state===s.OpenIDRequestState.Blocked?(U(new Error("User declined to verify their identity")),I.transport.reply(Re,{})):(U(new Error("Invalid state on reply: "+G.state)),I.transport.reply(Re,{error:{message:"Invalid state"}})),I.off("action:".concat(o.WidgetApiToWidgetAction.OpenIDCredentials),se))};I.on("action:".concat(o.WidgetApiToWidgetAction.OpenIDCredentials),ee)}else U(new Error("Invalid state: "+G.state))}).catch(U)})}},{key:"updateRequestedCapabilities",value:function(){return this.transport.send(o.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}},{key:"sendContentLoaded",value:function(){return this.transport.send(o.WidgetApiFromWidgetAction.ContentLoaded,{}).then()}},{key:"sendSticker",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.SendSticker,I).then()}},{key:"setAlwaysOnScreen",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:I}).then(function(j){return j.success})}},{key:"openModalWidget",value:function(I,j){var U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],K=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},G=arguments.length>4&&arguments[4]!==void 0?arguments[4]:a.MatrixWidgetType.Custom;return this.transport.send(o.WidgetApiFromWidgetAction.OpenModalWidget,{type:G,url:I,name:j,buttons:U,data:K}).then()}},{key:"closeModalWidget",value:function(){var I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.transport.send(o.WidgetApiFromWidgetAction.CloseModalWidget,I).then()}},{key:"sendRoomEvent",value:function(I,j,U,K,G,ee){return this.sendEvent(I,void 0,j,U,K,G,ee)}},{key:"sendStateEvent",value:function(I,j,U,K,G,ee){return this.sendEvent(I,j,U,K,G,ee)}},{key:"sendEvent",value:function(I,j,U,K,G,ee,se){return this.transport.send(o.WidgetApiFromWidgetAction.SendEvent,E(E(E(E(E({type:I,content:U},j!==void 0&&{state_key:j}),K!==void 0&&{room_id:K}),G!==void 0&&{delay:G}),ee!==void 0&&{parent_delay_id:ee}),se!==void 0&&{sticky_duration_ms:se}))}},{key:"cancelScheduledDelayedEvent",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:I,action:d.UpdateDelayedEventAction.Cancel})}},{key:"restartScheduledDelayedEvent",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:I,action:d.UpdateDelayedEventAction.Restart})}},{key:"sendScheduledDelayedEvent",value:function(I){return this.transport.send(o.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent,{delay_id:I,action:d.UpdateDelayedEventAction.Send})}},{key:"sendToDevice",value:function(I,j,U){return this.transport.send(o.WidgetApiFromWidgetAction.SendToDevice,{type:I,encrypted:j,messages:U})}},{key:"readRoomAccountData",value:function(I,j){var U={type:I};return j&&(j.includes(u.Symbols.AnyRoom)?U.room_ids=u.Symbols.AnyRoom:U.room_ids=j),this.transport.send(o.WidgetApiFromWidgetAction.BeeperReadRoomAccountData,U).then(function(K){return K.events})}},{key:"readRoomEvents",value:function(I,j,U,K,G){var ee={type:I,msgtype:U};return j!==void 0&&(ee.limit=j),K&&(K.includes(u.Symbols.AnyRoom)?ee.room_ids=u.Symbols.AnyRoom:ee.room_ids=K),G&&(ee.since=G),this.transport.send(o.WidgetApiFromWidgetAction.MSC2876ReadEvents,ee).then(function(se){return se.events})}},{key:"readEventRelations",value:function(){var M=h(f().mark(function j(U,K,G,ee,se,Ce,Re,ge){var He,Qe;return f().wrap(function(me){for(;;)switch(me.prev=me.next){case 0:return me.next=2,this.getClientVersions();case 2:if(He=me.sent,He.includes(n.UnstableApiVersion.MSC3869)){me.next=5;break}throw new Error("The read_relations action is not supported by the client.");case 5:return Qe={event_id:U,rel_type:G,event_type:ee,room_id:K,to:Re,from:Ce,limit:se,direction:ge},me.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC3869ReadRelations,Qe));case 7:case"end":return me.stop()}},j,this)}));function I(j,U,K,G,ee,se,Ce,Re){return M.apply(this,arguments)}return I}()},{key:"readStateEvents",value:function(I,j,U,K){var G={type:I,state_key:U===void 0?!0:U};return j!==void 0&&(G.limit=j),K&&(K.includes(u.Symbols.AnyRoom)?G.room_ids=u.Symbols.AnyRoom:G.room_ids=K),this.transport.send(o.WidgetApiFromWidgetAction.MSC2876ReadEvents,G).then(function(ee){return ee.events})}},{key:"setModalButtonEnabled",value:function(I,j){if(I===l.BuiltInModalButtonID.Close)throw new Error("The close button cannot be disabled");return this.transport.send(o.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:I,enabled:j}).then()}},{key:"navigateTo",value:function(I){if(!I||!I.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(o.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:I}).then()}},{key:"getTurnServers",value:function(){var I=this;return Ie(f().mark(function j(){var U,K;return f().wrap(function(ee){for(;;)switch(ee.prev=ee.next){case 0:if(K=function(){var se=h(f().mark(function Ce(Re){return f().wrap(function(He){for(;;)switch(He.prev=He.next){case 0:Re.preventDefault(),U(Re.detail.data),I.transport.reply(Re.detail,{});case 3:case"end":return He.stop()}},Ce)}));return function(Re){return se.apply(this,arguments)}}(),I.on("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),K),I.turnServerWatchers!==0){ee.next=12;break}return ee.prev=3,ee.next=6,Q(I.transport.send(o.WidgetApiFromWidgetAction.WatchTurnServers,{}));case 6:ee.next=12;break;case 8:throw ee.prev=8,ee.t0=ee.catch(3),I.off("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),K),ee.t0;case 12:I.turnServerWatchers++,ee.prev=13;case 14:return ee.next=17,Q(new Promise(function(se){return U=se}));case 17:return ee.next=19,ee.sent;case 19:ee.next=14;break;case 21:if(ee.prev=21,I.off("action:".concat(o.WidgetApiToWidgetAction.UpdateTurnServers),K),I.turnServerWatchers--,I.turnServerWatchers!==0){ee.next=27;break}return ee.next=27,Q(I.transport.send(o.WidgetApiFromWidgetAction.UnwatchTurnServers,{}));case 27:return ee.finish(21);case 28:case"end":return ee.stop()}},j,null,[[3,8],[13,,21,28]])}))()}},{key:"searchUserDirectory",value:function(){var M=h(f().mark(function j(U,K){var G,ee;return f().wrap(function(Ce){for(;;)switch(Ce.prev=Ce.next){case 0:return Ce.next=2,this.getClientVersions();case 2:if(G=Ce.sent,G.includes(n.UnstableApiVersion.MSC3973)){Ce.next=5;break}throw new Error("The user_directory_search action is not supported by the client.");case 5:return ee={search_term:U,limit:K},Ce.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch,ee));case 7:case"end":return Ce.stop()}},j,this)}));function I(j,U){return M.apply(this,arguments)}return I}()},{key:"getMediaConfig",value:function(){var M=h(f().mark(function j(){var U,K;return f().wrap(function(ee){for(;;)switch(ee.prev=ee.next){case 0:return ee.next=2,this.getClientVersions();case 2:if(U=ee.sent,U.includes(n.UnstableApiVersion.MSC4039)){ee.next=5;break}throw new Error("The get_media_config action is not supported by the client.");case 5:return K={},ee.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC4039GetMediaConfigAction,K));case 7:case"end":return ee.stop()}},j,this)}));function I(){return M.apply(this,arguments)}return I}()},{key:"uploadFile",value:function(){var M=h(f().mark(function j(U){var K,G;return f().wrap(function(se){for(;;)switch(se.prev=se.next){case 0:return se.next=2,this.getClientVersions();case 2:if(K=se.sent,K.includes(n.UnstableApiVersion.MSC4039)){se.next=5;break}throw new Error("The upload_file action is not supported by the client.");case 5:return G={file:U},se.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC4039UploadFileAction,G));case 7:case"end":return se.stop()}},j,this)}));function I(j){return M.apply(this,arguments)}return I}()},{key:"downloadFile",value:function(){var M=h(f().mark(function j(U){var K,G;return f().wrap(function(se){for(;;)switch(se.prev=se.next){case 0:return se.next=2,this.getClientVersions();case 2:if(K=se.sent,K.includes(n.UnstableApiVersion.MSC4039)){se.next=5;break}throw new Error("The download_file action is not supported by the client.");case 5:return G={content_uri:U},se.abrupt("return",this.transport.send(o.WidgetApiFromWidgetAction.MSC4039DownloadFileAction,G));case 7:case"end":return se.stop()}},j,this)}));function I(j){return M.apply(this,arguments)}return I}()},{key:"start",value:function(){var I=this;this.transport.start(),this.getClientVersions().then(function(j){j.includes(n.UnstableApiVersion.MSC2974)&&(I.supportsMSC2974Renegotiate=!0)})}},{key:"handleMessage",value:function(I){var j=new CustomEvent("action:".concat(I.detail.action),{detail:I.detail,cancelable:!0});if(this.emit("action:".concat(I.detail.action),j),!j.defaultPrevented)switch(I.detail.action){case o.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(I.detail);case o.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(I.detail);case o.WidgetApiToWidgetAction.UpdateVisibility:return this.transport.reply(I.detail,{});case o.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(I.detail,{});default:return this.transport.reply(I.detail,{error:{message:"Unknown or unsupported to-widget action: "+I.detail.action}})}}},{key:"replyVersions",value:function(I){this.transport.reply(I,{supported_versions:n.CurrentApiVersions})}},{key:"getClientVersions",value:function(){var I=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(o.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then(function(j){return I.cachedClientVersions=j.supported_versions,j.supported_versions}).catch(function(j){return console.warn("non-fatal error getting supported client versions: ",j),[]})}},{key:"handleCapabilities",value:function(I){var j=this;return this.capabilitiesFinished?this.transport.reply(I,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then(function(U){return U.includes(n.UnstableApiVersion.MSC2871)?j.once("action:".concat(o.WidgetApiToWidgetAction.NotifyCapabilities),function(K){j.approvedCapabilities=K.detail.data.approved,j.emit("ready")}):j.emit("ready"),j.capabilitiesFinished=!0,j.transport.reply(I,{capabilities:j.requestedCapabilities})})}}]),P}(e.EventEmitter);return oa.WidgetApi=W,oa}var bu={},Jn={};Object.defineProperty(Jn,"__esModule",{value:!0});Jn.VideoConferenceCapabilities=Jn.StickerpickerCapabilities=Jn.MatrixCapabilities=void 0;Jn.getTimelineRoomIDFromCapability=Q7;Jn.isTimelineCapability=J7;Jn.isTimelineCapabilityFor=X7;var Qw=function(r){return r.Screenshots="m.capability.screenshot",r.StickerSending="m.sticker",r.AlwaysOnScreen="m.always_on_screen",r.RequiresClient="io.element.requires_client",r.MSC2931Navigate="org.matrix.msc2931.navigate",r.MSC3846TurnServers="town.robin.msc3846.turn_servers",r.MSC3973UserDirectorySearch="org.matrix.msc3973.user_directory_search",r.MSC4039UploadFile="org.matrix.msc4039.upload_file",r.MSC4039DownloadFile="org.matrix.msc4039.download_file",r.MSC4157SendDelayedEvent="org.matrix.msc4157.send.delayed_event",r.MSC4157UpdateDelayedEvent="org.matrix.msc4157.update_delayed_event",r.MSC4407SendStickyEvent="org.matrix.msc4407.send.sticky_event",r.MSC4407ReceiveStickyEvent="org.matrix.msc4407.receive.sticky_event",r}({});Jn.MatrixCapabilities=Qw;var z7=[Qw.StickerSending];Jn.StickerpickerCapabilities=z7;var Y7=[Qw.AlwaysOnScreen];Jn.VideoConferenceCapabilities=Y7;function J7(r){return r==null?void 0:r.startsWith("org.matrix.msc2762.timeline:")}function X7(r,e){return r==="org.matrix.msc2762.timeline:".concat(e)}function Q7(r){return r.substring(r.indexOf(":")+1)}var Of={};Object.defineProperty(Of,"__esModule",{value:!0});Of.SimpleObservable=void 0;function zd(r){"@babel/helpers - typeof";return zd=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zd(r)}function Z7(r,e){var t=typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=eY(r))||e){t&&(r=t);var n=0,i=function(){};return{s:i,n:function(){return n>=r.length?{done:!0}:{done:!1,value:r[n++]}},e:function(c){throw c},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
297
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){t=t.call(r)},n:function(){var c=t.next();return o=c.done,c},e:function(c){s=!0,a=c},f:function(){try{!o&&t.return!=null&&t.return()}finally{if(s)throw a}}}}function eY(r,e){if(r){if(typeof r=="string")return nI(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return nI(r,e)}}function nI(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function tY(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function rY(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,rL(n.key),n)}}function nY(r,e,t){return e&&rY(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}function iY(r,e,t){return e=rL(e),e in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function rL(r){var e=oY(r,"string");return zd(e)==="symbol"?e:String(e)}function oY(r,e){if(zd(r)!=="object"||r===null)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(zd(n)!=="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}var sY=function(){function r(e){tY(this,r),iY(this,"listeners",[]),e&&this.listeners.push(e)}return nY(r,[{key:"onUpdate",value:function(t){this.listeners.push(t)}},{key:"update",value:function(t){var n=Z7(this.listeners),i;try{for(n.s();!(i=n.n()).done;){var o=i.value;o(t)}}catch(s){n.e(s)}finally{n.f()}}},{key:"close",value:function(){this.listeners=[]}}]),r}();Of.SimpleObservable=sY;var iI;function aY(){if(iI)return bu;iI=1,Object.defineProperty(bu,"__esModule",{value:!0}),bu.ClientWidgetApi=void 0;var r=Em,e=Xw(),t=tl,n=Ls,i=Jn,o=Zi,s=eo,a=Gc,l=Of,c=Hc,u=zc;function d(B){"@babel/helpers - typeof";return d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(W){return typeof W}:function(W){return W&&typeof Symbol=="function"&&W.constructor===Symbol&&W!==Symbol.prototype?"symbol":typeof W},d(B)}function f(B,W){var A=Object.keys(B);if(Object.getOwnPropertySymbols){var D=Object.getOwnPropertySymbols(B);W&&(D=D.filter(function(P){return Object.getOwnPropertyDescriptor(B,P).enumerable})),A.push.apply(A,D)}return A}function p(B){for(var W=1;W<arguments.length;W++){var A=arguments[W]!=null?arguments[W]:{};W%2?f(Object(A),!0).forEach(function(D){q(B,D,A[D])}):Object.getOwnPropertyDescriptors?Object.defineProperties(B,Object.getOwnPropertyDescriptors(A)):f(Object(A)).forEach(function(D){Object.defineProperty(B,D,Object.getOwnPropertyDescriptor(A,D))})}return B}function h(B,W){var A=typeof Symbol<"u"&&B[Symbol.iterator]||B["@@iterator"];if(!A){if(Array.isArray(B)||(A=y(B))||W){A&&(B=A);var D=0,P=function(){};return{s:P,n:function(){return D>=B.length?{done:!0}:{done:!1,value:B[D++]}},e:function(K){throw K},f:P}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
298
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var M=!0,I=!1,j;return{s:function(){A=A.call(B)},n:function(){var K=A.next();return M=K.done,K},e:function(K){I=!0,j=K},f:function(){try{!M&&A.return!=null&&A.return()}finally{if(I)throw j}}}}function m(B){return R(B)||S(B)||y(B)||E()}function E(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
299
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function y(B,W){if(B){if(typeof B=="string")return k(B,W);var A=Object.prototype.toString.call(B).slice(8,-1);if(A==="Object"&&B.constructor&&(A=B.constructor.name),A==="Map"||A==="Set")return Array.from(B);if(A==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A))return k(B,W)}}function S(B){if(typeof Symbol<"u"&&B[Symbol.iterator]!=null||B["@@iterator"]!=null)return Array.from(B)}function R(B){if(Array.isArray(B))return k(B)}function k(B,W){(W==null||W>B.length)&&(W=B.length);for(var A=0,D=new Array(W);A<W;A++)D[A]=B[A];return D}function x(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */x=function(){return B};var B={},W=Object.prototype,A=W.hasOwnProperty,D=Object.defineProperty||function(ye,fe,J){ye[fe]=J.value},P=typeof Symbol=="function"?Symbol:{},M=P.iterator||"@@iterator",I=P.asyncIterator||"@@asyncIterator",j=P.toStringTag||"@@toStringTag";function U(ye,fe,J){return Object.defineProperty(ye,fe,{value:J,enumerable:!0,configurable:!0,writable:!0}),ye[fe]}try{U({},"")}catch{U=function(J,te,ne){return J[te]=ne}}function K(ye,fe,J,te){var ne=fe&&fe.prototype instanceof se?fe:se,ue=Object.create(ne.prototype),Ee=new mr(te||[]);return D(ue,"_invoke",{value:un(ye,J,Ee)}),ue}function G(ye,fe,J){try{return{type:"normal",arg:ye.call(fe,J)}}catch(te){return{type:"throw",arg:te}}}B.wrap=K;var ee={};function se(){}function Ce(){}function Re(){}var ge={};U(ge,M,function(){return this});var He=Object.getPrototypeOf,Qe=He&&He(He(Rt([])));Qe&&Qe!==W&&A.call(Qe,M)&&(ge=Qe);var $e=Re.prototype=se.prototype=Object.create(ge);function me(ye){["next","throw","return"].forEach(function(fe){U(ye,fe,function(J){return this._invoke(fe,J)})})}function We(ye,fe){function J(ne,ue,Ee,Te){var ze=G(ye[ne],ye,ue);if(ze.type!=="throw"){var dt=ze.arg,ht=dt.value;return ht&&d(ht)=="object"&&A.call(ht,"__await")?fe.resolve(ht.__await).then(function(Kt){J("next",Kt,Ee,Te)},function(Kt){J("throw",Kt,Ee,Te)}):fe.resolve(ht).then(function(Kt){dt.value=Kt,Ee(dt)},function(Kt){return J("throw",Kt,Ee,Te)})}Te(ze.arg)}var te;D(this,"_invoke",{value:function(ue,Ee){function Te(){return new fe(function(ze,dt){J(ue,Ee,ze,dt)})}return te=te?te.then(Te,Te):Te()}})}function un(ye,fe,J){var te="suspendedStart";return function(ne,ue){if(te==="executing")throw new Error("Generator is already running");if(te==="completed"){if(ne==="throw")throw ue;return Cn()}for(J.method=ne,J.arg=ue;;){var Ee=J.delegate;if(Ee){var Te=Rr(Ee,J);if(Te){if(Te===ee)continue;return Te}}if(J.method==="next")J.sent=J._sent=J.arg;else if(J.method==="throw"){if(te==="suspendedStart")throw te="completed",J.arg;J.dispatchException(J.arg)}else J.method==="return"&&J.abrupt("return",J.arg);te="executing";var ze=G(ye,fe,J);if(ze.type==="normal"){if(te=J.done?"completed":"suspendedYield",ze.arg===ee)continue;return{value:ze.arg,done:J.done}}ze.type==="throw"&&(te="completed",J.method="throw",J.arg=ze.arg)}}}function Rr(ye,fe){var J=fe.method,te=ye.iterator[J];if(te===void 0)return fe.delegate=null,J==="throw"&&ye.iterator.return&&(fe.method="return",fe.arg=void 0,Rr(ye,fe),fe.method==="throw")||J!=="return"&&(fe.method="throw",fe.arg=new TypeError("The iterator does not provide a '"+J+"' method")),ee;var ne=G(te,ye.iterator,fe.arg);if(ne.type==="throw")return fe.method="throw",fe.arg=ne.arg,fe.delegate=null,ee;var ue=ne.arg;return ue?ue.done?(fe[ye.resultName]=ue.value,fe.next=ye.nextLoc,fe.method!=="return"&&(fe.method="next",fe.arg=void 0),fe.delegate=null,ee):ue:(fe.method="throw",fe.arg=new TypeError("iterator result is not an object"),fe.delegate=null,ee)}function gt(ye){var fe={tryLoc:ye[0]};1 in ye&&(fe.catchLoc=ye[1]),2 in ye&&(fe.finallyLoc=ye[2],fe.afterLoc=ye[3]),this.tryEntries.push(fe)}function vr(ye){var fe=ye.completion||{};fe.type="normal",delete fe.arg,ye.completion=fe}function mr(ye){this.tryEntries=[{tryLoc:"root"}],ye.forEach(gt,this),this.reset(!0)}function Rt(ye){if(ye){var fe=ye[M];if(fe)return fe.call(ye);if(typeof ye.next=="function")return ye;if(!isNaN(ye.length)){var J=-1,te=function ne(){for(;++J<ye.length;)if(A.call(ye,J))return ne.value=ye[J],ne.done=!1,ne;return ne.value=void 0,ne.done=!0,ne};return te.next=te}}return{next:Cn}}function Cn(){return{value:void 0,done:!0}}return Ce.prototype=Re,D($e,"constructor",{value:Re,configurable:!0}),D(Re,"constructor",{value:Ce,configurable:!0}),Ce.displayName=U(Re,j,"GeneratorFunction"),B.isGeneratorFunction=function(ye){var fe=typeof ye=="function"&&ye.constructor;return!!fe&&(fe===Ce||(fe.displayName||fe.name)==="GeneratorFunction")},B.mark=function(ye){return Object.setPrototypeOf?Object.setPrototypeOf(ye,Re):(ye.__proto__=Re,U(ye,j,"GeneratorFunction")),ye.prototype=Object.create($e),ye},B.awrap=function(ye){return{__await:ye}},me(We.prototype),U(We.prototype,I,function(){return this}),B.AsyncIterator=We,B.async=function(ye,fe,J,te,ne){ne===void 0&&(ne=Promise);var ue=new We(K(ye,fe,J,te),ne);return B.isGeneratorFunction(fe)?ue:ue.next().then(function(Ee){return Ee.done?Ee.value:ue.next()})},me($e),U($e,j,"Generator"),U($e,M,function(){return this}),U($e,"toString",function(){return"[object Generator]"}),B.keys=function(ye){var fe=Object(ye),J=[];for(var te in fe)J.push(te);return J.reverse(),function ne(){for(;J.length;){var ue=J.pop();if(ue in fe)return ne.value=ue,ne.done=!1,ne}return ne.done=!0,ne}},B.values=Rt,mr.prototype={constructor:mr,reset:function(fe){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(vr),!fe)for(var J in this)J.charAt(0)==="t"&&A.call(this,J)&&!isNaN(+J.slice(1))&&(this[J]=void 0)},stop:function(){this.done=!0;var fe=this.tryEntries[0].completion;if(fe.type==="throw")throw fe.arg;return this.rval},dispatchException:function(fe){if(this.done)throw fe;var J=this;function te(dt,ht){return Ee.type="throw",Ee.arg=fe,J.next=dt,ht&&(J.method="next",J.arg=void 0),!!ht}for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ue=this.tryEntries[ne],Ee=ue.completion;if(ue.tryLoc==="root")return te("end");if(ue.tryLoc<=this.prev){var Te=A.call(ue,"catchLoc"),ze=A.call(ue,"finallyLoc");if(Te&&ze){if(this.prev<ue.catchLoc)return te(ue.catchLoc,!0);if(this.prev<ue.finallyLoc)return te(ue.finallyLoc)}else if(Te){if(this.prev<ue.catchLoc)return te(ue.catchLoc,!0)}else{if(!ze)throw new Error("try statement without catch or finally");if(this.prev<ue.finallyLoc)return te(ue.finallyLoc)}}}},abrupt:function(fe,J){for(var te=this.tryEntries.length-1;te>=0;--te){var ne=this.tryEntries[te];if(ne.tryLoc<=this.prev&&A.call(ne,"finallyLoc")&&this.prev<ne.finallyLoc){var ue=ne;break}}ue&&(fe==="break"||fe==="continue")&&ue.tryLoc<=J&&J<=ue.finallyLoc&&(ue=null);var Ee=ue?ue.completion:{};return Ee.type=fe,Ee.arg=J,ue?(this.method="next",this.next=ue.finallyLoc,ee):this.complete(Ee)},complete:function(fe,J){if(fe.type==="throw")throw fe.arg;return fe.type==="break"||fe.type==="continue"?this.next=fe.arg:fe.type==="return"?(this.rval=this.arg=fe.arg,this.method="return",this.next="end"):fe.type==="normal"&&J&&(this.next=J),ee},finish:function(fe){for(var J=this.tryEntries.length-1;J>=0;--J){var te=this.tryEntries[J];if(te.finallyLoc===fe)return this.complete(te.completion,te.afterLoc),vr(te),ee}},catch:function(fe){for(var J=this.tryEntries.length-1;J>=0;--J){var te=this.tryEntries[J];if(te.tryLoc===fe){var ne=te.completion;if(ne.type==="throw"){var ue=ne.arg;vr(te)}return ue}}throw new Error("illegal catch attempt")},delegateYield:function(fe,J,te){return this.delegate={iterator:Rt(fe),resultName:J,nextLoc:te},this.method==="next"&&(this.arg=void 0),ee}},B}function T(B,W,A,D,P,M,I){try{var j=B[M](I),U=j.value}catch(K){A(K);return}j.done?W(U):Promise.resolve(U).then(D,P)}function O(B){return function(){var W=this,A=arguments;return new Promise(function(D,P){var M=B.apply(W,A);function I(U){T(M,D,P,I,j,"next",U)}function j(U){T(M,D,P,I,j,"throw",U)}I(void 0)})}}function C(B,W){if(!(B instanceof W))throw new TypeError("Cannot call a class as a function")}function N(B,W){for(var A=0;A<W.length;A++){var D=W[A];D.enumerable=D.enumerable||!1,D.configurable=!0,"value"in D&&(D.writable=!0),Object.defineProperty(B,z(D.key),D)}}function F(B,W,A){return W&&N(B.prototype,W),Object.defineProperty(B,"prototype",{writable:!1}),B}function H(B,W){if(typeof W!="function"&&W!==null)throw new TypeError("Super expression must either be null or a function");B.prototype=Object.create(W&&W.prototype,{constructor:{value:B,writable:!0,configurable:!0}}),Object.defineProperty(B,"prototype",{writable:!1}),W&&ie(B,W)}function ie(B,W){return ie=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(D,P){return D.__proto__=P,D},ie(B,W)}function $(B){var W=re();return function(){var D=ae(B),P;if(W){var M=ae(this).constructor;P=Reflect.construct(D,arguments,M)}else P=D.apply(this,arguments);return X(this,P)}}function X(B,W){if(W&&(d(W)==="object"||typeof W=="function"))return W;if(W!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return oe(B)}function oe(B){if(B===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return B}function re(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function ae(B){return ae=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(A){return A.__proto__||Object.getPrototypeOf(A)},ae(B)}function q(B,W,A){return W=z(W),W in B?Object.defineProperty(B,W,{value:A,enumerable:!0,configurable:!0,writable:!0}):B[W]=A,B}function z(B){var W=Q(B,"string");return d(W)==="symbol"?W:String(W)}function Q(B,W){if(d(B)!=="object"||B===null)return B;var A=B[Symbol.toPrimitive];if(A!==void 0){var D=A.call(B,W);if(d(D)!=="object")return D;throw new TypeError("@@toPrimitive must return a primitive value.")}return(W==="string"?String:Number)(B)}function Ie(B){var W,A,D,P=2;for(typeof Symbol<"u"&&(A=Symbol.asyncIterator,D=Symbol.iterator);P--;){if(A&&(W=B[A])!=null)return W.call(B);if(D&&(W=B[D])!=null)return new Y(W.call(B));A="@@asyncIterator",D="@@iterator"}throw new TypeError("Object is not async iterable")}function Y(B){function W(A){if(Object(A)!==A)return Promise.reject(new TypeError(A+" is not an object."));var D=A.done;return Promise.resolve(A.value).then(function(P){return{value:P,done:D}})}return Y=function(D){this.s=D,this.n=D.next},Y.prototype={s:null,n:null,next:function(){return W(this.n.apply(this.s,arguments))},return:function(D){var P=this.s.return;return P===void 0?Promise.resolve({value:D,done:!0}):W(P.apply(this.s,arguments))},throw:function(D){var P=this.s.return;return P===void 0?Promise.reject(D):W(P.apply(this.s,arguments))}},new Y(B)}var le=function(B){H(A,B);var W=$(A);function A(D,P,M){var I;if(C(this,A),I=W.call(this),I.widget=D,I.driver=M,q(oe(I),"transport",void 0),q(oe(I),"cachedWidgetVersions",null),q(oe(I),"contentLoadedActionSent",!1),q(oe(I),"allowedCapabilities",new Set),q(oe(I),"allowedEvents",[]),q(oe(I),"isStopped",!1),q(oe(I),"turnServers",null),q(oe(I),"contentLoadedWaitTimer",void 0),q(oe(I),"pushRoomStateTasks",new Set),q(oe(I),"pushRoomStateResult",new Map),q(oe(I),"flushRoomStateTask",null),q(oe(I),"viewedRoomId",null),!(P!=null&&P.contentWindow))throw new Error("No iframe supplied");if(!D)throw new Error("Invalid widget");if(!M)throw new Error("Invalid driver");return I.transport=new e.PostmessageTransport(t.WidgetApiDirection.ToWidget,D.id,P.contentWindow,globalThis),I.transport.targetOrigin=D.origin,I.transport.on("message",I.handleMessage.bind(oe(I))),P.addEventListener("load",I.onIframeLoad.bind(oe(I))),I.transport.start(),I}return F(A,[{key:"hasCapability",value:function(P){return this.allowedCapabilities.has(P)}},{key:"canUseRoomTimeline",value:function(P){return this.hasCapability("org.matrix.msc2762.timeline:".concat(c.Symbols.AnyRoom))||this.hasCapability("org.matrix.msc2762.timeline:".concat(P))}},{key:"canSendRoomEvent",value:function(P){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(I){return I.matchesAsRoomEvent(s.EventDirection.Send,P,M)})}},{key:"canSendStateEvent",value:function(P,M){return this.allowedEvents.some(function(I){return I.matchesAsStateEvent(s.EventDirection.Send,P,M)})}},{key:"canSendToDeviceEvent",value:function(P){return this.allowedEvents.some(function(M){return M.matchesAsToDeviceEvent(s.EventDirection.Send,P)})}},{key:"canReceiveRoomEvent",value:function(P){var M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return this.allowedEvents.some(function(I){return I.matchesAsRoomEvent(s.EventDirection.Receive,P,M)})}},{key:"canReceiveStateEvent",value:function(P,M){return this.allowedEvents.some(function(I){return I.matchesAsStateEvent(s.EventDirection.Receive,P,M)})}},{key:"canReceiveToDeviceEvent",value:function(P){return this.allowedEvents.some(function(M){return M.matchesAsToDeviceEvent(s.EventDirection.Receive,P)})}},{key:"canReceiveRoomAccountData",value:function(P){return this.allowedEvents.some(function(M){return M.matchesAsRoomAccountData(s.EventDirection.Receive,P)})}},{key:"stop",value:function(){this.isStopped=!0,this.transport.stop()}},{key:"getWidgetVersions",value:function(){var D=O(x().mark(function M(){var I;return x().wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(!Array.isArray(this.cachedWidgetVersions)){U.next=2;break}return U.abrupt("return",this.cachedWidgetVersions);case 2:return U.prev=2,U.next=5,this.transport.send(n.WidgetApiToWidgetAction.SupportedApiVersions,{});case 5:return I=U.sent,this.cachedWidgetVersions=I.supported_versions,U.abrupt("return",I.supported_versions);case 10:return U.prev=10,U.t0=U.catch(2),console.warn("non-fatal error getting supported widget versions: ",U.t0),U.abrupt("return",[]);case 14:case"end":return U.stop()}},M,this,[[2,10]])}));function P(){return D.apply(this,arguments)}return P}()},{key:"beginCapabilities",value:function(){var P=this;this.emit("preparing");var M;this.transport.send(n.WidgetApiToWidgetAction.Capabilities,{}).then(function(I){return M=I.capabilities,P.driver.validateCapabilities(new Set(I.capabilities))}).then(function(I){P.allowCapabilities(m(I),M),P.emit("ready")}).catch(function(I){P.emit("error:preparing",I)})}},{key:"allowCapabilities",value:function(P,M){var I,j=this;console.log("Widget ".concat(this.widget.id," is allowed capabilities:"),P);var U=h(P),K;try{for(U.s();!(K=U.n()).done;){var G=K.value;this.allowedCapabilities.add(G)}}catch(gt){U.e(gt)}finally{U.f()}var ee=s.WidgetEventCapability.findEventCapabilities(P);(I=this.allowedEvents).push.apply(I,m(ee)),this.transport.send(n.WidgetApiToWidgetAction.NotifyCapabilities,{requested:M,approved:Array.from(this.allowedCapabilities)}).catch(function(gt){console.warn("non-fatal error notifying widget of approved capabilities:",gt)}).then(function(){j.emit("capabilitiesNotified")});var se=h(P),Ce;try{for(se.s();!(Ce=se.n()).done;){var Re=Ce.value;if((0,i.isTimelineCapability)(Re)){var ge=(0,i.getTimelineRoomIDFromCapability)(Re);if(ge===c.Symbols.AnyRoom){var He=h(this.driver.getKnownRooms()),Qe;try{for(He.s();!(Qe=He.n()).done;){var $e=Qe.value;this.pushRoomState($e)}}catch(gt){He.e(gt)}finally{He.f()}}else this.pushRoomState(ge)}}}catch(gt){se.e(gt)}finally{se.f()}if(P.includes(i.MatrixCapabilities.MSC4407ReceiveStickyEvent)){console.debug("Widget ".concat(this.widget.id," is allowed to receive sticky events, check current sticky state."));var me=P.filter(function(gt){return(0,i.isTimelineCapability)(gt)}).map(function(gt){return(0,i.getTimelineRoomIDFromCapability)(gt)}).flatMap(function(gt){return gt===c.Symbols.AnyRoom?j.driver.getKnownRooms():gt});console.debug("Widget ".concat(this.widget.id," is allowed to receive sticky events in rooms:"),me);var We=h(me),un;try{var Rr=function(){var vr=un.value;j.pushStickyState(vr).catch(function(mr){console.error("Failed to push sticky events to widget ".concat(j.widget.id," for room ").concat(vr,":"),mr)})};for(We.s();!(un=We.n()).done;)Rr()}catch(gt){We.e(gt)}finally{We.f()}}ee.length>0&&this.viewedRoomId!==null&&!this.canUseRoomTimeline(this.viewedRoomId)&&this.pushRoomState(this.viewedRoomId)}},{key:"onIframeLoad",value:function(P){this.widget.waitForIframeLoad?this.beginCapabilities():(console.log("waitForIframeLoad is false: waiting for widget to send contentLoaded"),this.contentLoadedWaitTimer=setTimeout(function(){console.error("Widget specified waitForIframeLoad=false but timed out waiting for contentLoaded event!")},1e4),this.contentLoadedActionSent=!1)}},{key:"handleContentLoadedAction",value:function(P){if(this.contentLoadedWaitTimer!==void 0&&(clearTimeout(this.contentLoadedWaitTimer),this.contentLoadedWaitTimer=void 0),this.contentLoadedActionSent)throw new Error("Improper sequence: ContentLoaded Action can only be sent once after the widget loaded and should only be used if waitForIframeLoad is false (default=true)");this.widget.waitForIframeLoad?this.transport.reply(P,{error:{message:"Improper sequence: not expecting ContentLoaded event if waitForIframeLoad is true (default=true)"}}):(this.transport.reply(P,{}),this.beginCapabilities()),this.contentLoadedActionSent=!0}},{key:"replyVersions",value:function(P){this.transport.reply(P,{supported_versions:o.CurrentApiVersions})}},{key:"supportsUpdateState",value:function(){var D=O(x().mark(function M(){return x().wrap(function(j){for(;;)switch(j.prev=j.next){case 0:return j.next=2,this.getWidgetVersions();case 2:return j.abrupt("return",j.sent.includes(o.UnstableApiVersion.MSC2762_UPDATE_STATE));case 3:case"end":return j.stop()}},M,this)}));function P(){return D.apply(this,arguments)}return P}()},{key:"handleCapabilitiesRenegotiate",value:function(P){var M,I=this;this.transport.reply(P,{});var j=((M=P.data)===null||M===void 0?void 0:M.capabilities)||[],U=new Set(j.filter(function(K){return!I.hasCapability(K)}));U.size===0&&this.allowCapabilities([],[]),this.driver.validateCapabilities(U).then(function(K){return I.allowCapabilities(m(K),m(U))})}},{key:"handleNavigate",value:function(P){var M,I=this;if(!this.hasCapability(i.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(P,{error:{message:"Missing capability"}});if(!((M=P.data)!==null&&M!==void 0&&M.uri.startsWith("https://matrix.to/#")))return this.transport.reply(P,{error:{message:"Invalid matrix.to URI"}});var j=function(K){console.error("[ClientWidgetApi] Failed to handle navigation: ",K),I.handleDriverError(K,P,"Error handling navigation")};try{this.driver.navigate(P.data.uri.toString()).catch(function(U){return j(U)}).then(function(){return I.transport.reply(P,{})})}catch(U){return j(U)}}},{key:"handleOIDC",value:function(P){var M=this,I=1,j=function(ee,se){return se=se||{},I>1?M.transport.send(n.WidgetApiToWidgetAction.OpenIDCredentials,p({state:ee,original_request_id:P.requestId},se)):M.transport.reply(P,p({state:ee},se))},U=function(ee){return console.error("[ClientWidgetApi] Failed to handle OIDC: ",ee),I>1?j(a.OpenIDRequestState.Blocked):M.transport.reply(P,{error:{message:ee}})},K=new l.SimpleObservable(function(G){if(G.state===a.OpenIDRequestState.PendingUserConfirmation&&I>1)return K.close(),U("client provided out-of-phase response to OIDC flow");if(G.state===a.OpenIDRequestState.PendingUserConfirmation){j(G.state),I++;return}return G.state===a.OpenIDRequestState.Allowed&&!G.token?U("client provided invalid OIDC token for an allowed request"):(G.state===a.OpenIDRequestState.Blocked&&(G.token=void 0),K.close(),j(G.state,G.token))});this.driver.askOpenID(K)}},{key:"handleReadRoomAccountData",value:function(P){var M=this,I=this.driver.readRoomAccountData(P.data.type);return this.canReceiveRoomAccountData(P.data.type)?I.then(function(j){M.transport.reply(P,{events:j})}):this.transport.reply(P,{error:{message:"Cannot read room account data of this type"}})}},{key:"handleReadEvents",value:function(){var D=O(x().mark(function M(I){var j=this,U,K,G,ee,se,Ce,Re,ge,He,Qe;return x().wrap(function(me){for(;;)switch(me.prev=me.next){case 0:if(I.data.type){me.next=2;break}return me.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - missing event type"}}));case 2:if(!(I.data.limit!==void 0&&(!I.data.limit||I.data.limit<0))){me.next=4;break}return me.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - limit out of range"}}));case 4:if(I.data.room_ids!==void 0){me.next=8;break}U=this.viewedRoomId===null?[]:[this.viewedRoomId],me.next=30;break;case 8:if(I.data.room_ids!==c.Symbols.AnyRoom){me.next=12;break}U=this.driver.getKnownRooms().filter(function(We){return j.canUseRoomTimeline(We)}),me.next=30;break;case 12:U=I.data.room_ids,K=h(U),me.prev=14,K.s();case 16:if((G=K.n()).done){me.next=22;break}if(ee=G.value,this.canUseRoomTimeline(ee)){me.next=20;break}return me.abrupt("return",this.transport.reply(I,{error:{message:"Unable to access room timeline: ".concat(ee)}}));case 20:me.next=16;break;case 22:me.next=27;break;case 24:me.prev=24,me.t0=me.catch(14),K.e(me.t0);case 27:return me.prev=27,K.f(),me.finish(27);case 30:if(se=I.data.limit||0,Ce=I.data.since,Re=void 0,ge=void 0,I.data.state_key===void 0){me.next=40;break}if(Re=I.data.state_key===!0?void 0:I.data.state_key.toString(),this.canReceiveStateEvent(I.data.type,(He=Re)!==null&&He!==void 0?He:null)){me.next=38;break}return me.abrupt("return",this.transport.reply(I,{error:{message:"Cannot read state events of this type"}}));case 38:me.next=43;break;case 40:if(ge=I.data.msgtype,this.canReceiveRoomEvent(I.data.type,ge)){me.next=43;break}return me.abrupt("return",this.transport.reply(I,{error:{message:"Cannot read room events of this type"}}));case 43:if(!(I.data.room_ids===void 0&&U.length===0)){me.next=50;break}return console.warn("The widgetDriver uses deprecated behaviour:\n It does not set the viewedRoomId using `setViewedRoomId`"),me.next=47,I.data.state_key===void 0?this.driver.readRoomEvents(I.data.type,ge,se,null,Ce):this.driver.readStateEvents(I.data.type,Re,se,null);case 47:Qe=me.sent,me.next=68;break;case 50:return me.next=52,this.supportsUpdateState();case 52:if(!me.sent){me.next=58;break}return me.next=55,Promise.all(U.map(function(We){return j.driver.readRoomTimeline(We,I.data.type,ge,Re,se,Ce)}));case 55:Qe=me.sent.flat(1),me.next=68;break;case 58:if(I.data.state_key!==void 0){me.next=64;break}return me.next=61,Promise.all(U.map(function(We){return j.driver.readRoomTimeline(We,I.data.type,ge,Re,se,Ce)}));case 61:me.t1=me.sent,me.next=67;break;case 64:return me.next=66,Promise.all(U.map(function(We){return j.driver.readRoomState(We,I.data.type,Re)}));case 66:me.t1=me.sent;case 67:Qe=me.t1.flat(1);case 68:this.transport.reply(I,{events:Qe});case 69:case"end":return me.stop()}},M,this,[[14,24,27,30]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleSendEvent",value:function(P){var M=this;if(!P.data.type)return this.transport.reply(P,{error:{message:"Invalid request - missing event type"}});if(P.data.room_id&&!this.canUseRoomTimeline(P.data.room_id))return this.transport.reply(P,{error:{message:"Unable to access room timeline: ".concat(P.data.room_id)}});var I=P.data.delay!==void 0||P.data.parent_delay_id!==void 0;if(I&&!this.hasCapability(i.MatrixCapabilities.MSC4157SendDelayedEvent))return this.transport.reply(P,{error:{message:"Missing capability for ".concat(i.MatrixCapabilities.MSC4157SendDelayedEvent)}});var j=P.data.sticky_duration_ms!==void 0;if(j&&!this.hasCapability(i.MatrixCapabilities.MSC4407SendStickyEvent))return this.transport.reply(P,{error:{message:"Missing capability for ".concat(i.MatrixCapabilities.MSC4407SendStickyEvent)}});var U;if(P.data.state_key!==void 0){if(!this.canSendStateEvent(P.data.type,P.data.state_key))return this.transport.reply(P,{error:{message:"Cannot send state events of this type"}});if(j)return this.transport.reply(P,{error:{message:"Cannot send a state event with a sticky duration"}});if(I){var K,G;U=this.driver.sendDelayedEvent((K=P.data.delay)!==null&&K!==void 0?K:null,(G=P.data.parent_delay_id)!==null&&G!==void 0?G:null,P.data.type,P.data.content||{},P.data.state_key,P.data.room_id)}else U=this.driver.sendEvent(P.data.type,P.data.content||{},P.data.state_key,P.data.room_id)}else{var ee=P.data.content||{},se=ee.msgtype;if(!this.canSendRoomEvent(P.data.type,se))return this.transport.reply(P,{error:{message:"Cannot send room events of this type"}});var Ce=[P.data.type,ee,null,P.data.room_id];if(I&&P.data.sticky_duration_ms){var Re,ge;U=this.driver.sendDelayedStickyEvent((Re=P.data.delay)!==null&&Re!==void 0?Re:null,(ge=P.data.parent_delay_id)!==null&&ge!==void 0?ge:null,P.data.sticky_duration_ms,P.data.type,ee,P.data.room_id)}else if(I){var He,Qe,$e;U=(He=this.driver).sendDelayedEvent.apply(He,[(Qe=P.data.delay)!==null&&Qe!==void 0?Qe:null,($e=P.data.parent_delay_id)!==null&&$e!==void 0?$e:null].concat(Ce))}else if(P.data.sticky_duration_ms)U=this.driver.sendStickyEvent(P.data.sticky_duration_ms,P.data.type,ee,P.data.room_id);else{var me;U=(me=this.driver).sendEvent.apply(me,Ce)}}U.then(function(We){return M.transport.reply(P,p({room_id:We.roomId},"eventId"in We?{event_id:We.eventId}:{delay_id:We.delayId}))}).catch(function(We){console.error("error sending event: ",We),M.handleDriverError(We,P,"Error sending event")})}},{key:"handleUpdateDelayedEvent",value:function(P){var M=this;if(!P.data.delay_id)return this.transport.reply(P,{error:{message:"Invalid request - missing delay_id"}});if(!this.hasCapability(i.MatrixCapabilities.MSC4157UpdateDelayedEvent))return this.transport.reply(P,{error:{message:"Missing capability"}});var I;switch(P.data.action){case u.UpdateDelayedEventAction.Cancel:I=this.driver.cancelScheduledDelayedEvent;break;case u.UpdateDelayedEventAction.Restart:I=this.driver.restartScheduledDelayedEvent;break;case u.UpdateDelayedEventAction.Send:I=this.driver.sendScheduledDelayedEvent;break;default:return this.transport.reply(P,{error:{message:"Invalid request - unsupported action"}})}I.call(this.driver,P.data.delay_id).then(function(){return M.transport.reply(P,{})}).catch(function(j){console.error("error updating delayed event: ",j),M.handleDriverError(j,P,"Error updating delayed event")})}},{key:"handleSendToDevice",value:function(){var D=O(x().mark(function M(I){return x().wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(I.data.type){U.next=4;break}this.transport.reply(I,{error:{message:"Invalid request - missing event type"}}),U.next=26;break;case 4:if(I.data.messages){U.next=8;break}this.transport.reply(I,{error:{message:"Invalid request - missing event contents"}}),U.next=26;break;case 8:if(typeof I.data.encrypted=="boolean"){U.next=12;break}this.transport.reply(I,{error:{message:"Invalid request - missing encryption flag"}}),U.next=26;break;case 12:if(this.canSendToDeviceEvent(I.data.type)){U.next=16;break}this.transport.reply(I,{error:{message:"Cannot send to-device events of this type"}}),U.next=26;break;case 16:return U.prev=16,U.next=19,this.driver.sendToDevice(I.data.type,I.data.encrypted,I.data.messages);case 19:this.transport.reply(I,{}),U.next=26;break;case 22:U.prev=22,U.t0=U.catch(16),console.error("error sending to-device event",U.t0),this.handleDriverError(U.t0,I,"Error sending event");case 26:case"end":return U.stop()}},M,this,[[16,22]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"pollTurnServers",value:function(){var D=O(x().mark(function M(I,j){var U,K,G,ee,se,Ce;return x().wrap(function(ge){for(;;)switch(ge.prev=ge.next){case 0:return ge.prev=0,ge.next=3,this.transport.send(n.WidgetApiToWidgetAction.UpdateTurnServers,j);case 3:U=!1,K=!1,ge.prev=5,ee=Ie(I);case 7:return ge.next=9,ee.next();case 9:if(!(U=!(se=ge.sent).done)){ge.next=16;break}return Ce=se.value,ge.next=13,this.transport.send(n.WidgetApiToWidgetAction.UpdateTurnServers,Ce);case 13:U=!1,ge.next=7;break;case 16:ge.next=22;break;case 18:ge.prev=18,ge.t0=ge.catch(5),K=!0,G=ge.t0;case 22:if(ge.prev=22,ge.prev=23,!(U&&ee.return!=null)){ge.next=27;break}return ge.next=27,ee.return();case 27:if(ge.prev=27,!K){ge.next=30;break}throw G;case 30:return ge.finish(27);case 31:return ge.finish(22);case 32:ge.next=37;break;case 34:ge.prev=34,ge.t1=ge.catch(0),console.error("error polling for TURN servers",ge.t1);case 37:case"end":return ge.stop()}},M,this,[[0,34],[5,18,22,32],[23,,27,31]])}));function P(M,I){return D.apply(this,arguments)}return P}()},{key:"handleWatchTurnServers",value:function(){var D=O(x().mark(function M(I){var j,U,K,G;return x().wrap(function(se){for(;;)switch(se.prev=se.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC3846TurnServers)){se.next=4;break}this.transport.reply(I,{error:{message:"Missing capability"}}),se.next=26;break;case 4:if(!this.turnServers){se.next=8;break}this.transport.reply(I,{}),se.next=26;break;case 8:return se.prev=8,j=this.driver.getTurnServers(),se.next=12,j.next();case 12:if(U=se.sent,K=U.done,G=U.value,!K){se.next=17;break}throw new Error("Client refuses to provide any TURN servers");case 17:this.transport.reply(I,{}),this.pollTurnServers(j,G),this.turnServers=j,se.next=26;break;case 22:se.prev=22,se.t0=se.catch(8),console.error("error getting first TURN server results",se.t0),this.transport.reply(I,{error:{message:"TURN servers not available"}});case 26:case"end":return se.stop()}},M,this,[[8,22]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleUnwatchTurnServers",value:function(){var D=O(x().mark(function M(I){return x().wrap(function(U){for(;;)switch(U.prev=U.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC3846TurnServers)){U.next=4;break}this.transport.reply(I,{error:{message:"Missing capability"}}),U.next=12;break;case 4:if(this.turnServers){U.next=8;break}this.transport.reply(I,{}),U.next=12;break;case 8:return U.next=10,this.turnServers.return(void 0);case 10:this.turnServers=null,this.transport.reply(I,{});case 12:case"end":return U.stop()}},M,this)}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleReadRelations",value:function(){var D=O(x().mark(function M(I){var j=this,U,K;return x().wrap(function(ee){for(;;)switch(ee.prev=ee.next){case 0:if(I.data.event_id){ee.next=2;break}return ee.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - missing event ID"}}));case 2:if(!(I.data.limit!==void 0&&I.data.limit<0)){ee.next=4;break}return ee.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - limit out of range"}}));case 4:if(!(I.data.room_id!==void 0&&!this.canUseRoomTimeline(I.data.room_id))){ee.next=6;break}return ee.abrupt("return",this.transport.reply(I,{error:{message:"Unable to access room timeline: ".concat(I.data.room_id)}}));case 6:return ee.prev=6,ee.next=9,this.driver.readEventRelations(I.data.event_id,I.data.room_id,I.data.rel_type,I.data.event_type,I.data.from,I.data.to,I.data.limit,I.data.direction);case 9:return U=ee.sent,K=U.chunk.filter(function(se){return se.state_key!==void 0?j.canReceiveStateEvent(se.type,se.state_key):j.canReceiveRoomEvent(se.type,se.content.msgtype)}),ee.abrupt("return",this.transport.reply(I,{chunk:K,prev_batch:U.prevBatch,next_batch:U.nextBatch}));case 14:ee.prev=14,ee.t0=ee.catch(6),console.error("error getting the relations",ee.t0),this.handleDriverError(ee.t0,I,"Unexpected error while reading relations");case 18:case"end":return ee.stop()}},M,this,[[6,14]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleUserDirectorySearch",value:function(){var D=O(x().mark(function M(I){var j;return x().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC3973UserDirectorySearch)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:if(typeof I.data.search_term=="string"){K.next=4;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - missing search term"}}));case 4:if(!(I.data.limit!==void 0&&I.data.limit<0)){K.next=6;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Invalid request - limit out of range"}}));case 6:return K.prev=6,K.next=9,this.driver.searchUserDirectory(I.data.search_term,I.data.limit);case 9:return j=K.sent,K.abrupt("return",this.transport.reply(I,{limited:j.limited,results:j.results.map(function(G){return{user_id:G.userId,display_name:G.displayName,avatar_url:G.avatarUrl}})}));case 13:K.prev=13,K.t0=K.catch(6),console.error("error searching in the user directory",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while searching in the user directory");case 17:case"end":return K.stop()}},M,this,[[6,13]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleGetMediaConfig",value:function(){var D=O(x().mark(function M(I){var j;return x().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC4039UploadFile)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:return K.prev=2,K.next=5,this.driver.getMediaConfig();case 5:return j=K.sent,K.abrupt("return",this.transport.reply(I,j));case 9:K.prev=9,K.t0=K.catch(2),console.error("error while getting the media configuration",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while getting the media configuration");case 13:case"end":return K.stop()}},M,this,[[2,9]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleUploadFile",value:function(){var D=O(x().mark(function M(I){var j;return x().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC4039UploadFile)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:return K.prev=2,K.next=5,this.driver.uploadFile(I.data.file);case 5:return j=K.sent,K.abrupt("return",this.transport.reply(I,{content_uri:j.contentUri}));case 9:K.prev=9,K.t0=K.catch(2),console.error("error while uploading a file",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while uploading a file");case 13:case"end":return K.stop()}},M,this,[[2,9]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleDownloadFile",value:function(){var D=O(x().mark(function M(I){var j;return x().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(this.hasCapability(i.MatrixCapabilities.MSC4039DownloadFile)){K.next=2;break}return K.abrupt("return",this.transport.reply(I,{error:{message:"Missing capability"}}));case 2:return K.prev=2,K.next=5,this.driver.downloadFile(I.data.content_uri);case 5:return j=K.sent,K.abrupt("return",this.transport.reply(I,{file:j.file}));case 9:K.prev=9,K.t0=K.catch(2),console.error("error while downloading a file",K.t0),this.handleDriverError(K.t0,I,"Unexpected error while downloading a file");case 13:case"end":return K.stop()}},M,this,[[2,9]])}));function P(M){return D.apply(this,arguments)}return P}()},{key:"handleDriverError",value:function(P,M,I){var j=this.driver.processError(P);this.transport.reply(M,{error:p({message:I},j)})}},{key:"handleMessage",value:function(P){if(!this.isStopped){var M=new CustomEvent("action:".concat(P.detail.action),{detail:P.detail,cancelable:!0});if(this.emit("action:".concat(P.detail.action),M),!M.defaultPrevented)switch(P.detail.action){case n.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(P.detail);case n.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(P.detail);case n.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(P.detail);case n.WidgetApiFromWidgetAction.SendToDevice:return this.handleSendToDevice(P.detail);case n.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(P.detail);case n.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(P.detail);case n.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(P.detail);case n.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(P.detail);case n.WidgetApiFromWidgetAction.WatchTurnServers:return this.handleWatchTurnServers(P.detail);case n.WidgetApiFromWidgetAction.UnwatchTurnServers:return this.handleUnwatchTurnServers(P.detail);case n.WidgetApiFromWidgetAction.MSC3869ReadRelations:return this.handleReadRelations(P.detail);case n.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch:return this.handleUserDirectorySearch(P.detail);case n.WidgetApiFromWidgetAction.BeeperReadRoomAccountData:return this.handleReadRoomAccountData(P.detail);case n.WidgetApiFromWidgetAction.MSC4039GetMediaConfigAction:return this.handleGetMediaConfig(P.detail);case n.WidgetApiFromWidgetAction.MSC4039UploadFileAction:return this.handleUploadFile(P.detail);case n.WidgetApiFromWidgetAction.MSC4039DownloadFileAction:return this.handleDownloadFile(P.detail);case n.WidgetApiFromWidgetAction.MSC4157UpdateDelayedEvent:return this.handleUpdateDelayedEvent(P.detail);default:return this.transport.reply(P.detail,{error:{message:"Unknown or unsupported from-widget action: "+P.detail.action}})}}}},{key:"updateTheme",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.ThemeChange,P)}},{key:"updateLanguage",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.LanguageChange,{lang:P})}},{key:"takeScreenshot",value:function(){return this.transport.send(n.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:"updateVisibility",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.UpdateVisibility,{visible:P})}},{key:"sendWidgetConfig",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.WidgetConfig,P).then()}},{key:"notifyModalWidgetButtonClicked",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.ButtonClicked,{id:P}).then()}},{key:"notifyModalWidgetClose",value:function(P){return this.transport.send(n.WidgetApiToWidgetAction.CloseModalWidget,P).then()}},{key:"feedEvent",value:function(){var D=O(x().mark(function M(I,j){var U;return x().wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(j!==void 0&&this.setViewedRoomId(j),!(I.room_id!==this.viewedRoomId&&!this.canUseRoomTimeline(I.room_id))){G.next=3;break}return G.abrupt("return");case 3:if(!(I.state_key!==void 0&&I.state_key!==null)){G.next=8;break}if(this.canReceiveStateEvent(I.type,I.state_key)){G.next=6;break}return G.abrupt("return");case 6:G.next=10;break;case 8:if(this.canReceiveRoomEvent(I.type,(U=I.content)===null||U===void 0?void 0:U.msgtype)){G.next=10;break}return G.abrupt("return");case 10:return G.next=12,this.transport.send(n.WidgetApiToWidgetAction.SendEvent,I);case 12:case"end":return G.stop()}},M,this)}));function P(M,I){return D.apply(this,arguments)}return P}()},{key:"feedToDevice",value:function(){var D=O(x().mark(function M(I,j){return x().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:if(!this.canReceiveToDeviceEvent(I.type)){K.next=3;break}return K.next=3,this.transport.send(n.WidgetApiToWidgetAction.SendToDevice,p(p({},I),{},{encrypted:j}));case 3:case"end":return K.stop()}},M,this)}));function P(M,I){return D.apply(this,arguments)}return P}()},{key:"setViewedRoomId",value:function(P){this.viewedRoomId=P,P!==null&&!this.canUseRoomTimeline(P)&&this.pushRoomState(P)}},{key:"flushRoomState",value:function(){var D=O(x().mark(function M(){var I,j,U,K,G,ee,se;return x().wrap(function(Re){for(;;)switch(Re.prev=Re.next){case 0:Re.prev=0;case 1:return Re.next=3,Promise.all(this.pushRoomStateTasks);case 3:if(this.pushRoomStateTasks.size>0){Re.next=1;break}case 4:I=[],j=h(this.pushRoomStateResult.values());try{for(j.s();!(U=j.n()).done;){K=U.value,G=h(K.values());try{for(G.s();!(ee=G.n()).done;)se=ee.value,I.push.apply(I,m(se.values()))}catch(ge){G.e(ge)}finally{G.f()}}}catch(ge){j.e(ge)}finally{j.f()}return Re.next=9,this.getWidgetVersions();case 9:if(!Re.sent.includes(o.UnstableApiVersion.MSC2762_UPDATE_STATE)){Re.next=12;break}return Re.next=12,this.transport.send(n.WidgetApiToWidgetAction.UpdateState,{state:I});case 12:return Re.prev=12,this.flushRoomStateTask=null,Re.finish(12);case 15:case"end":return Re.stop()}},M,this,[[0,,12,15]])}));function P(){return D.apply(this,arguments)}return P}()},{key:"pushStickyState",value:function(){var D=O(x().mark(function M(I){var j=this;return x().wrap(function(K){for(;;)switch(K.prev=K.next){case 0:return console.debug("Pushing sticky state to widget for room",I),K.abrupt("return",this.driver.readStickyEvents(I).then(function(G){var ee=G.filter(function(se){var Ce;return j.canReceiveRoomEvent(se.type,typeof((Ce=se.content)===null||Ce===void 0?void 0:Ce.msgtype)=="string"?se.content.msgtype:null)});return{roomId:I,stickyEvents:ee}}).then(function(){var G=O(x().mark(function ee(se){var Ce,Re,ge;return x().wrap(function(Qe){for(;;)switch(Qe.prev=Qe.next){case 0:return Ce=se.roomId,Re=se.stickyEvents,console.debug("Pushing",Re.length,"sticky events to widget for room",Ce),ge=Re.map(function($e){return j.transport.send(n.WidgetApiToWidgetAction.SendEvent,$e)}),Qe.next=5,Promise.all(ge);case 5:case"end":return Qe.stop()}},ee)}));return function(ee){return G.apply(this,arguments)}}()));case 2:case"end":return K.stop()}},M,this)}));function P(M){return D.apply(this,arguments)}return P}()},{key:"pushRoomState",value:function(P){var M=this,I=h(this.allowedEvents),j;try{var U=function(){var G=j.value;if(G.kind===s.EventKind.State&&G.direction===s.EventDirection.Receive){var ee,se,Ce=M.driver.readRoomState(P,G.eventType,(ee=G.keyStr)!==null&&ee!==void 0?ee:void 0),Re=Ce.then(function(ge){var He=h(ge),Qe;try{for(He.s();!(Qe=He.n()).done;){var $e=Qe.value,me=M.pushRoomStateResult.get(P);me===void 0&&(me=new Map,M.pushRoomStateResult.set(P,me));var We=me.get(G.eventType);We===void 0&&(We=new Map,me.set(G.eventType,We)),We.has($e.state_key)||We.set($e.state_key,$e)}}catch(un){He.e(un)}finally{He.f()}},function(ge){return console.error("Failed to read room state for ".concat(P," (").concat(G.eventType,", ").concat(G.keyStr,")"),ge)}).then(function(){M.pushRoomStateTasks.delete(Re)});M.pushRoomStateTasks.add(Re),(se=M.flushRoomStateTask)!==null&&se!==void 0||(M.flushRoomStateTask=M.flushRoomState()),M.flushRoomStateTask.catch(function(ge){return console.error("Failed to push room state",ge)})}};for(I.s();!(j=I.n()).done;)U()}catch(K){I.e(K)}finally{I.f()}}},{key:"feedStateUpdate",value:function(){var D=O(x().mark(function M(I){var j,U;return x().wrap(function(G){for(;;)switch(G.prev=G.next){case 0:if(I.state_key!==void 0){G.next=2;break}throw new Error("Not a state event");case 2:if(!((I.room_id===this.viewedRoomId||this.canUseRoomTimeline(I.room_id))&&this.canReceiveStateEvent(I.type,I.state_key))){G.next=21;break}if(this.pushRoomStateTasks.size!==0){G.next=11;break}return G.next=6,this.getWidgetVersions();case 6:if(!G.sent.includes(o.UnstableApiVersion.MSC2762_UPDATE_STATE)){G.next=9;break}return G.next=9,this.transport.send(n.WidgetApiToWidgetAction.UpdateState,{state:[I]});case 9:G.next=21;break;case 11:j=this.pushRoomStateResult.get(I.room_id),j===void 0&&(j=new Map,this.pushRoomStateResult.set(I.room_id,j)),U=j.get(I.type),U===void 0&&(U=new Map,j.set(I.type,U)),U.has(I.type)||U.set(I.state_key,I);case 16:return G.next=18,Promise.all(this.pushRoomStateTasks);case 18:if(this.pushRoomStateTasks.size>0){G.next=16;break}case 19:return G.next=21,this.flushRoomStateTask;case 21:case"end":return G.stop()}},M,this)}));function P(M){return D.apply(this,arguments)}return P}()}]),A}(r.EventEmitter);return bu.ClientWidgetApi=le,bu}var Zw={};Object.defineProperty(Zw,"__esModule",{value:!0});Zw.isErrorResponse=lY;function y_(r){"@babel/helpers - typeof";return y_=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},y_(r)}function lY(r){var e=r.error;return y_(e)==="object"&&e!==null&&"message"in e&&typeof e.message=="string"}var Am={};Object.defineProperty(Am,"__esModule",{value:!0});Am.WidgetKind=void 0;var cY=function(r){return r.Room="room",r.Account="account",r.Modal="modal",r}({});Am.WidgetKind=cY;var Dm={};Object.defineProperty(Dm,"__esModule",{value:!0});Dm.ModalButtonKind=void 0;var uY=function(r){return r.Primary="m.primary",r.Secondary="m.secondary",r.Warning="m.warning",r.Danger="m.danger",r.Link="m.link",r}({});Dm.ModalButtonKind=uY;var Nm={};Object.defineProperty(Nm,"__esModule",{value:!0});Nm.isValidUrl=dY;function dY(r){if(!r)return!1;try{var e=new URL(r);return!(e.protocol!=="http"&&e.protocol!=="https")}catch(t){if(t instanceof TypeError)return!1;throw t}}var Lm={};Object.defineProperty(Lm,"__esModule",{value:!0});Lm.assertPresent=fY;function fY(r,e){if(!r[e])throw new Error("".concat(String(e)," is required"))}var _u={},oI;function nL(){if(oI)return _u;oI=1,Object.defineProperty(_u,"__esModule",{value:!0}),_u.Widget=void 0;var r=jm(),e=Lm;function t(c){"@babel/helpers - typeof";return t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(u){return typeof u}:function(u){return u&&typeof Symbol=="function"&&u.constructor===Symbol&&u!==Symbol.prototype?"symbol":typeof u},t(c)}function n(c,u){if(!(c instanceof u))throw new TypeError("Cannot call a class as a function")}function i(c,u){for(var d=0;d<u.length;d++){var f=u[d];f.enumerable=f.enumerable||!1,f.configurable=!0,"value"in f&&(f.writable=!0),Object.defineProperty(c,s(f.key),f)}}function o(c,u,d){return u&&i(c.prototype,u),Object.defineProperty(c,"prototype",{writable:!1}),c}function s(c){var u=a(c,"string");return t(u)==="symbol"?u:String(u)}function a(c,u){if(t(c)!=="object"||c===null)return c;var d=c[Symbol.toPrimitive];if(d!==void 0){var f=d.call(c,u);if(t(f)!=="object")return f;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(c)}var l=function(){function c(u){if(n(this,c),this.definition=u,!this.definition)throw new Error("Definition is required");(0,e.assertPresent)(u,"id"),(0,e.assertPresent)(u,"creatorUserId"),(0,e.assertPresent)(u,"type"),(0,e.assertPresent)(u,"url")}return o(c,[{key:"creatorUserId",get:function(){return this.definition.creatorUserId}},{key:"type",get:function(){return this.definition.type}},{key:"id",get:function(){return this.definition.id}},{key:"name",get:function(){return this.definition.name||null}},{key:"title",get:function(){return this.rawData.title||null}},{key:"templateUrl",get:function(){return this.definition.url}},{key:"origin",get:function(){return new URL(this.templateUrl).origin}},{key:"waitForIframeLoad",get:function(){return this.definition.waitForIframeLoad===!1?!1:(this.definition.waitForIframeLoad===!0,!0)}},{key:"rawData",get:function(){return this.definition.data||{}}},{key:"getCompleteUrl",value:function(d){return(0,r.runTemplate)(this.templateUrl,this.definition,d)}}]),c}();return _u.Widget=l,_u}var Eu={},sI;function hY(){if(sI)return Eu;sI=1,Object.defineProperty(Eu,"__esModule",{value:!0}),Eu.WidgetParser=void 0;var r=nL(),e=Nm;function t(f){"@babel/helpers - typeof";return t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p},t(f)}function n(f,p){var h=typeof Symbol<"u"&&f[Symbol.iterator]||f["@@iterator"];if(!h){if(Array.isArray(f)||(h=i(f))||p){h&&(f=h);var m=0,E=function(){};return{s:E,n:function(){return m>=f.length?{done:!0}:{done:!1,value:f[m++]}},e:function(x){throw x},f:E}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
300
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y=!0,S=!1,R;return{s:function(){h=h.call(f)},n:function(){var x=h.next();return y=x.done,x},e:function(x){S=!0,R=x},f:function(){try{!y&&h.return!=null&&h.return()}finally{if(S)throw R}}}}function i(f,p){if(f){if(typeof f=="string")return o(f,p);var h=Object.prototype.toString.call(f).slice(8,-1);if(h==="Object"&&f.constructor&&(h=f.constructor.name),h==="Map"||h==="Set")return Array.from(f);if(h==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(h))return o(f,p)}}function o(f,p){(p==null||p>f.length)&&(p=f.length);for(var h=0,m=new Array(p);h<p;h++)m[h]=f[h];return m}function s(f,p){if(!(f instanceof p))throw new TypeError("Cannot call a class as a function")}function a(f,p){for(var h=0;h<p.length;h++){var m=p[h];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(f,c(m.key),m)}}function l(f,p,h){return h&&a(f,h),Object.defineProperty(f,"prototype",{writable:!1}),f}function c(f){var p=u(f,"string");return t(p)==="symbol"?p:String(p)}function u(f,p){if(t(f)!=="object"||f===null)return f;var h=f[Symbol.toPrimitive];if(h!==void 0){var m=h.call(f,p);if(t(m)!=="object")return m;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(f)}var d=function(){function f(){s(this,f)}return l(f,null,[{key:"parseAccountData",value:function(h){if(!h)return[];for(var m=[],E=0,y=Object.keys(h);E<y.length;E++){var S=y[E],R=h[S];if(R&&!(R.type!=="m.widget"&&R.type!=="im.vector.modular.widgets")&&R.sender){var k=R.state_key||R.id;if(k===S){var x={content:R.content,sender:R.sender,type:"m.widget",state_key:S,event_id:"$example",room_id:"!example",origin_server_ts:1},T=f.parseRoomWidget(x);T&&m.push(T)}}}return m}},{key:"parseWidgetsFromRoomState",value:function(h){if(!h)return[];var m=[],E=n(h),y;try{for(E.s();!(y=E.n()).done;){var S=y.value,R=f.parseRoomWidget(S);R&&m.push(R)}}catch(k){E.e(k)}finally{E.f()}return m}},{key:"parseRoomWidget",value:function(h){if(!h||h.type!=="m.widget"&&h.type!=="im.vector.modular.widgets")return null;var m=h.content||{},E={id:h.state_key,creatorUserId:m.creatorUserId||h.sender,name:m.name,type:m.type,url:m.url,waitForIframeLoad:m.waitForIframeLoad,data:m.data};return f.processEstimatedWidget(E)}},{key:"processEstimatedWidget",value:function(h){return!h.id||!h.creatorUserId||!h.type||!(0,e.isValidUrl)(h.url)?null:new r.Widget(h)}}]),f}();return Eu.WidgetParser=d,Eu}var Um={};Object.defineProperty(Um,"__esModule",{value:!0});Um.runTemplate=pY;Um.toString=iL;function pY(r,e,t){for(var n=Object.assign({},e.data,{matrix_room_id:t.widgetRoomId||"",matrix_user_id:t.currentUserId,matrix_display_name:t.userDisplayName||t.currentUserId,matrix_avatar_url:t.userHttpAvatarUrl||"",matrix_widget_id:e.id,"org.matrix.msc2873.client_id":t.clientId||"","org.matrix.msc2873.client_theme":t.clientTheme||"","org.matrix.msc2873.client_language":t.clientLanguage||"","org.matrix.msc3819.matrix_device_id":t.deviceId||"","org.matrix.msc4039.matrix_base_url":t.baseUrl||""}),i=r,o=0,s=Object.keys(n);o<s.length;o++){var a=s[o],l="$".concat(a).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(l,"g");i=i.replace(c,encodeURIComponent(iL(n[a])))}return i}function iL(r){return r==null?"".concat(r):String(r)}var wu={},aI;function vY(){if(aI)return wu;aI=1,Object.defineProperty(wu,"__esModule",{value:!0}),wu.WidgetDriver=void 0;var r=jm();function e(l){"@babel/helpers - typeof";return e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c},e(l)}function t(l,c){if(!(l instanceof c))throw new TypeError("Cannot call a class as a function")}function n(l,c){for(var u=0;u<c.length;u++){var d=c[u];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(l,o(d.key),d)}}function i(l,c,u){return c&&n(l.prototype,c),Object.defineProperty(l,"prototype",{writable:!1}),l}function o(l){var c=s(l,"string");return e(c)==="symbol"?c:String(c)}function s(l,c){if(e(l)!=="object"||l===null)return l;var u=l[Symbol.toPrimitive];if(u!==void 0){var d=u.call(l,c);if(e(d)!=="object")return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(l)}var a=function(){function l(){t(this,l)}return i(l,[{key:"validateCapabilities",value:function(u){return Promise.resolve(new Set)}},{key:"sendEvent",value:function(u,d){return Promise.reject(new Error("Failed to override function"))}},{key:"sendStickyEvent",value:function(u,d,f){throw new Error("Method not implemented.")}},{key:"sendDelayedEvent",value:function(u,d,f,p){return Promise.reject(new Error("Failed to override function"))}},{key:"sendDelayedStickyEvent",value:function(u,d,f,p,h){throw new Error("Method not implemented.")}},{key:"cancelScheduledDelayedEvent",value:function(u){return Promise.reject(new Error("Failed to override function"))}},{key:"restartScheduledDelayedEvent",value:function(u){return Promise.reject(new Error("Failed to override function"))}},{key:"sendScheduledDelayedEvent",value:function(u){return Promise.reject(new Error("Failed to override function"))}},{key:"sendToDevice",value:function(u,d,f){return Promise.reject(new Error("Failed to override function"))}},{key:"readRoomAccountData",value:function(u){return Promise.resolve([])}},{key:"readRoomEvents",value:function(u,d,f){return Promise.resolve([])}},{key:"readStateEvents",value:function(u,d,f){return Promise.resolve([])}},{key:"readStickyEvents",value:function(u){throw new Error("readStickyEvents is not implemented")}},{key:"readRoomTimeline",value:function(u,d,f,p,h,m){return p===void 0?this.readRoomEvents(d,f,h,[u],m):this.readStateEvents(d,p,h,[u])}},{key:"readRoomState",value:function(u,d,f){return this.readStateEvents(d,f,Number.MAX_SAFE_INTEGER,[u])}},{key:"readEventRelations",value:function(u,d,f,p,h,m,E,y){return Promise.resolve({chunk:[]})}},{key:"askOpenID",value:function(u){u.update({state:r.OpenIDRequestState.Blocked})}},{key:"navigate",value:function(u){throw new Error("Navigation is not implemented")}},{key:"getTurnServers",value:function(){throw new Error("TURN server support is not implemented")}},{key:"searchUserDirectory",value:function(u,d){return Promise.resolve({limited:!1,results:[]})}},{key:"getMediaConfig",value:function(){throw new Error("Get media config is not implemented")}},{key:"uploadFile",value:function(u){throw new Error("Upload file is not implemented")}},{key:"downloadFile",value:function(u){throw new Error("Download file is not implemented")}},{key:"getKnownRooms",value:function(){throw new Error("Querying known rooms is not implemented")}},{key:"processError",value:function(u){}}]),l}();return wu.WidgetDriver=a,wu}var lI;function jm(){return lI||(lI=1,function(r){Object.defineProperty(r,"__esModule",{value:!0});var e=H7();Object.keys(e).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===e[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return e[C]}})});var t=aY();Object.keys(t).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===t[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return t[C]}})});var n=Hc;Object.keys(n).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===n[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return n[C]}})});var i=Xw();Object.keys(i).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===i[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return i[C]}})});var o=If;Object.keys(o).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===o[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return o[C]}})});var s=Zw;Object.keys(s).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===s[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return s[C]}})});var a=Ls;Object.keys(a).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===a[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return a[C]}})});var l=tl;Object.keys(l).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===l[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return l[C]}})});var c=Zi;Object.keys(c).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===c[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return c[C]}})});var u=Jn;Object.keys(u).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===u[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return u[C]}})});var d=Gc;Object.keys(d).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===d[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return d[C]}})});var f=Am;Object.keys(f).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===f[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return f[C]}})});var p=Dm;Object.keys(p).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===p[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return p[C]}})});var h=xf;Object.keys(h).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===h[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return h[C]}})});var m=zc;Object.keys(m).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===m[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return m[C]}})});var E=eo;Object.keys(E).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===E[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return E[C]}})});var y=Nm;Object.keys(y).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===y[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return y[C]}})});var S=Lm;Object.keys(S).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===S[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return S[C]}})});var R=nL();Object.keys(R).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===R[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return R[C]}})});var k=hY();Object.keys(k).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===k[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return k[C]}})});var x=Um;Object.keys(x).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===x[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return x[C]}})});var T=Of;Object.keys(T).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===T[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return T[C]}})});var O=vY();Object.keys(O).forEach(function(C){C==="default"||C==="__esModule"||C in r&&r[C]===O[C]||Object.defineProperty(r,C,{enumerable:!0,get:function(){return O[C]}})})}(my)),my}var ss=jm();function cI(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function Rh(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?cI(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):cI(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function mY(r){var e,t,n,i=2;for(typeof Symbol<"u"&&(t=Symbol.asyncIterator,n=Symbol.iterator);i--;){if(t&&(e=r[t])!=null)return e.call(r);if(n&&(e=r[n])!=null)return new cp(e.call(r));t="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function cp(r){function e(t){if(Object(t)!==t)return Promise.reject(new TypeError(t+" is not an object."));var n=t.done;return Promise.resolve(t.value).then(function(i){return{value:i,done:n}})}return cp=function(n){this.s=n,this.n=n.next},cp.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(n){var i=this.s.return;return i===void 0?Promise.resolve({value:n,done:!0}):e(i.apply(this.s,arguments))},throw:function(n){var i=this.s.return;return i===void 0?Promise.reject(n):e(i.apply(this.s,arguments))}},new cp(r)}var up=function(r){return r.PendingEventsChanged="PendingEvent.pendingEventsChanged",r}({});class oL extends qc{constructor(e,t,n,i,o){var s,a,l,c,u,d,f,p,h,m,E,y,S;super(i),s=this,this.widgetApi=e,this.capabilities=t,this.roomId=n,v(this,"room",void 0),v(this,"widgetApiReady",void 0),v(this,"lifecycle",void 0),v(this,"syncState",null),v(this,"pendingSendingEventsTxId",[]),v(this,"eventEmitter",new Tt),v(this,"updateTxId",function(){var x=w(function*(T){if(T.getSender()===s.getUserId()&&s.pendingSendingEventsTxId.some(F=>T.getType()===F.type)){for(var O,C=(O=s.pendingSendingEventsTxId.find(F=>F.id===T.getId()))===null||O===void 0?void 0:O.txId;!C&&s.pendingSendingEventsTxId.length>0;){var N;yield new Promise(F=>s.eventEmitter.once(up.PendingEventsChanged,()=>F())),C=(N=s.pendingSendingEventsTxId.find(F=>F.id===T.getId()))===null||N===void 0?void 0:N.txId}C&&(T.setTxnId(C),T.setUnsigned(Rh(Rh({},T.getUnsigned()),{},{transaction_id:C}))),s.pendingSendingEventsTxId=s.pendingSendingEventsTxId.filter(F=>F.id!==T.getId()),s.pendingSendingEventsTxId.length===0&&s.eventEmitter.emit(up.PendingEventsChanged)}});return function(T){return x.apply(this,arguments)}}()),v(this,"onEvent",function(){var x=w(function*(T){if(T.preventDefault(),T.detail.data.room_id===s.roomId){var O=new pr(T.detail.data);yield s.updateTxId(O),yield s.syncApi.injectRoomEvents(s.room,[],[O]),s.emit(be.Event,O),s.setSyncState(ct.Syncing),b.info("Received event ".concat(O.getId()," ").concat(O.getType()," ").concat(O.getStateKey()))}else{var{event_id:C,room_id:N}=T.detail.data;b.info("Received event ".concat(C," for a different room ").concat(N,"; discarding"))}yield s.ack(T)});return function(T){return x.apply(this,arguments)}}()),v(this,"onToDevice",function(){var x=w(function*(T){T.preventDefault();var O=new pr({type:T.detail.data.type,sender:T.detail.data.sender,content:T.detail.data.content});T.detail.data.encrypted&&O.makeEncrypted(V.RoomMessageEncrypted,{},"",""),s.emit(be.ToDeviceEvent,O),s.setSyncState(ct.Syncing),yield s.ack(T)});return function(T){return x.apply(this,arguments)}}());var R=this.widgetApi.transport.send.bind(this.widgetApi.transport);this.widgetApi.transport.send=function(){var x=w(function*(T,O){try{return yield R(T,O)}catch(C){uI(C)}});return function(T,O){return x.apply(this,arguments)}}();var k=this.widgetApi.transport.sendComplete.bind(this.widgetApi.transport);this.widgetApi.transport.sendComplete=function(){var x=w(function*(T,O){try{return yield k(T,O)}catch(C){uI(C)}});return function(T,O){return x.apply(this,arguments)}}(),this.widgetApiReady=new Promise(x=>this.widgetApi.once("ready",x)),((a=t.sendEvent)!==null&&a!==void 0&&a.length||(l=t.receiveEvent)!==null&&l!==void 0&&l.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||t.receiveMessage===!0||Array.isArray(t.receiveMessage)&&t.receiveMessage.length||(c=t.sendState)!==null&&c!==void 0&&c.length||(u=t.receiveState)!==null&&u!==void 0&&u.length)&&e.requestCapabilityForRoomTimeline(n),(d=t.sendEvent)===null||d===void 0||d.forEach(x=>e.requestCapabilityToSendEvent(x)),(f=t.receiveEvent)===null||f===void 0||f.forEach(x=>e.requestCapabilityToReceiveEvent(x)),t.sendMessage===!0?e.requestCapabilityToSendMessage():Array.isArray(t.sendMessage)&&t.sendMessage.forEach(x=>e.requestCapabilityToSendMessage(x)),t.receiveMessage===!0?e.requestCapabilityToReceiveMessage():Array.isArray(t.receiveMessage)&&t.receiveMessage.forEach(x=>e.requestCapabilityToReceiveMessage(x)),(p=t.sendState)===null||p===void 0||p.forEach(x=>{var{eventType:T,stateKey:O}=x;return e.requestCapabilityToSendState(T,O)}),(h=t.receiveState)===null||h===void 0||h.forEach(x=>{var{eventType:T,stateKey:O}=x;return e.requestCapabilityToReceiveState(T,O)}),(m=t.sendToDevice)===null||m===void 0||m.forEach(x=>e.requestCapabilityToSendToDevice(x)),(E=t.receiveToDevice)===null||E===void 0||E.forEach(x=>e.requestCapabilityToReceiveToDevice(x)),t.sendDelayedEvents&&((y=t.sendEvent)!==null&&y!==void 0&&y.length||t.sendMessage===!0||Array.isArray(t.sendMessage)&&t.sendMessage.length||(S=t.sendState)!==null&&S!==void 0&&S.length)&&e.requestCapability(ss.MatrixCapabilities.MSC4157SendDelayedEvent),t.updateDelayedEvents&&e.requestCapability(ss.MatrixCapabilities.MSC4157UpdateDelayedEvent),t.turnServers&&e.requestCapability(ss.MatrixCapabilities.MSC3846TurnServers),e.on("action:".concat(ss.WidgetApiToWidgetAction.SendEvent),this.onEvent),e.on("action:".concat(ss.WidgetApiToWidgetAction.SendToDevice),this.onToDevice),e.start(),o&&e.sendContentLoaded()}startClient(){var e=arguments,t=this;return w(function*(){var n,i,o=e.length>0&&e[0]!==void 0?e[0]:{};t.lifecycle=new AbortController;var s=t.getUserId();s&&t.store.storeUser(new ko(s)),o.slidingSync?t.syncApi=new GN(o.slidingSync,t,o,t.buildSyncApiOptions()):t.syncApi=new Au(t,o,t.buildSyncApiOptions()),t.room=t.syncApi.createRoom(t.roomId),t.store.storeRoom(t.room),yield t.widgetApiReady,yield Promise.all((n=(i=t.capabilities.receiveState)===null||i===void 0?void 0:i.map(function(){var a=w(function*(l){var{eventType:c,stateKey:u}=l,d=yield t.widgetApi.readStateEvents(c,void 0,u,[t.roomId]),f=d.map(p=>new pr(p));yield t.syncApi.injectRoomEvents(t.room,[],f),f.forEach(p=>{t.emit(be.Event,p),b.info("Backfilled event ".concat(p.getId()," ").concat(p.getType()," ").concat(p.getStateKey()))})});return function(l){return a.apply(this,arguments)}}()))!==null&&n!==void 0?n:[]),o.clientWellKnownPollPeriod!==void 0&&(t.clientWellKnownIntervalID=setInterval(()=>{t.fetchClientWellKnown()},1e3*o.clientWellKnownPollPeriod),t.fetchClientWellKnown()),t.setSyncState(ct.Syncing),b.info("Finished backfilling events"),t.matrixRTC.start(),t.capabilities.turnServers&&t.watchTurnServers()})()}stopClient(){this.widgetApi.off("action:".concat(ss.WidgetApiToWidgetAction.SendEvent),this.onEvent),this.widgetApi.off("action:".concat(ss.WidgetApiToWidgetAction.SendToDevice),this.onToDevice),super.stopClient(),this.lifecycle.abort()}joinRoom(e){var t=this;return w(function*(){if(e===t.roomId)return t.room;throw new Error("Unknown room: ".concat(e))})()}encryptAndSendEvent(e,t,n){var i=this;return w(function*(){var o=t.event.redacts?Rh(Rh({},t.getContent()),{},{redacts:t.event.redacts}):t.getContent();if(n){var s=yield i.widgetApi.sendRoomEvent(t.getType(),o,e.roomId,"delay"in n?n.delay:void 0,"parent_delay_id"in n?n.parent_delay_id:void 0);return i.validateSendDelayedEventResponse(s)}var a=t.getTxnId();a&&i.pendingSendingEventsTxId.push({type:t.getType(),id:void 0,txId:a});var l;try{l=yield i.widgetApi.sendRoomEvent(t.getType(),o,e.roomId)}catch(c){throw i.updatePendingEventStatus(e,t,je.NOT_SENT),c}return e.updatePendingEvent(t,je.SENT,l.event_id),i.pendingSendingEventsTxId.forEach(c=>{c.txId===a&&(c.id=l.event_id)}),i.eventEmitter.emit(up.PendingEventsChanged),{event_id:l.event_id}})()}sendStateEvent(e,t,n){var i=arguments,o=this;return w(function*(){var s=i.length>3&&i[3]!==void 0?i[3]:"",a=yield o.widgetApi.sendStateEvent(t,s,n,e);if(a.event_id===void 0)throw new Error("'event_id' absent from response to an event request");return{event_id:a.event_id}})()}_unstable_sendDelayedStateEvent(e,t,n,i){var o=arguments,s=this;return w(function*(){var a=o.length>4&&o[4]!==void 0?o[4]:"";if(!(yield s.doesServerSupportUnstableFeature(Wi)))throw Error("Server does not support the delayed events API");var l=yield s.widgetApi.sendStateEvent(n,a,i,e,"delay"in t?t.delay:void 0,"parent_delay_id"in t?t.parent_delay_id:void 0);return s.validateSendDelayedEventResponse(l)})()}validateSendDelayedEventResponse(e){if(e.delay_id===void 0)throw new Error("'delay_id' absent from response to a delayed event request");return{delay_id:e.delay_id}}_unstable_updateDelayedEvent(e,t){var n=this;return w(function*(){if(!(yield n.doesServerSupportUnstableFeature(Wi)))throw Error("Server does not support the delayed events API");return yield n.widgetApi.updateDelayedEvent(e,t)})()}sendToDevice(e,t){var n=this;return w(function*(){return yield n.widgetApi.sendToDevice(e,!1,ms(t)),{}})()}getOpenIdToken(){var e=this;return w(function*(){var t=yield e.widgetApi.requestOpenIDConnectToken();return{access_token:t.access_token,expires_in:t.expires_in,matrix_server_name:t.matrix_server_name,token_type:t.token_type}})()}queueToDevice(e){var t=this;return w(function*(){var{eventType:n,batch:i}=e,o=new Gt(()=>new Map);for(var{userId:s,deviceId:a,payload:l}of i)o.getOrCreate(s).set(a,l);yield t.widgetApi.sendToDevice(n,!1,ms(o))})()}encryptAndSendToDevices(e,t){var n=this;return w(function*(){var i=new Gt(()=>new Map);for(var{userId:o,deviceInfo:{deviceId:s}}of e)i.getOrCreate(o).set(s,t);yield n.widgetApi.sendToDevice(t.type,!0,ms(i))})()}sendToDeviceViaWidgetApi(e,t,n){var i=this;return w(function*(){yield i.widgetApi.sendToDevice(e,t,ms(n))})()}checkTurnServers(){var e=this;return w(function*(){return e.turnServers.length>0})()}getSyncState(){return this.syncState}setSyncState(e){var t=this.syncState;this.syncState=e,this.emit(be.Sync,e,t)}ack(e){var t=this;return w(function*(){yield t.widgetApi.transport.reply(e.detail,{})})()}watchTurnServers(){var e=this;return w(function*(){var t=e.widgetApi.getTurnServers(),n=()=>{t.return(void 0)};e.lifecycle.signal.addEventListener("abort",n);try{var i=!1,o=!1,s;try{for(var a=mY(t),l;i=!(l=yield a.next()).done;i=!1){var c=l.value;e.turnServers=[{urls:c.uris,username:c.username,credential:c.password}],e.emit(be.TurnServers,e.turnServers),b.log("Received TURN server: ".concat(c.uris))}}catch(u){o=!0,s=u}finally{try{i&&a.return!=null&&(yield a.return())}finally{if(o)throw s}}}catch(u){b.warn("Error watching TURN servers",u)}finally{e.lifecycle.signal.removeEventListener("abort",n)}})()}}function uI(r){throw r instanceof ss.WidgetApiResponseError&&r.data.matrix_api_error?hr.fromWidgetApiErrorData(r.data.matrix_api_error):r}class gY{constructor(){v(this,"unthreadedReadReceipts",new Map),v(this,"threadedReadReceipts",new Gt(()=>new Map))}setUnthreaded(e,t){this.unthreadedReadReceipts.set(e,t)}setThreaded(e,t,n){this.threadedReadReceipts.getOrCreate(e).set(t,n)}allUnthreaded(){return this.unthreadedReadReceipts.entries()}*allThreaded(){for(var e of this.threadedReadReceipts.values())for(var t of e.entries())yield t}consumeEphemeralEvents(e){e==null||e.forEach(t=>{t.type!==V.Receipt||!t.content||Object.keys(t.content).forEach(n=>{Object.entries(t.content[n]).forEach(i=>{var[o,s]=i;if(kw(o))for(var a of Object.keys(s)){var l=t.content[n][o][a],c={data:t.content[n][o][a],type:o,eventId:n};l.thread_id?this.setThreaded(l.thread_id,a,c):this.setUnthreaded(a,c)}})})})}buildAccumulatedReceiptEvent(e){var t={type:V.Receipt,room_id:e,content:{}},n=new Gt(()=>new Gt(()=>new Map));for(var[i,o]of this.allUnthreaded())n.getOrCreate(o.eventId).getOrCreate(o.type).set(i,o.data);for(var[s,a]of this.allThreaded())n.getOrCreate(a.eventId).getOrCreate(a.type).set(s,a.data);return t.content=ms(n),n.size>0?t:null}}var po=function(r){return r.Invite="invite",r.Leave="leave",r.Join="join",r.Knock="knock",r}({});function yY(r){return"_localTs"in r&&r._localTs!==void 0}class sL{constructor(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.opts=e,v(this,"accountData",{}),v(this,"inviteRooms",{}),v(this,"knockRooms",{}),v(this,"joinRooms",{}),v(this,"nextBatch",null),this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;this.accumulateRooms(e,t),this.accumulateAccountData(e),this.nextBatch=e.next_batch}accumulateAccountData(e){!e.account_data||!e.account_data.events||e.account_data.events.forEach(t=>{this.accountData[t.type]=t})}accumulateRooms(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach(n=>{this.accumulateRoom(n,po.Invite,e.rooms.invite[n],t)}),e.rooms.join&&Object.keys(e.rooms.join).forEach(n=>{this.accumulateRoom(n,po.Join,e.rooms.join[n],t)}),e.rooms.leave&&Object.keys(e.rooms.leave).forEach(n=>{this.accumulateRoom(n,po.Leave,e.rooms.leave[n],t)}),e.rooms.knock&&Object.keys(e.rooms.knock).forEach(n=>{this.accumulateRoom(n,po.Knock,e.rooms.knock[n],t)}))}accumulateRoom(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;switch(t){case po.Invite:this.knockRooms[e]&&delete this.knockRooms[e],this.accumulateInviteState(e,n);break;case po.Knock:this.accumulateKnockState(e,n);break;case po.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,n,i);break;case po.Leave:this.knockRooms[e]?delete this.knockRooms[e]:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:b.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!(!t.invite_state||!t.invite_state.events)){if(!this.inviteRooms[e]){this.inviteRooms[e]={invite_state:t.invite_state};return}var n=this.inviteRooms[e];t.invite_state.events.forEach(i=>{for(var o=!1,s=0;s<n.invite_state.events.length;s++){var a=n.invite_state.events[s];a.type===i.type&&a.state_key==i.state_key&&(n.invite_state.events[s]=i,o=!0)}o||n.invite_state.events.push(i)})}}accumulateKnockState(e,t){if(!(!t.knock_state||!t.knock_state.events)){if(!this.knockRooms[e]){this.knockRooms[e]={knock_state:t.knock_state};return}var n=this.knockRooms[e];t.knock_state.events.forEach(i=>{for(var o=!1,s=0;s<n.knock_state.events.length;s++){var a=n.knock_state.events[s];a.type===i.type&&a.state_key==i.state_key&&(n.knock_state.events[s]=i,o=!0)}o||n.knock_state.events.push(i)})}}accumulateJoinState(e,t){var n,i,o,s,a,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 gY});var c=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach(k=>{c._accountData[k.type]=k}),t.unread_notifications&&(c._unreadNotifications=t.unread_notifications),c._unreadThreadNotifications=(n=(i=t[Bd.stable])!==null&&i!==void 0?i:t[Bd.unstable])!==null&&n!==void 0?n:void 0,t.summary){var u,d,f,p="m.heroes",h="m.invited_member_count",m="m.joined_member_count",E=c._summary,y=t.summary;E[p]=(u=y[p])!==null&&u!==void 0?u:E[p],E[m]=(d=y[m])!==null&&d!==void 0?d:E[m],E[h]=(f=y[h])!==null&&f!==void 0?f:E[h]}if(c._receipts.consumeEphemeralEvents((o=t.ephemeral)===null||o===void 0?void 0:o.events),t.timeline&&t.timeline.limited&&(c._timeline=[]),(s=t.state)===null||s===void 0||(s=s.events)===null||s===void 0||s.forEach(k=>{gy(c._currentState,k)}),(a=t.timeline)===null||a===void 0||(a=a.events)===null||a===void 0||a.forEach((k,x)=>{var T;gy(c._currentState,k);var O;if(l)O=k;else{var C;O=Object.assign({},k),O.unsigned!==void 0&&(O.unsigned=Object.assign({},O.unsigned));var N=(C=k.unsigned)===null||C===void 0?void 0:C.age;N!==void 0&&(O._localTs=Date.now()-N)}c._timeline.push({event:O,token:x===0&&(T=t.timeline.prev_batch)!==null&&T!==void 0?T:null})}),c._timeline.length>this.opts.maxTimelineEntries){for(var S=c._timeline.length-this.opts.maxTimelineEntries,R=S;R<c._timeline.length;R++)if(c._timeline[R].token){c._timeline=c._timeline.slice(R,c._timeline.length);break}}}getJSON(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t={join:{},invite:{},knock:{},leave:{}};Object.keys(this.inviteRooms).forEach(i=>{t.invite[i]=this.inviteRooms[i]}),Object.keys(this.knockRooms).forEach(i=>{t.knock[i]=this.knockRooms[i]}),Object.keys(this.joinRooms).forEach(i=>{var o=this.joinRooms[i],s={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:o._unreadNotifications,unread_thread_notifications:o._unreadThreadNotifications,summary:o._summary};Object.keys(o._accountData).forEach(f=>{s.account_data.events.push(o._accountData[f])});var a=o._receipts.buildAccumulatedReceiptEvent(i);a&&s.ephemeral.events.push(a),o._timeline.forEach(f=>{if(!s.timeline.prev_batch){if(!f.token)return;s.timeline.prev_batch=f.token}var p;!e&&yY(f.event)?(p=Object.assign({},f.event),p.unsigned!==void 0&&(p.unsigned=Object.assign({},p.unsigned)),delete p._localTs,p.unsigned=p.unsigned||{},p.unsigned.age=Date.now()-f.event._localTs):p=f.event,s.timeline.events.push(p)});for(var l=Object.create(null),c=s.timeline.events.length-1;c>=0;c--){var u=s.timeline.events[c];if(!(u.state_key===null||u.state_key===void 0)){var d=ym(u);d.unsigned&&(d.unsigned.prev_content&&(d.content=d.unsigned.prev_content),d.unsigned.prev_sender&&(d.sender=d.unsigned.prev_sender)),gy(l,d)}}Object.keys(o._currentState).forEach(f=>{Object.keys(o._currentState[f]).forEach(p=>{var h=o._currentState[f][p];l[f]&&l[f][p]&&(h=l[f][p]),s.state.events.push(h)})}),t.join[i]=s});var n=[];return Object.keys(this.accountData).forEach(i=>{n.push(this.accountData[i])}),{nextBatch:this.nextBatch,roomsData:t,accountData:n}}getNextBatchToken(){return this.nextBatch}}function gy(r,e){e.state_key===null||e.state_key===void 0||!e.type||(r[e.type]||(r[e.type]=Object.create(null)),r[e.type][e.state_key]=e)}class Uu extends Error{}Uu.prototype.name="InvalidTokenError";function SY(r){return decodeURIComponent(atob(r).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}))}function bY(r){let e=r.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 SY(e)}catch{return atob(e)}}function aL(r,e){if(typeof r!="string")throw new Uu("Invalid token specified: must be a string");e||(e={});const t=e.header===!0?0:1,n=r.split(".")[t];if(typeof n!="string")throw new Uu(`Invalid token specified: missing part #${t+1}`);let i;try{i=bY(n)}catch(o){throw new Uu(`Invalid token specified: invalid base64 for part #${t+1} (${o.message})`)}try{return JSON.parse(i)}catch(o){throw new Uu(`Invalid token specified: invalid json for part #${t+1} (${o.message})`)}}var _Y={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Bi,Ki,Yd=(r=>(r[r.NONE=0]="NONE",r[r.ERROR=1]="ERROR",r[r.WARN=2]="WARN",r[r.INFO=3]="INFO",r[r.DEBUG=4]="DEBUG",r))(Yd||{});(r=>{function e(){Bi=3,Ki=_Y}r.reset=e;function t(i){if(!(0<=i&&i<=4))throw new Error("Invalid log level");Bi=i}r.setLevel=t;function n(i){Ki=i}r.setLogger=n})(Yd||(Yd={}));var Qt=class Ui{constructor(e){this._name=e}debug(...e){Bi>=4&&Ki.debug(Ui._format(this._name,this._method),...e)}info(...e){Bi>=3&&Ki.info(Ui._format(this._name,this._method),...e)}warn(...e){Bi>=2&&Ki.warn(Ui._format(this._name,this._method),...e)}error(...e){Bi>=1&&Ki.error(Ui._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const n=new Ui(`${e}.${t}`);return n.debug("begin"),n}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(e,...t){Bi>=4&&Ki.debug(Ui._format(e),...t)}static info(e,...t){Bi>=3&&Ki.info(Ui._format(e),...t)}static warn(e,...t){Bi>=2&&Ki.warn(Ui._format(e),...t)}static error(e,...t){Bi>=1&&Ki.error(Ui._format(e),...t)}};Yd.reset();var Jd=class{static decode(r){try{return aL(r)}catch(e){throw Qt.error("JwtUtils.decode",e),e}}static async generateSignedJwt(r,e,t){const n=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(r))),i=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),o=`${n}.${i}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,new TextEncoder().encode(o)),a=Or.encodeBase64Url(new Uint8Array(s));return`${o}.${a}`}static async generateSignedJwtWithHmac(r,e,t){const n=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(r))),i=Or.encodeBase64Url(new TextEncoder().encode(JSON.stringify(e))),o=`${n}.${i}`,s=await window.crypto.subtle.sign("HMAC",t,new TextEncoder().encode(o)),a=Or.encodeBase64Url(new Uint8Array(s));return`${o}.${a}`}},EY="10000000-1000-4000-8000-100000000000",S_=r=>btoa([...new Uint8Array(r)].map(e=>String.fromCharCode(e)).join("")),lL=class ci{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return EY.replace(/[018]/g,t=>(+t^ci._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return ci.generateUUIDv4()+ci.generateUUIDv4()+ci.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const n=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",n);return S_(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw Qt.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const i=new TextEncoder().encode([e,t].join(":"));return S_(i)}static async hash(e,t){const n=new TextEncoder().encode(t),i=await crypto.subtle.digest(e,n);return new Uint8Array(i)}static async customCalculateJwkThumbprint(e){let t;switch(e.kty){case"RSA":t={e:e.e,kty:e.kty,n:e.n};break;case"EC":t={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":t={crv:e.crv,kty:e.kty,x:e.x};break;case"oct":t={crv:e.k,kty:e.kty};break;default:throw new Error("Unknown jwk type")}const n=await ci.hash("SHA-256",JSON.stringify(t));return ci.encodeBase64Url(n)}static async generateDPoPProof({url:e,accessToken:t,httpMethod:n,keyPair:i,nonce:o}){let s,a;const l={jti:window.crypto.randomUUID(),htm:n??"GET",htu:e,iat:Math.floor(Date.now()/1e3)};t&&(s=await ci.hash("SHA-256",t),a=ci.encodeBase64Url(s),l.ath=a),o&&(l.nonce=o);try{const c=await crypto.subtle.exportKey("jwk",i.publicKey),u={alg:"ES256",typ:"dpop+jwt",jwk:{crv:c.crv,kty:c.kty,x:c.x,y:c.y}};return await Jd.generateSignedJwt(u,l,i.privateKey)}catch(c){throw c instanceof TypeError?new Error(`Error exporting dpop public key: ${c.message}`):c}}static async generateDPoPJkt(e){try{const t=await crypto.subtle.exportKey("jwk",e.publicKey);return await ci.customCalculateJwkThumbprint(t)}catch(t){throw t instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${t.message}`):t}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}static async generateClientAssertionJwt(e,t,n,i="HS256"){const o=Math.floor(Date.now()/1e3),s={alg:i,typ:"JWT"},a={iss:e,sub:e,aud:n,jti:ci.generateUUIDv4(),exp:o+300,iat:o},c={HS256:"SHA-256",HS384:"SHA-384",HS512:"SHA-512"}[i];if(!c)throw new Error(`Unsupported algorithm: ${i}. Supported algorithms are: HS256, HS384, HS512`);const u=new TextEncoder,d=await crypto.subtle.importKey("raw",u.encode(t),{name:"HMAC",hash:c},!1,["sign"]);return await Jd.generateSignedJwtWithHmac(s,a,d)}};lL.encodeBase64Url=r=>S_(r).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var Or=lL,wY=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new Qt(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},yv=class dp extends wY{constructor(){super(...arguments),this._logger=new Qt(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-dp.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=dp.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const n=dp.getEpochTime()+e;if(this.expiration===n&&this._timerHandle){t.debug("skipping since already initialized for expiration at",this.expiration);return}this.cancel(),t.debug("using duration",e),this._expiration=n;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)}},dI=class{static readParams(r,e="query"){if(!r)throw new TypeError("Invalid URL");const n=new URL(r,"http://127.0.0.1")[e==="fragment"?"hash":"search"];return new URLSearchParams(n.slice(1))}},Ic=";",Xd=class extends Error{constructor(r,e){var t,n,i;if(super(r.error_description||r.error||""),this.form=e,this.name="ErrorResponse",!r.error)throw Qt.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=r.error,this.error_description=(t=r.error_description)!=null?t:null,this.error_uri=(n=r.error_uri)!=null?n:null,this.state=r.userState,this.session_state=(i=r.session_state)!=null?i:null,this.url_state=r.url_state}},TY=class extends Error{constructor(r){super(r),this.name="ErrorTimeout"}},RY=class{constructor(){this._logger=new Qt("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(r){return this._logger.create(`getItem('${r}')`),this._data[r]}setItem(r,e){this._logger.create(`setItem('${r}')`),this._data[r]=e}removeItem(r){this._logger.create(`removeItem('${r}')`),delete this._data[r]}get length(){return Object.getOwnPropertyNames(this._data).length}key(r){return Object.getOwnPropertyNames(this._data)[r]}},b_=class extends Error{constructor(r,e){super(e),this.name="ErrorDPoPNonce",this.nonce=r}},e0=class{constructor(r=[],e=null,t={}){this._jwtHandler=e,this._extraHeaders=t,this._logger=new Qt("JsonService"),this._contentTypes=[],this._contentTypes.push(...r,"application/json"),e&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(r,e={}){const{timeoutInSeconds:t,...n}=e;if(!t)return await fetch(r,n);const i=new AbortController,o=setTimeout(()=>i.abort(),t*1e3);try{return await fetch(r,{...e,signal:i.signal})}catch(s){throw s instanceof DOMException&&s.name==="AbortError"?new TY("Network timed out"):s}finally{clearTimeout(o)}}async getJson(r,{token:e,credentials:t,timeoutInSeconds:n}={}){const i=this._logger.create("getJson"),o={Accept:this._contentTypes.join(", ")};e&&(i.debug("token passed, setting Authorization header"),o.Authorization="Bearer "+e),this._appendExtraHeaders(o);let s;try{i.debug("url:",r),s=await this.fetchWithTimeout(r,{method:"GET",headers:o,timeoutInSeconds:n,credentials:t})}catch(c){throw i.error("Network Error"),c}i.debug("HTTP response received, status",s.status);const a=s.headers.get("Content-Type");if(a&&!this._contentTypes.find(c=>a.startsWith(c))&&i.throw(new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${r}`)),s.ok&&this._jwtHandler&&(a!=null&&a.startsWith("application/jwt")))return await this._jwtHandler(await s.text());let l;try{l=await s.json()}catch(c){throw i.error("Error parsing JSON response",c),s.ok?c:new Error(`${s.statusText} (${s.status})`)}if(!s.ok)throw i.error("Error from server:",l),l.error?new Xd(l):new Error(`${s.statusText} (${s.status}): ${JSON.stringify(l)}`);return l}async postForm(r,{body:e,basicAuth:t,timeoutInSeconds:n,initCredentials:i,extraHeaders:o}){const s=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...o};t!==void 0&&(a.Authorization="Basic "+t),this._appendExtraHeaders(a);let l;try{s.debug("url:",r),l=await this.fetchWithTimeout(r,{method:"POST",headers:a,body:e,timeoutInSeconds:n,credentials:i})}catch(f){throw s.error("Network error"),f}s.debug("HTTP response received, status",l.status);const c=l.headers.get("Content-Type");if(c&&!this._contentTypes.find(f=>c.startsWith(f)))throw new Error(`Invalid response Content-Type: ${c??"undefined"}, from URL: ${r}`);const u=await l.text();let d={};if(u)try{d=JSON.parse(u)}catch(f){throw s.error("Error parsing JSON response",f),l.ok?f:new Error(`${l.statusText} (${l.status})`)}if(!l.ok){if(s.error("Error from server:",d),l.headers.has("dpop-nonce")){const f=l.headers.get("dpop-nonce");throw new b_(f,`${JSON.stringify(d)}`)}throw d.error?new Xd(d,e):new Error(`${l.statusText} (${l.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(r){const e=this._logger.create("appendExtraHeaders"),t=Object.keys(this._extraHeaders),n=["accept","content-type"],i=["authorization"];t.length!==0&&t.forEach(o=>{if(n.includes(o.toLocaleLowerCase())){e.warn("Protected header could not be set",o,n);return}if(i.includes(o.toLocaleLowerCase())&&Object.keys(r).includes(o)){e.warn("Header could not be overridden",o,i);return}const s=typeof this._extraHeaders[o]=="function"?this._extraHeaders[o]():this._extraHeaders[o];s&&s!==""&&(r[o]=s)})}},cL=class{constructor(r){this._settings=r,this._logger=new Qt("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new e0(["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 r=this._logger.create("getMetadata");if(this._metadata)return r.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw r.throw(new Error("No authority or metadataUrl configured on settings")),null;r.debug("getting metadata from",this._metadataUrl);const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return r.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},e,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(r=!0){return this._getMetadataProperty("token_endpoint",r)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(r=!0){return this._getMetadataProperty("revocation_endpoint",r)}getKeysEndpoint(r=!0){return this._getMetadataProperty("jwks_uri",r)}async _getMetadataProperty(r,e=!1){const t=this._logger.create(`_getMetadataProperty('${r}')`),n=await this.getMetadata();if(t.debug("resolved"),n[r]===void 0){if(e===!0){t.warn("Metadata does not contain optional property");return}t.throw(new Error("Metadata does not contain property "+r))}return n[r]}async getSigningKeys(){const r=this._logger.create("getSigningKeys");if(this._signingKeys)return r.debug("returning signingKeys from cache"),this._signingKeys;const e=await this.getKeysEndpoint(!1);r.debug("got jwks_uri",e);const t=await this._jsonService.getJson(e,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(r.debug("got key set",t),!Array.isArray(t.keys))throw r.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=t.keys,this._signingKeys}},Fm=class{constructor({prefix:r="oidc.",store:e=localStorage}={}){this._logger=new Qt("WebStorageStateStore"),this._store=e,this._prefix=r}async set(r,e){this._logger.create(`set('${r}')`),r=this._prefix+r,await this._store.setItem(r,e)}async get(r){return this._logger.create(`get('${r}')`),r=this._prefix+r,await this._store.getItem(r)}async remove(r){this._logger.create(`remove('${r}')`),r=this._prefix+r;const e=await this._store.getItem(r);return await this._store.removeItem(r),e}async getAllKeys(){this._logger.create("getAllKeys");const r=await this._store.length,e=[];for(let t=0;t<r;t++){const n=await this._store.key(t);n&&n.indexOf(this._prefix)===0&&e.push(n.substr(this._prefix.length))}return e}},CY="code",kY="openid",IY="client_secret_post",xY=60*15,__=class{constructor({authority:r,metadataUrl:e,metadata:t,signingKeys:n,metadataSeed:i,client_id:o,client_secret:s,response_type:a=CY,scope:l=kY,redirect_uri:c,post_logout_redirect_uri:u,client_authentication:d=IY,token_endpoint_auth_signing_alg:f="HS256",prompt:p,display:h,max_age:m,ui_locales:E,acr_values:y,resource:S,response_mode:R,filterProtocolClaims:k=!0,loadUserInfo:x=!1,requestTimeoutInSeconds:T,staleStateAgeInSeconds:O=xY,mergeClaimsStrategy:C={array:"replace"},disablePKCE:N=!1,stateStore:F,revokeTokenAdditionalContentTypes:H,fetchRequestCredentials:ie,refreshTokenAllowedScope:$,extraQueryParams:X={},extraTokenParams:oe={},extraHeaders:re={},dpop:ae,omitScopeWhenRequesting:q=!1}){var z;if(this.authority=r,e?this.metadataUrl=e:(this.metadataUrl=r,r&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=t,this.metadataSeed=i,this.signingKeys=n,this.client_id=o,this.client_secret=s,this.response_type=a,this.scope=l,this.redirect_uri=c,this.post_logout_redirect_uri=u,this.client_authentication=d,this.token_endpoint_auth_signing_alg=f,this.prompt=p,this.display=h,this.max_age=m,this.ui_locales=E,this.acr_values=y,this.resource=S,this.response_mode=R,this.filterProtocolClaims=k??!0,this.loadUserInfo=!!x,this.staleStateAgeInSeconds=O,this.mergeClaimsStrategy=C,this.omitScopeWhenRequesting=q,this.disablePKCE=!!N,this.revokeTokenAdditionalContentTypes=H,this.fetchRequestCredentials=ie||"same-origin",this.requestTimeoutInSeconds=T,F)this.stateStore=F;else{const Q=typeof window<"u"?window.localStorage:new RY;this.stateStore=new Fm({store:Q})}if(this.refreshTokenAllowedScope=$,this.extraQueryParams=X,this.extraTokenParams=oe,this.extraHeaders=re,this.dpop=ae,this.dpop&&!((z=this.dpop)!=null&&z.store))throw new Error("A DPoPStore is required when dpop is enabled")}},OY=class{constructor(r,e){this._settings=r,this._metadataService=e,this._logger=new Qt("UserInfoService"),this._getClaimsFromJwt=async t=>{const n=this._logger.create("_getClaimsFromJwt");try{const i=Jd.decode(t);return n.debug("JWT decoding successful"),i}catch(i){throw n.error("Error parsing JWT response"),i}},this._jsonService=new e0(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(r){const e=this._logger.create("getClaims");r||this._logger.throw(new Error("No token passed"));const t=await this._metadataService.getUserInfoEndpoint();e.debug("got userinfo url",t);const n=await this._jsonService.getJson(t,{token:r,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("got claims",n),n}},uL=class{constructor(r,e){this._settings=r,this._metadataService=e,this._logger=new Qt("TokenClient"),this._jsonService=new e0(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:r="authorization_code",redirect_uri:e=this._settings.redirect_uri,client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:i,...o}){const s=this._logger.create("exchangeCode");t||s.throw(new Error("A client_id is required")),e||s.throw(new Error("A redirect_uri is required")),o.code||s.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:r,redirect_uri:e});for(const[d,f]of Object.entries(o))f!=null&&a.set(d,f);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&n==null)throw s.throw(new Error("A client_secret is required")),null;let l;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":l=Or.generateBasicAuth(t,n);break;case"client_secret_post":a.append("client_id",t),n&&a.append("client_secret",n);break;case"client_secret_jwt":{const d=await Or.generateClientAssertionJwt(t,n,c,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",t),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",d);break}}s.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return s.debug("got response"),u}async exchangeCredentials({grant_type:r="password",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,scope:n=this._settings.scope,...i}){const o=this._logger.create("exchangeCredentials");e||o.throw(new Error("A client_id is required"));const s=new URLSearchParams({grant_type:r});this._settings.omitScopeWhenRequesting||s.set("scope",n);for(const[u,d]of Object.entries(i))d!=null&&s.set(u,d);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&t==null)throw o.throw(new Error("A client_secret is required")),null;let a;const l=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":a=Or.generateBasicAuth(e,t);break;case"client_secret_post":s.append("client_id",e),t&&s.append("client_secret",t);break;case"client_secret_jwt":{const u=await Or.generateClientAssertionJwt(e,t,l,this._settings.token_endpoint_auth_signing_alg);s.append("client_id",e),s.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),s.append("client_assertion",u);break}}o.debug("got token endpoint");const c=await this._jsonService.postForm(l,{body:s,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return o.debug("got response"),c}async exchangeRefreshToken({grant_type:r="refresh_token",client_id:e=this._settings.client_id,client_secret:t=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:i,...o}){const s=this._logger.create("exchangeRefreshToken");e||s.throw(new Error("A client_id is required")),o.refresh_token||s.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:r});for(const[d,f]of Object.entries(o))Array.isArray(f)?f.forEach(p=>a.append(d,p)):f!=null&&a.set(d,f);if((this._settings.client_authentication==="client_secret_basic"||this._settings.client_authentication==="client_secret_jwt")&&t==null)throw s.throw(new Error("A client_secret is required")),null;let l;const c=await this._metadataService.getTokenEndpoint(!1);switch(this._settings.client_authentication){case"client_secret_basic":l=Or.generateBasicAuth(e,t);break;case"client_secret_post":a.append("client_id",e),t&&a.append("client_secret",t);break;case"client_secret_jwt":{const d=await Or.generateClientAssertionJwt(e,t,c,this._settings.token_endpoint_auth_signing_alg);a.append("client_id",e),a.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),a.append("client_assertion",d);break}}s.debug("got token endpoint");const u=await this._jsonService.postForm(c,{body:a,basicAuth:l,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:i});return s.debug("got response"),u}async revoke(r){var e;const t=this._logger.create("revoke");r.token||t.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);t.debug(`got revocation endpoint, revoking ${(e=r.token_type_hint)!=null?e:"default token type"}`);const i=new URLSearchParams;for(const[o,s]of Object.entries(r))s!=null&&i.set(o,s);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:i,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),t.debug("got response")}},PY=class{constructor(r,e,t){this._settings=r,this._metadataService=e,this._claimsService=t,this._logger=new Qt("ResponseValidator"),this._userInfoService=new OY(this._settings,this._metadataService),this._tokenClient=new uL(this._settings,this._metadataService)}async validateSigninResponse(r,e,t){const n=this._logger.create("validateSigninResponse");this._processSigninState(r,e),n.debug("state processed"),await this._processCode(r,e,t),n.debug("code processed"),r.isOpenId&&this._validateIdTokenAttributes(r,"",e.nonce),n.debug("tokens validated"),await this._processClaims(r,e==null?void 0:e.skipUserInfo,r.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(r,e){const t=this._logger.create("validateCredentialsResponse"),n=r.isOpenId&&!!r.id_token;n&&this._validateIdTokenAttributes(r),t.debug("tokens validated"),await this._processClaims(r,e,n),t.debug("claims processed")}async validateRefreshResponse(r,e){var t,n;const i=this._logger.create("validateRefreshResponse");r.userState=e.data,(t=r.session_state)!=null||(r.session_state=e.session_state),(n=r.scope)!=null||(r.scope=e.scope),r.isOpenId&&r.id_token&&(this._validateIdTokenAttributes(r,e.id_token),i.debug("ID Token validated")),r.id_token||(r.id_token=e.id_token,r.profile=e.profile);const o=r.isOpenId&&!!r.id_token;await this._processClaims(r,!1,o),i.debug("claims processed")}validateSignoutResponse(r,e){const t=this._logger.create("validateSignoutResponse");if(e.id!==r.state&&t.throw(new Error("State does not match")),t.debug("state validated"),r.userState=e.data,r.error)throw t.warn("Response was error",r.error),new Xd(r)}_processSigninState(r,e){var t;const n=this._logger.create("_processSigninState");if(e.id!==r.state&&n.throw(new Error("State does not match")),e.client_id||n.throw(new Error("No client_id on state")),e.authority||n.throw(new Error("No authority on state")),this._settings.authority!==e.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==e.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),r.userState=e.data,r.url_state=e.url_state,(t=r.scope)!=null||(r.scope=e.scope),r.error)throw n.warn("Response was error",r.error),new Xd(r);e.code_verifier&&!r.code&&n.throw(new Error("Expected code in response"))}async _processClaims(r,e=!1,t=!0){const n=this._logger.create("_processClaims");if(r.profile=this._claimsService.filterProtocolClaims(r.profile),e||!this._settings.loadUserInfo||!r.access_token){n.debug("not loading user info");return}n.debug("loading user info");const i=await this._userInfoService.getClaims(r.access_token);n.debug("user info claims received from user info endpoint"),t&&i.sub!==r.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),r.profile=this._claimsService.mergeClaims(r.profile,this._claimsService.filterProtocolClaims(i)),n.debug("user info claims received, updated profile:",r.profile)}async _processCode(r,e,t){const n=this._logger.create("_processCode");if(r.code){n.debug("Validating code");const i=await this._tokenClient.exchangeCode({client_id:e.client_id,client_secret:e.client_secret,code:r.code,redirect_uri:e.redirect_uri,code_verifier:e.code_verifier,extraHeaders:t,...e.extraTokenParams});Object.assign(r,i)}else n.debug("No code to process")}_validateIdTokenAttributes(r,e,t){var n;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const o=Jd.decode((n=r.id_token)!=null?n:"");if(o.sub||i.throw(new Error("ID Token is missing a subject claim")),t&&o.nonce!==t&&i.throw(new Error("nonce in id_token does not match nonce in client storage")),e){const s=Jd.decode(e);o.sub!==s.sub&&i.throw(new Error("sub in id_token does not match current sub")),o.auth_time&&o.auth_time!==s.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),o.azp&&o.azp!==s.azp&&i.throw(new Error("azp in id_token does not match original azp")),!o.azp&&s.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}r.profile=o}},Sv=class E_{constructor(e){this.id=e.id||Or.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=yv.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Qt("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 Qt.createStatic("State","fromStorageString"),Promise.resolve(new E_(JSON.parse(e)))}static async clearStaleState(e,t){const n=Qt.createStatic("State","clearStaleState"),i=yv.getEpochTime()-t,o=await e.getAllKeys();n.debug("got keys",o);for(let s=0;s<o.length;s++){const a=o[s],l=await e.get(a);let c=!1;if(l)try{const u=await E_.fromStorageString(l);n.debug("got item from key:",a,u.created),u.created<=i&&(c=!0)}catch(u){n.error("Error parsing state for key:",a,u),c=!0}else n.debug("no item in storage for key:",a),c=!0;c&&(n.debug("removed item for key:",a),e.remove(a))}}},t0=class w_ extends Sv{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,this.nonce=e.nonce}static async create(e){const t=e.code_verifier===!0?Or.generateCodeVerifier():e.code_verifier||void 0,n=t?await Or.generateCodeChallenge(t):void 0;return new w_({...e,code_verifier:t,code_challenge:n})}toStorageString(){return new Qt("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,nonce:this.nonce})}static fromStorageString(e){Qt.createStatic("SigninState","fromStorageString");const t=JSON.parse(e);return w_.create(t)}},dL=class fL{constructor(e){this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:n,redirect_uri:i,response_type:o,scope:s,state_data:a,response_mode:l,request_type:c,client_secret:u,nonce:d,url_state:f,resource:p,skipUserInfo:h,extraQueryParams:m,extraTokenParams:E,disablePKCE:y,dpopJkt:S,omitScopeWhenRequesting:R,...k}){if(!e)throw this._logger.error("create: No url passed"),new Error("url");if(!n)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(!o)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!s)throw this._logger.error("create: No scope passed"),new Error("scope");if(!t)throw this._logger.error("create: No authority passed"),new Error("authority");const x=await t0.create({data:a,request_type:c,url_state:f,code_verifier:!y,client_id:n,authority:t,redirect_uri:i,response_mode:l,client_secret:u,scope:s,extraTokenParams:E,skipUserInfo:h,nonce:d}),T=new URL(e);T.searchParams.append("client_id",n),T.searchParams.append("redirect_uri",i),T.searchParams.append("response_type",o),R||T.searchParams.append("scope",s),d&&T.searchParams.append("nonce",d),S&&T.searchParams.append("dpop_jkt",S);let O=x.id;f&&(O=`${O}${Ic}${f}`),T.searchParams.append("state",O),x.code_challenge&&(T.searchParams.append("code_challenge",x.code_challenge),T.searchParams.append("code_challenge_method","S256")),p&&(Array.isArray(p)?p:[p]).forEach(N=>T.searchParams.append("resource",N));for(const[C,N]of Object.entries({response_mode:l,...k,...m}))N!=null&&T.searchParams.append(C,N.toString());return new fL({url:T.href,state:x})}};dL._logger=new Qt("SigninRequest");var MY=dL,AY="openid",fp=class{constructor(r){if(this.access_token="",this.token_type="",this.profile={},this.state=r.get("state"),this.session_state=r.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(Ic);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Ic))}this.error=r.get("error"),this.error_description=r.get("error_description"),this.error_uri=r.get("error_uri"),this.code=r.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-yv.getEpochTime()}set expires_in(r){typeof r=="string"&&(r=Number(r)),r!==void 0&&r>=0&&(this.expires_at=Math.floor(r)+yv.getEpochTime())}get isOpenId(){var r;return((r=this.scope)==null?void 0:r.split(" ").includes(AY))||!!this.id_token}},DY=class{constructor({url:r,state_data:e,id_token_hint:t,post_logout_redirect_uri:n,extraQueryParams:i,request_type:o,client_id:s,url_state:a}){if(this._logger=new Qt("SignoutRequest"),!r)throw this._logger.error("ctor: No url passed"),new Error("url");const l=new URL(r);if(t&&l.searchParams.append("id_token_hint",t),s&&l.searchParams.append("client_id",s),n&&(l.searchParams.append("post_logout_redirect_uri",n),e||a)){this.state=new Sv({data:e,request_type:o,url_state:a});let c=this.state.id;a&&(c=`${c}${Ic}${a}`),l.searchParams.append("state",c)}for(const[c,u]of Object.entries({...i}))u!=null&&l.searchParams.append(c,u.toString());this.url=l.href}},NY=class{constructor(r){if(this.state=r.get("state"),this.state){const e=decodeURIComponent(this.state).split(Ic);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Ic))}this.error=r.get("error"),this.error_description=r.get("error_description"),this.error_uri=r.get("error_uri")}},LY=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],UY=["sub","iss","aud","exp","iat"],jY=class{constructor(r){this._settings=r,this._logger=new Qt("ClaimsService")}filterProtocolClaims(r){const e={...r};if(this._settings.filterProtocolClaims){let t;Array.isArray(this._settings.filterProtocolClaims)?t=this._settings.filterProtocolClaims:t=LY;for(const n of t)UY.includes(n)||delete e[n]}return e}mergeClaims(r,e){const t={...r};for(const[n,i]of Object.entries(e))if(t[n]!==i)if(Array.isArray(t[n])||Array.isArray(i))if(this._settings.mergeClaimsStrategy.array=="replace")t[n]=i;else{const o=Array.isArray(t[n])?t[n]:[t[n]];for(const s of Array.isArray(i)?i:[i])o.includes(s)||o.push(s);t[n]=o}else typeof t[n]=="object"&&typeof i=="object"?t[n]=this.mergeClaims(t[n],i):t[n]=i;return t}},FY=class{constructor(r,e){this.keys=r,this.nonce=e}},r0=class{constructor(r,e){this._logger=new Qt("OidcClient"),this.settings=r instanceof __?r:new __(r),this.metadataService=e??new cL(this.settings),this._claimsService=new jY(this.settings),this._validator=new PY(this.settings,this.metadataService,this._claimsService),this._tokenClient=new uL(this.settings,this.metadataService)}async createSigninRequest({state:r,request:e,request_uri:t,request_type:n,id_token_hint:i,login_hint:o,skipUserInfo:s,nonce:a,url_state:l,response_type:c=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:f=this.settings.prompt,display:p=this.settings.display,max_age:h=this.settings.max_age,ui_locales:m=this.settings.ui_locales,acr_values:E=this.settings.acr_values,resource:y=this.settings.resource,response_mode:S=this.settings.response_mode,extraQueryParams:R=this.settings.extraQueryParams,extraTokenParams:k=this.settings.extraTokenParams,dpopJkt:x,omitScopeWhenRequesting:T=this.settings.omitScopeWhenRequesting}){const O=this._logger.create("createSigninRequest");if(c!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const C=await this.metadataService.getAuthorizationEndpoint();O.debug("Received authorization endpoint",C);const N=await MY.create({url:C,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:c,scope:u,state_data:r,url_state:l,prompt:f,display:p,max_age:h,ui_locales:m,id_token_hint:i,login_hint:o,acr_values:E,dpopJkt:x,resource:y,request:e,request_uri:t,extraQueryParams:R,extraTokenParams:k,request_type:n,response_mode:S,client_secret:this.settings.client_secret,skipUserInfo:s,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:T});await this.clearStaleState();const F=N.state;return await this.settings.stateStore.set(F.id,F.toStorageString()),N}async readSigninResponseState(r,e=!1){const t=this._logger.create("readSigninResponseState"),n=new fp(dI.readParams(r,this.settings.response_mode));if(!n.state)throw t.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[e?"remove":"get"](n.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await t0.fromStorageString(i),response:n}}async processSigninResponse(r,e,t=!0){const n=this._logger.create("processSigninResponse"),{state:i,response:o}=await this.readSigninResponseState(r,t);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(o,i,e)}catch(s){if(s instanceof b_&&this.settings.dpop){const a=await this.getDpopProof(this.settings.dpop.store,s.nonce);e.DPoP=a,await this._validator.validateSigninResponse(o,i,e)}else throw s}return o}async getDpopProof(r,e){let t,n;return(await r.getAllKeys()).includes(this.settings.client_id)?(n=await r.get(this.settings.client_id),n.nonce!==e&&e&&(n.nonce=e,await r.set(this.settings.client_id,n))):(t=await Or.generateDPoPKeys(),n=new FY(t,e),await r.set(this.settings.client_id,n)),await Or.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:r,password:e,skipUserInfo:t=!1,extraTokenParams:n={}}){const i=await this._tokenClient.exchangeCredentials({username:r,password:e,...n}),o=new fp(new URLSearchParams);return Object.assign(o,i),await this._validator.validateCredentialsResponse(o,t),o}async useRefreshToken({state:r,redirect_uri:e,resource:t,timeoutInSeconds:n,extraHeaders:i,extraTokenParams:o}){var s;const a=this._logger.create("useRefreshToken");let l;if(this.settings.refreshTokenAllowedScope===void 0)l=r.scope;else{const d=this.settings.refreshTokenAllowedScope.split(" ");l=(((s=r.scope)==null?void 0:s.split(" "))||[]).filter(p=>d.includes(p)).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const d=await this.getDpopProof(this.settings.dpop.store);i={...i,DPoP:d}}let c;try{c=await this._tokenClient.exchangeRefreshToken({refresh_token:r.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:n,extraHeaders:i,...o})}catch(d){if(d instanceof b_&&this.settings.dpop)i.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),c=await this._tokenClient.exchangeRefreshToken({refresh_token:r.refresh_token,scope:l,redirect_uri:e,resource:t,timeoutInSeconds:n,extraHeaders:i,...o});else throw d}const u=new fp(new URLSearchParams);return Object.assign(u,c),a.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...r,scope:l}),u}async createSignoutRequest({state:r,id_token_hint:e,client_id:t,request_type:n,url_state:i,post_logout_redirect_uri:o=this.settings.post_logout_redirect_uri,extraQueryParams:s=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),l=await this.metadataService.getEndSessionEndpoint();if(!l)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",l),!t&&o&&!e&&(t=this.settings.client_id);const c=new DY({url:l,id_token_hint:e,client_id:t,post_logout_redirect_uri:o,state_data:r,extraQueryParams:s,request_type:n,url_state:i});await this.clearStaleState();const u=c.state;return u&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),c}async readSignoutResponseState(r,e=!1){const t=this._logger.create("readSignoutResponseState"),n=new NY(dI.readParams(r,this.settings.response_mode));if(!n.state){if(t.debug("No state in response"),n.error)throw t.warn("Response was error:",n.error),new Xd(n);return{state:void 0,response:n}}const i=await this.settings.stateStore[e?"remove":"get"](n.state);if(!i)throw t.throw(new Error("No matching state found in storage")),null;return{state:await Sv.fromStorageString(i),response:n}}async processSignoutResponse(r){const e=this._logger.create("processSignoutResponse"),{state:t,response:n}=await this.readSignoutResponseState(r,!0);return t?(e.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,t)):e.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),Sv.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(r,e){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:r,token_type_hint:e})}},Wr=function(r){return r.NotSupported="OIDC authentication not supported",r.Misconfigured="OIDC is misconfigured",r.General="Something went wrong with OIDC discovery",r.OpSupport="Configured OIDC OP does not support required functions",r.DynamicRegistrationNotSupported="Dynamic registration not supported",r.DynamicRegistrationFailed="Dynamic registration failed",r.DynamicRegistrationInvalid="Dynamic registration invalid response",r.CodeExchangeFailed="Failed to exchange code for token",r.InvalidBearerTokenResponse="Invalid bearer token response",r.InvalidIdToken="Invalid ID token",r.MissingOrInvalidStoredState="State required to finish logging in is not found in storage.",r}({}),n0=r=>!!r&&typeof r=="object"&&!Array.isArray(r),Is=(r,e)=>!r[e]||!ld(r,e)?(b.error("Missing or invalid property: ".concat(e)),!1):!0,ld=(r,e)=>r[e]&&typeof r[e]!="string"?(b.error("Invalid property: ".concat(e)),!1):!0,BY=(r,e)=>r[e]&&(!Array.isArray(r[e])||!r[e].every(t=>typeof t=="string"))?(b.error("Invalid property: ".concat(e)),!1):!0,yy=(r,e,t)=>{var n=r[e];return!n||!Array.isArray(n)||!n.includes(t)?(b.error("Invalid property: ".concat(e,". ").concat(t," is required.")),!1):!0},i0=r=>{if(!n0(r))throw b.error("Issuer configuration not found or malformed"),new Error(Wr.OpSupport);var e=[Is(r,"authorization_endpoint"),Is(r,"token_endpoint"),Is(r,"revocation_endpoint"),ld(r,"registration_endpoint"),ld(r,"account_management_uri"),ld(r,"device_authorization_endpoint"),BY(r,"account_management_actions_supported"),yy(r,"response_types_supported","code"),yy(r,"grant_types_supported","authorization_code"),yy(r,"code_challenge_methods_supported","S256")].some(t=>!t);if(!e)return{authorizationEndpoint:r.authorization_endpoint,tokenEndpoint:r.token_endpoint,registrationEndpoint:r.registration_endpoint,accountManagementEndpoint:r.account_management_uri,accountManagementActionsSupported:r.account_management_actions_supported};throw b.error("Issuer configuration not valid"),new Error(Wr.OpSupport)};function hL(r){i0(r)}var pL=r=>{try{return aL(r)}catch(e){throw b.error("Could not decode id_token",e),e}},vL=(r,e,t,n)=>{try{if(!r)throw new Error("No ID token");var i=pL(r);if(i.iss!==e)throw new Error("Invalid issuer");if(i.aud!==t)throw new Error("Invalid audience");if(n!==void 0&&i.nonce!==n)throw new Error("Invalid nonce");if(!i.exp||Date.now()>i.exp*1e3)throw new Error("Invalid expiry")}catch(o){throw b.error("Invalid ID token",o),new Error(Wr.InvalidIdToken)}};function mL(r){if(!n0(r))throw b.error("Stored user state not found"),new Error(Wr.MissingOrInvalidStoredState);var e=[Is(r,"homeserverUrl"),Is(r,"nonce"),ld(r,"identityServerUrl")].some(t=>!t);if(e)throw new Error(Wr.MissingOrInvalidStoredState)}var KY=r=>n0(r)&&Is(r,"token_type")&&r.token_type.toLowerCase()==="bearer"&&Is(r,"access_token")&&Is(r,"refresh_token")&&(!("expires_in"in r)||typeof r.expires_in=="number");function gL(r){if(!KY(r))throw new Error(Wr.InvalidBearerTokenResponse)}function fI(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function bv(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?fI(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):fI(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var Bm=r=>{var e=r??Ei(10);return"openid urn:matrix:org.matrix.msc2967.client:api:* urn:matrix:org.matrix.msc2967.client:device:".concat(e)},VY=function(){var r=w(function*(e){if(!globalThis.crypto.subtle)return b.warn("A secure context is required to generate code challenge. Using plain text code challenge"),e;var t=yield YN(e);return Cm(t)});return function(t){return r.apply(this,arguments)}}(),$Y=r=>{var{redirectUri:e}=r;return{scope:Bm(),redirectUri:e,state:Ei(8),nonce:Ei(8),codeVerifier:Ei(64)}},WY=function(){var r=w(function*(e,t,n){var{scope:i,redirectUri:o,state:s,nonce:a,codeVerifier:l}=n,c=new URL(e);return c.searchParams.append("response_mode","query"),c.searchParams.append("response_type","code"),c.searchParams.append("redirect_uri",o),c.searchParams.append("client_id",t),c.searchParams.append("state",s),c.searchParams.append("scope",i),c.searchParams.append("nonce",a),c.searchParams.append("code_challenge_method","S256"),c.searchParams.append("code_challenge",yield VY(l)),c.toString()});return function(t,n,i){return r.apply(this,arguments)}}(),qY=function(){var r=w(function*(e){var{metadata:t,redirectUri:n,clientId:i,homeserverUrl:o,identityServerUrl:s,nonce:a,prompt:l,urlState:c}=e,u=Bm(),d=new r0(bv(bv({},t),{},{client_id:i,redirect_uri:n,authority:t.issuer,response_mode:"query",response_type:"code",scope:u,stateStore:new Fm({prefix:"mx_oidc_",store:window.sessionStorage})})),f={homeserverUrl:o,nonce:a,identityServerUrl:s},p=yield d.createSigninRequest({state:f,nonce:a,prompt:l,url_state:c});return p.url});return function(t){return r.apply(this,arguments)}}(),GY=r=>({id_token:r.id_token,scope:r.scope,expires_at:r.expires_at,refresh_token:r.refresh_token,access_token:r.access_token,token_type:"Bearer"}),HY=function(){var r=w(function*(e,t){var n=new URL(window.location.origin);n.searchParams.append("code",e),n.searchParams.append("state",t),Yd.setLogger(b);try{var i=new fp(n.searchParams),o=new Fm({prefix:"mx_oidc_",store:window.sessionStorage}),s=yield o.get(i.state);if(!s)throw new Error(Wr.MissingOrInvalidStoredState);var a=yield t0.fromStorageString(s),l=new r0(bv(bv({},a),{},{stateStore:o})),c=yield l.processSigninResponse(n.href),u=c.userState;mL(u),gL(c),vL(c.id_token,l.settings.authority,l.settings.client_id,u.nonce);var d=GY(c);return{oidcClientSettings:{clientId:l.settings.client_id,issuer:l.settings.authority},tokenResponse:d,homeserverUrl:u.homeserverUrl,identityServerUrl:u.identityServerUrl,idTokenClaims:c.profile}}catch(p){b.error("Oidc login failed",p);var f=p.message;throw Object.values(Wr).includes(f)?p:new Error(Wr.CodeExchangeFailed)}});return function(t,n){return r.apply(this,arguments)}}();function hI(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function pI(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?hI(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):hI(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}var yL=function(){var r=w(function*(e){var t,n=new URL(".well-known/openid-configuration",e),i=yield fetch(n,{method:Z.Get,signal:wm(5e3)}),o=yield i.json(),s=i0(o),a=new __({authority:e,redirect_uri:"",client_id:""}),l=new cL(a),c=yield l.getMetadata(),u=(t=yield l.getSigningKeys())!==null&&t!==void 0?t:void 0;return hL(c),pI(pI({},s),{},{metadata:c,signingKeys:u})});return function(t){return r.apply(this,arguments)}}(),zY="urn:ietf:params:oauth:grant-type:device_code",YY=function(){var r=w(function*(e,t){if(!e.registrationEndpoint)throw new Error(Wr.DynamicRegistrationNotSupported);var n=["authorization_code","refresh_token"];if(n.some(c=>!e.metadata.grant_types_supported.includes(c)))throw new Error(Wr.DynamicRegistrationNotSupported);var i={client_name:t.clientName,client_uri:t.clientUri,response_types:["code"],grant_types:n,redirect_uris:t.redirectUris,id_token_signed_response_alg:"RS256",token_endpoint_auth_method:"none",application_type:t.applicationType,logo_uri:t.logoUri,contacts:t.contacts,policy_uri:t.policyUri,tos_uri:t.tosUri},o={Accept:"application/json","Content-Type":"application/json"};try{var s=yield fetch(e.registrationEndpoint,{method:Z.Post,headers:o,body:JSON.stringify(i)});if(s.status>=400)throw new Error(Wr.DynamicRegistrationFailed);var a=yield s.json(),l=a.client_id;if(!l||typeof l!="string")throw new Error(Wr.DynamicRegistrationInvalid);return l}catch(c){throw Object.values(Wr).includes(c.message)?c:(b.error("Dynamic registration request failed",c),new Error(Wr.DynamicRegistrationFailed))}});return function(t,n){return r.apply(this,arguments)}}();function vI(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function mI(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?vI(Object(t),!0).forEach(function(n){v(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):vI(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}class JY{constructor(e,t,n,i,o){this.idTokenClaims=o,v(this,"oidcClientReady",void 0),v(this,"oidcClient",void 0),v(this,"inflightRefreshRequest",void 0),this.oidcClientReady=this.initialiseOidcClient(e,t,i,n)}initialiseOidcClient(e,t,n,i){var o=this;return w(function*(){try{var s=yield yL(e),a=Bm(n);o.oidcClient=new r0(mI(mI({},s.metadata),{},{client_id:t,scope:a,redirect_uri:i,authority:s.metadata.issuer,stateStore:new Fm({prefix:"mx_oidc_",store:window.sessionStorage})}))}catch(l){throw b.error("Failed to initialise OIDC client.",l),new Error("Failed to initialise OIDC client.")}})()}doRefreshAccessToken(e){var t=this;return w(function*(){t.inflightRefreshRequest||(t.inflightRefreshRequest=t.getNewTokens(e));try{var n=yield t.inflightRefreshRequest;return n}finally{t.inflightRefreshRequest=void 0}})()}persistTokens(e){return w(function*(){})()}getNewTokens(e){var t=this;return w(function*(){if(!t.oidcClient)throw new Error("Cannot get new token before OIDC client is initialised.");var n={refresh_token:e,session_state:"test",data:void 0,profile:t.idTokenClaims},i=yield t.oidcClient.useRefreshToken({state:n,timeoutInSeconds:300}),o={accessToken:i.access_token,refreshToken:i.refresh_token};return yield t.persistTokens(o),o})()}}var gI=function(){},XY=10;class QY{constructor(e,t){var n,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.client=e,this.timelineSet=t,v(this,"windowLimit",void 0),v(this,"start",void 0),v(this,"end",void 0),v(this,"eventCount",0),this.windowLimit=i.windowLimit||1e3,(n=t.room)===null||n===void 0||n.on(pe.Timeline,this.onTimelineEvent.bind(this))}load(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:20,n=i=>{if(!i)throw new Error("No timeline given to initFields");var o,s=i.getEvents();if(!e)o=s.length;else if(o=s.findIndex(c=>c.getId()===e),o<0)throw new Error("getEventTimeline result didn't include requested event");var a=Math.min(s.length,o+Math.ceil(t/2)),l=Math.max(0,a-t);this.start=new T_(i,l-i.getBaseIndex()),this.end=new T_(i,a-i.getBaseIndex()),this.eventCount=a-l};return this.timelineSet.getTimelineForEvent(e)?(n(this.timelineSet.getTimelineForEvent(e)),Promise.resolve()):e?this.client.getEventTimeline(this.timelineSet,e).then(n):(n(this.timelineSet.getLiveTimeline()),Promise.resolve())}getTimelineIndex(e){if(e==we.BACKWARDS){var t;return(t=this.start)!==null&&t!==void 0?t:null}else if(e==we.FORWARDS){var n;return(n=this.end)!==null&&n!==void 0?n:null}else throw new Error("Invalid direction '"+e+"'")}extend(e,t){var n=this.getTimelineIndex(e);if(!n)return!1;var i=e==we.BACKWARDS?n.retreat(t):n.advance(t);if(i){this.eventCount+=i,gI("TimelineWindow: increased cap by "+i+" (now "+this.eventCount+")");var o=this.eventCount-this.windowLimit;return o>0&&this.unpaginate(o,e!=we.BACKWARDS),!0}return!1}onTimelineEvent(e,t,n,i){i&&this.onEventRemoved()}onEventRemoved(){var e=this.getEvents();e.length>0&&e[e.length-1]===void 0&&this.end&&this.end.index--}canPaginate(e){var t=this.getTimelineIndex(e);if(!t)return!1;if(e==we.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;var n=t.timeline.getNeighbouringTimeline(e),i=t.timeline.getPaginationToken(e);return!!n||!!i}paginate(e,t){var n=arguments,i=this;return w(function*(){var o=n.length>2&&n[2]!==void 0?n[2]:!0,s=n.length>3&&n[3]!==void 0?n[3]:XY,a=i.getTimelineIndex(e);if(!a)return!1;if(a.pendingPaginate)return a.pendingPaginate;if(i.extend(e,t))return!0;if(!o||s===0)return!1;var l=a.timeline.getPaginationToken(e);if(!l)return!1;var c=i.client.paginateEventTimeline(a.timeline,{backwards:e==we.BACKWARDS,limit:t}).finally(function(){a.pendingPaginate=void 0}).then(u=>u?i.paginate(e,t,!0,s-1):i.paginate(e,t,!1,0));return a.pendingPaginate=c,c})()}unpaginate(e,t){var n=t?this.start:this.end;if(!n)throw new Error("Attempting to unpaginate startOfTimeline=".concat(t," but don't have this direction"));if(e>this.eventCount||e<0)throw new Error("Attemting to unpaginate ".concat(e," events, but only have ").concat(this.eventCount," in the timeline"));for(;e>0;){var i=t?n.advance(e):n.retreat(e);if(i<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=i,this.eventCount-=i,gI("TimelineWindow.unpaginate: dropped "+i+" (now "+this.eventCount+")")}}getEvents(){if(!this.start)return[];for(var e=[],t=this.start.timeline;t;){var n,i,o=t.getEvents(),s=0,a=o.length;t===this.start.timeline&&(s=this.start.index+t.getBaseIndex()),t===((n=this.end)===null||n===void 0?void 0:n.timeline)&&(a=this.end.index+t.getBaseIndex());for(var l=s;l<a;l++)e.push(o[l]);if(t===((i=this.end)===null||i===void 0?void 0:i.timeline))break;t=t.getNeighbouringTimeline(we.FORWARDS)}return e}}class T_{constructor(e,t){this.timeline=e,this.index=t,v(this,"pendingPaginate",void 0)}minIndex(){return this.timeline.getBaseIndex()*-1}maxIndex(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()}advance(e){if(!e)return 0;var t;if(e<0){if(t=Math.max(e,this.minIndex()-this.index),t<0)return this.index+=t,t}else if(t=Math.min(e,this.maxIndex()-this.index),t>0)return this.index+=t,t;var n=this.timeline.getNeighbouringTimeline(e<0?we.BACKWARDS:we.FORWARDS);return n?(this.timeline=n,e<0?this.index=this.maxIndex():this.index=this.minIndex(),this.advance(e)):0}retreat(e){return this.advance(e*-1)*-1}}var Tu="m.login.email.identity",yI="m.login.msisdn",R_=function(r){return r.Password="m.login.password",r.Recaptcha="m.login.recaptcha",r.Terms="m.login.terms",r.Email="m.login.email.identity",r.Msisdn="m.login.msisdn",r.Sso="m.login.sso",r.SsoUnstable="org.matrix.login.sso",r.Dummy="m.login.dummy",r.RegistrationToken="m.login.registration_token",r.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token",r}({});class SL extends Error{constructor(e,t,n){super(e),this.required_stages=t,this.flows=n,v(this,"name","NoAuthFlowFoundError")}}class ZY{constructor(e){var t=this;v(this,"matrixClient",void 0),v(this,"inputs",void 0),v(this,"clientSecret",void 0),v(this,"requestCallback",void 0),v(this,"busyChangedCallback",void 0),v(this,"stateUpdatedCallback",void 0),v(this,"requestEmailTokenCallback",void 0),v(this,"supportedStages",void 0),v(this,"data",void 0),v(this,"emailSid",void 0),v(this,"requestingEmailToken",!1),v(this,"attemptAuthDeferred",null),v(this,"chosenFlow",null),v(this,"currentStage",null),v(this,"emailAttempt",1),v(this,"submitPromise",null),v(this,"requestEmailToken",w(function*(){if(t.requestingEmailToken)b.warn("Could not request email token: Already requesting");else{b.trace("Requesting email token. Attempt: "+t.emailAttempt),t.requestingEmailToken=!0;try{var n=yield t.requestEmailTokenCallback(t.inputs.emailAddress,t.clientSecret,t.emailAttempt++,t.data.session);t.emailSid=n.sid,b.trace("Email token request succeeded")}finally{t.requestingEmailToken=!1}}})),this.matrixClient=e.matrixClient,this.data=e.authData||{flows:[]},this.requestCallback=e.doRequest,this.busyChangedCallback=e.busyChanged,this.stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this.requestEmailTokenCallback=e.requestEmailToken,this.inputs=e.inputs||{},e.sessionId&&(this.data.session=e.sessionId),this.clientSecret=e.clientSecret||this.matrixClient.generateClientSecret(),this.emailSid=e.emailSid,e.supportedStages!==void 0&&(this.supportedStages=new Set(e.supportedStages))}attemptAuth(){var e=this;return w(function*(){var t;e.attemptAuthDeferred=Hs();var n=e.attemptAuthDeferred.promise;if((t=e.data)!==null&&t!==void 0&&(t=t.flows)!==null&&t!==void 0&&t.length)e.startNextAuthStage();else{var i;(i=e.busyChangedCallback)===null||i===void 0||i.call(e,!0);var o=e.data.session?{session:e.data.session}:null;e.doRequest(o).finally(()=>{var s;(s=e.busyChangedCallback)===null||s===void 0||s.call(e,!1)})}return n})()}poll(){var e=this;return w(function*(){if(e.data.session&&e.attemptAuthDeferred&&!e.submitPromise){var t={};if(e.currentStage==Tu&&e.emailSid){var n={sid:e.emailSid,client_secret:e.clientSecret},i=e.matrixClient.getIdentityServerUrl();i&&(n.id_server=new URL(i).host),t={type:Tu,threepid_creds:n}}e.submitAuthDict(t,!0)}})()}getSessionId(){var e;return(e=this.data)===null||e===void 0?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var t;return(t=this.data)===null||t===void 0||(t=t.params)===null||t===void 0?void 0:t[e]}getChosenFlow(){return this.chosenFlow}submitAuthDict(e){var t=arguments,n=this;return w(function*(){var i,o=t.length>1&&t[1]!==void 0?t[1]:!1;if(!n.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");if(!o){var s;(s=n.busyChangedCallback)===null||s===void 0||s.call(n,!0)}for(;n.submitPromise;)try{yield n.submitPromise}catch{}var a;(i=n.data)!==null&&i!==void 0&&i.session?(a={session:n.data.session},Object.assign(a,e)):a=e;try{n.submitPromise=n.doRequest(a,o),yield n.submitPromise}finally{if(n.submitPromise=null,!o){var l;(l=n.busyChangedCallback)===null||l===void 0||l.call(n,!1)}}})()}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}doRequest(e){var t=arguments,n=this;return w(function*(){var i=t.length>1&&t[1]!==void 0?t[1]:!1;try{var o=yield n.requestCallback(e,i);n.attemptAuthDeferred.resolve(o),n.attemptAuthDeferred=null}catch(h){var s,a,l,c,u=h instanceof hr?h:null,d=(s=u==null||(a=u.data)===null||a===void 0?void 0:a.flows)!==null&&s!==void 0?s:null,f=((l=n.data)===null||l===void 0?void 0:l.flows)||!!d;if(!u||u.httpStatus!==401||!u.data||!f)if(i)b.log("Background poll request failed doing UI auth: ignoring",h);else{var p;(p=n.attemptAuthDeferred)===null||p===void 0||p.reject(h)}u&&!u.data&&(u.data={}),u&&!u.data.flows&&!u.data.completed&&!u.data.session&&(u.data.flows=n.data.flows,u.data.completed=n.data.completed,u.data.session=n.data.session),u&&(n.data=u.data);try{n.startNextAuthStage()}catch(m){n.attemptAuthDeferred.reject(m),n.attemptAuthDeferred=null;return}if(!n.emailSid&&(c=n.chosenFlow)!==null&&c!==void 0&&c.stages.includes(R_.Email))try{yield n.requestEmailToken()}catch(m){n.attemptAuthDeferred.reject(m),n.attemptAuthDeferred=null}}})()}startNextAuthStage(){var e,t,n=this.chooseStage();if(!n)throw new Error("No incomplete flows from the server");if(this.currentStage=n,n===R_.Dummy){this.submitAuthDict({type:"m.login.dummy"});return}if((e=this.data)!==null&&e!==void 0&&e.errcode||(t=this.data)!==null&&t!==void 0&&t.error){var i,o;this.stateUpdatedCallback(n,{errcode:((i=this.data)===null||i===void 0?void 0:i.errcode)||"",error:((o=this.data)===null||o===void 0?void 0:o.error)||""});return}this.stateUpdatedCallback(n,n===Tu?{emailSid:this.emailSid}:{})}chooseStage(){this.chosenFlow===null&&(this.chosenFlow=this.chooseFlow()),b.log("Active flow => %s",JSON.stringify(this.chosenFlow));var e=this.firstUncompletedStage(this.chosenFlow);return b.log("Next stage: %s",e),e}scoreFlow(e){var t=e.stages.length;return this.supportedStages!==void 0&&(t+=e.stages.filter(n=>!this.supportedStages.has(n)).length*10),t}chooseFlow(){var e,t=((e=this.data)===null||e===void 0?void 0:e.flows)||[],n=!!this.inputs.emailAddress||!!this.emailSid,i=!!this.inputs.phoneCountry&&!!this.inputs.phoneNumber;t.sort((u,d)=>this.scoreFlow(u)-this.scoreFlow(d));for(var o of t){var s=!1,a=!1;for(var l of o.stages)l===Tu?s=!0:l==yI&&(a=!0);if(s==n&&a==i)return o}var c=[];throw n&&c.push(Tu),i&&c.push(yI),new SL("No appropriate authentication flow found",c,t)}firstUncompletedStage(e){var t,n=((t=this.data)===null||t===void 0?void 0:t.completed)||[];return e.stages.find(i=>!n.includes(i))}}var bL=[r=>{r.createObjectStore("users",{keyPath:["userId"]}),r.createObjectStore("accountData",{keyPath:["type"]}),r.createObjectStore("sync",{keyPath:["clobber"]})},r=>{var e=r.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]});e.createIndex("room","room_id")},r=>{r.createObjectStore("client_options",{keyPath:["clobber"]})},r=>{r.createObjectStore("to_device_queue",{autoIncrement:!0})}],eJ=bL.length;function Ch(r,e,t){var n=r.openCursor(e);return new Promise((i,o)=>{var s=[];n.onerror=()=>{o(new Error("Query failed: "+n.error))},n.onsuccess=()=>{var a=n.result;if(!a){i(s);return}s.push(t(a)),a.continue()}})}function sa(r){return new Promise((e,t)=>{r.oncomplete=function(n){e(n)},r.onerror=function(){t(r.error)}})}function _L(r){return new Promise((e,t)=>{r.onsuccess=function(n){e(n)},r.onerror=function(){t(r.error)}})}function tJ(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r),r.onerror=n=>t(n)})}function Sy(r){return _L(r).then(e=>r.result)}class SI{static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),xN(e,t)}constructor(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"default";this.indexedDB=e,v(this,"dbName",void 0),v(this,"syncAccumulator",void 0),v(this,"db",void 0),v(this,"disconnected",!0),v(this,"_isNewlyCreated",!1),v(this,"syncToDatabasePromise",void 0),v(this,"pendingUserPresenceData",[]),this.dbName="matrix-js-sdk:"+t,this.syncAccumulator=new sL}connect(e){var t=this;if(!this.disconnected)return b.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,b.log("LocalIndexedDBStoreBackend.connect: connecting...");var n=this.indexedDB.open(this.dbName,eJ);return n.onupgradeneeded=i=>{var o=n.result,s=i.oldVersion;b.log("LocalIndexedDBStoreBackend.connect: upgrading from ".concat(s)),s<1&&(this._isNewlyCreated=!0),bL.forEach((a,l)=>{s<=l&&a(o)})},n.onblocked=()=>{b.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},b.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),_L(n).then(w(function*(){b.log("LocalIndexedDBStoreBackend.connect: connected"),t.db=n.result,t.db.onversionchange=()=>{var i;(i=t.db)===null||i===void 0||i.close(),t.disconnected=!0,t.db=void 0},t.db.onclose=()=>{t.disconnected=!0,t.db=void 0,e==null||e()},yield t.init()}))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then(e=>{var[t,n]=e;b.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:n.nextBatch,rooms:n.roomsData,account_data:{events:t}},!0)})}getOutOfBandMembers(e){return new Promise((t,n)=>{var i=this.db.transaction(["oob_membership_events"],"readonly"),o=i.objectStore("oob_membership_events"),s=o.index("room"),a=IDBKeyRange.only(e),l=s.openCursor(a),c=[],u=!1;l.onsuccess=()=>{var d=l.result;if(!d)return!c.length&&!u?t(null):t(c);var f=d.value;f.oob_written?u=!0:c.push(f),d.continue()},l.onerror=d=>{n(d)}}).then(t=>(b.log("LL: got ".concat(t==null?void 0:t.length," membershipEvents from storage for room ").concat(e," ...")),t))}setOutOfBandMembers(e,t){var n=this;return w(function*(){b.log("LL: backend about to store ".concat(t.length)+" members for ".concat(e));var i=n.db.transaction(["oob_membership_events"],"readwrite"),o=i.objectStore("oob_membership_events");t.forEach(a=>{o.put(a)});var s={room_id:e,oob_written:!0,state_key:0};o.put(s),yield sa(i),b.log("LL: backend done storing for ".concat(e,"!"))})()}clearOutOfBandMembers(e){var t=this;return w(function*(){var n=t.db.transaction(["oob_membership_events"],"readonly"),i=n.objectStore("oob_membership_events"),o=i.index("room"),s=IDBKeyRange.only(e),a=Sy(o.openKeyCursor(s,"next")).then(h=>(h==null?void 0:h.primaryKey)[1]),l=Sy(o.openKeyCursor(s,"prev")).then(h=>(h==null?void 0:h.primaryKey)[1]),[c,u]=yield Promise.all([a,l]),d=t.db.transaction(["oob_membership_events"],"readwrite"),f=d.objectStore("oob_membership_events"),p=IDBKeyRange.bound([e,c],[e,u]);b.log("LL: Deleting all users + marker in storage for room ".concat(e,", with key range:"),[e,c],[e,u]),yield tJ(f.delete(p))})()}clearDatabase(){return new Promise(e=>{var t;b.log("Removing indexeddb instance: ".concat(this.dbName)),(t=this.db)===null||t===void 0||t.close();var n=this.indexedDB.deleteDatabase(this.dbName);n.onblocked=()=>{b.log("can't yet delete indexeddb ".concat(this.dbName," because it is open elsewhere"))},n.onerror=()=>{b.warn("unable to delete js-sdk store indexeddb: ".concat(n.error)),e()},n.onsuccess=()=>{b.log("Removed indexeddb instance: ".concat(this.dbName)),e()}})}getSavedSync(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(ym(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then(()=>{this.syncAccumulator.accumulate(e)})}syncToDatabase(e){var t=this;return w(function*(){return t.syncToDatabasePromise?(b.warn("Skipping syncToDatabase() as persist already in flight"),t.pendingUserPresenceData.push(...e),t.syncToDatabasePromise):(e.unshift(...t.pendingUserPresenceData),t.syncToDatabasePromise=t.doSyncToDatabase(e),t.syncToDatabasePromise)})()}doSyncToDatabase(e){var t=this;return w(function*(){try{var n=t.syncAccumulator.getJSON(!0);yield Promise.all([t.persistUserPresenceEvents(e),t.persistAccountData(n.accountData),t.persistSyncData(n.nextBatch,n.roomsData)])}finally{t.syncToDatabasePromise=void 0}})()}persistSyncData(e,t){return b.log("Persisting sync data up to",e),da(()=>{var n=this.db.transaction(["sync"],"readwrite"),i=n.objectStore("sync");return i.put({clobber:"-",nextBatch:e,roomsData:t}),sa(n).then(()=>{b.log("Persisted sync data up to",e)})})}persistAccountData(e){return da(()=>{var t=this.db.transaction(["accountData"],"readwrite"),n=t.objectStore("accountData");for(var i of e)n.put(i);return sa(t).then()})}persistUserPresenceEvents(e){return da(()=>{var t=this.db.transaction(["users"],"readwrite"),n=t.objectStore("users");for(var i of e)n.put({userId:i[0],event:i[1]});return sa(t).then()})}getUserPresenceEvents(){return da(()=>{var e=this.db.transaction(["users"],"readonly"),t=e.objectStore("users");return Ch(t,void 0,n=>[n.value.userId,n.value.event])})}loadAccountData(){return b.log("LocalIndexedDBStoreBackend: loading account data..."),da(()=>{var e=this.db.transaction(["accountData"],"readonly"),t=e.objectStore("accountData");return Ch(t,void 0,n=>n.value).then(n=>(b.log("LocalIndexedDBStoreBackend: loaded account data"),n))})}loadSyncData(){return b.log("LocalIndexedDBStoreBackend: loading sync data..."),da(()=>{var e=this.db.transaction(["sync"],"readonly"),t=e.objectStore("sync");return Ch(t,void 0,n=>n.value).then(n=>(b.log("LocalIndexedDBStoreBackend: loaded sync data"),n.length>1&&b.warn("loadSyncData: More than 1 sync row found."),n.length>0?n[0]:{}))})}getClientOptions(){return Promise.resolve().then(()=>{var e=this.db.transaction(["client_options"],"readonly"),t=e.objectStore("client_options");return Ch(t,void 0,n=>{var i;return(i=n.value)===null||i===void 0?void 0:i.options}).then(n=>n[0])})}storeClientOptions(e){var t=this;return w(function*(){var n=t.db.transaction(["client_options"],"readwrite"),i=n.objectStore("client_options");i.put({clobber:"-",options:e}),yield sa(n)})()}saveToDeviceBatches(e){var t=this;return w(function*(){var n=t.db.transaction(["to_device_queue"],"readwrite"),i=n.objectStore("to_device_queue");for(var o of e)i.add(o);yield sa(n)})()}getOldestToDeviceBatch(){var e=this;return w(function*(){var t=e.db.transaction(["to_device_queue"],"readonly"),n=t.objectStore("to_device_queue"),i=yield Sy(n.openCursor());if(!i)return null;var o=i.value;return{id:i.key,txnId:o.txnId,eventType:o.eventType,batch:o.batch}})()}removeToDeviceBatch(e){var t=this;return w(function*(){var n=t.db.transaction(["to_device_queue"],"readwrite"),i=n.objectStore("to_device_queue");i.delete(e),yield sa(n)})()}destroy(){var e=this;return w(function*(){var t;(t=e.db)===null||t===void 0||t.close()})()}}class rJ{constructor(e,t){this.workerFactory=e,this.dbName=t,v(this,"worker",void 0),v(this,"nextSeq",0),v(this,"inFlight",{}),v(this,"startPromise",void 0),v(this,"onWorkerMessage",n=>{var i=n.data;if(i.command=="closed"){var o;(o=this.onClose)===null||o===void 0||o.call(this)}else if(i.command=="cmd_success"||i.command=="cmd_fail"){if(i.seq===void 0){b.error("Got reply from worker with no seq");return}var s=this.inFlight[i.seq];if(s===void 0){b.error("Got reply for unknown seq "+i.seq);return}if(delete this.inFlight[i.seq],i.command=="cmd_success")s.resolve(i.result);else{var a=new Error(i.error.message);a.name=i.error.name,s.reject(a)}}else b.warn("Unrecognised message from worker: ",i)})}connect(e){return this.onClose=e,this.ensureStarted().then(()=>this.doCmd("connect"))}clearDatabase(){return this.ensureStarted().then(()=>this.doCmd("clearDatabase"))}isNewlyCreated(){return this.doCmd("isNewlyCreated")}getSavedSync(){return this.doCmd("getSavedSync")}getNextBatchToken(){return this.doCmd("getNextBatchToken")}setSyncData(e){return this.doCmd("setSyncData",[e])}syncToDatabase(e){return this.doCmd("syncToDatabase",[e])}getOutOfBandMembers(e){return this.doCmd("getOutOfBandMembers",[e])}setOutOfBandMembers(e,t){return this.doCmd("setOutOfBandMembers",[e,t])}clearOutOfBandMembers(e){return this.doCmd("clearOutOfBandMembers",[e])}getClientOptions(){return this.doCmd("getClientOptions")}storeClientOptions(e){return this.doCmd("storeClientOptions",[e])}getUserPresenceEvents(){return this.doCmd("getUserPresenceEvents")}saveToDeviceBatches(e){var t=this;return w(function*(){return t.doCmd("saveToDeviceBatches",[e])})()}getOldestToDeviceBatch(){var e=this;return w(function*(){return e.doCmd("getOldestToDeviceBatch")})()}removeToDeviceBatch(e){var t=this;return w(function*(){return t.doCmd("removeToDeviceBatch",[e])})()}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then(()=>{b.log("IndexedDB worker is ready")})),this.startPromise}doCmd(e,t){return Promise.resolve().then(()=>{var n,i=this.nextSeq++,o=Hs();return this.inFlight[i]=o,(n=this.worker)===null||n===void 0||n.postMessage({command:e,seq:i,args:t}),o.promise})}destroy(){var e=this;return w(function*(){var t;(t=e.worker)===null||t===void 0||t.terminate()})()}}var nJ=1e3*60*5;class iJ extends Mm{static exists(e,t){return SI.exists(e,t)}constructor(e){if(super(e),v(this,"backend",void 0),v(this,"startedUp",!1),v(this,"syncTs",0),v(this,"userModifiedMap",{}),v(this,"emitter",new Tt),v(this,"onClose",()=>{this.emitter.emit("closed")}),v(this,"getSavedSync",this.degradable(()=>this.backend.getSavedSync(),"getSavedSync")),v(this,"isNewlyCreated",this.degradable(()=>this.backend.isNewlyCreated(),"isNewlyCreated")),v(this,"getSavedSyncToken",this.degradable(()=>this.backend.getNextBatchToken(),"getSavedSyncToken")),v(this,"deleteAllData",this.degradable(()=>(super.deleteAllData(),this.backend.clearDatabase().then(()=>{b.log("Deleted indexeddb data.")},t=>{throw b.error("Failed to delete indexeddb data: ".concat(t)),t})),null)),v(this,"reallySave",this.degradable(()=>{this.syncTs=Date.now();var t=[];for(var n of this.getUsers())this.userModifiedMap[n.userId]!==n.getLastModifiedTime()&&n.events.presence&&(t.push([n.userId,n.events.presence.event]),this.userModifiedMap[n.userId]=n.getLastModifiedTime());return this.backend.syncToDatabase(t)},null)),v(this,"setSyncData",this.degradable(t=>this.backend.setSyncData(t),"setSyncData")),v(this,"getOutOfBandMembers",this.degradable(t=>this.backend.getOutOfBandMembers(t),"getOutOfBandMembers")),v(this,"setOutOfBandMembers",this.degradable((t,n)=>(super.setOutOfBandMembers(t,n),this.backend.setOutOfBandMembers(t,n)),"setOutOfBandMembers")),v(this,"clearOutOfBandMembers",this.degradable(t=>(super.clearOutOfBandMembers(t),this.backend.clearOutOfBandMembers(t)),"clearOutOfBandMembers")),v(this,"getClientOptions",this.degradable(()=>this.backend.getClientOptions(),"getClientOptions")),v(this,"storeClientOptions",this.degradable(t=>(super.storeClientOptions(t),this.backend.storeClientOptions(t)),"storeClientOptions")),!e.indexedDB)throw new Error("Missing required option: indexedDB");e.workerFactory?this.backend=new rJ(e.workerFactory,e.dbName):this.backend=new SI(e.indexedDB,e.dbName)}on(e,t){this.emitter.on(e,t)}startup(){return this.startedUp?(b.log("IndexedDBStore.startup: already started"),Promise.resolve()):(b.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect(this.onClose).then(()=>(b.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents())).then(e=>{b.log("IndexedDBStore.startup: processing presence events"),e.forEach(t=>{var[n,i]=t;if(!this.createUser)throw new Error("`IndexedDBStore.startup` must be called after assigning it to the client, not before!");var o=this.createUser(n);i&&o.setPresenceEvent(new pr(i)),this.userModifiedMap[o.userId]=o.getLastModifiedTime(),this.storeUser(o)}),this.startedUp=!0}))}destroy(){return this.backend.destroy()}wantsSave(){var e=Date.now();return e-this.syncTs>nJ}save(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){var n=this,i=t?super[t]:null;return w(function*(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];try{return yield e.call(n,...s)}catch(l){b.error("IndexedDBStore failure, degrading to MemoryStore",l),n.emitter.emit("degraded",l);try{b.log("IndexedDBStore trying to delete degraded data"),yield n.backend.clearDatabase(),b.log("IndexedDBStore delete after degrading succeeded")}catch(c){b.warn("IndexedDBStore delete after degrading failed",c)}if(i)return i.call(n,...s)}})}getPendingEvents(e){var t=()=>super.getPendingEvents,n=this;return w(function*(){if(!n.localStorage)return t().call(n,e);var i=n.localStorage.getItem(by(e));if(i)try{return JSON.parse(i)}catch(o){b.error("Could not parse persisted pending events",o)}return[]})()}setPendingEvents(e,t){var n=()=>super.setPendingEvents,i=this;return w(function*(){if(!i.localStorage)return n().call(i,e,t);t.length>0?i.localStorage.setItem(by(e),JSON.stringify(t)):i.localStorage.removeItem(by(e))})()}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function by(r){return"mx_pending_events_".concat(r)}var oJ=function(r){return r.Email="email",r.Phone="msisdn",r}({}),sJ=new Bt("delegated_oidc_compatibility","org.matrix.msc3824.delegated_oidc_compatibility"),aJ=function(r){return r.Gitlab="gitlab",r.Github="github",r.Apple="apple",r.Google="google",r.Facebook="facebook",r.Twitter="twitter",r}({}),lJ=function(r){return r.LOGIN="login",r.REGISTER="register",r}({}),cJ=function(r){return r.Global="Global",r.SetItemError="setItem",r.GetItemError="getItem",r.RemoveItemError="removeItem",r.ClearError="clear",r.QuotaExceededError="QuotaExceededError",r}({});class uJ extends Tt{}new uJ;var EL=()=>new Sm;function wL(r){EL=r}function TL(r){var e,t,n;return r.store=(e=r.store)!==null&&e!==void 0?e:new Mm({localStorage:globalThis.localStorage}),r.scheduler=(t=r.scheduler)!==null&&t!==void 0?t:new Rc,r.cryptoStore=(n=r.cryptoStore)!==null&&n!==void 0?n:EL(),r}function RL(r){return new qc(TL(r))}function dJ(r,e,t,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;return new oL(r,e,t,TL(n),i)}const fJ=Object.freeze(Object.defineProperty({__proto__:null,AuthType:R_,AutoDiscovery:Ke,AutoDiscoveryAction:Nn,AutoDiscoveryError:ni,Beacon:ZD,BeaconEvent:kt,CRYPTO_ENABLED:R7,CallEvent:Ye,CallFeedEvent:Li,Category:po,ClientEvent:be,ClientPrefix:Pt,ClientStoppedError:N8,ConditionKind:rr,ConditionOperator:m8,ConnectionError:Rf,ContentHelpers:zH,Crypto:K8,CryptoEvent:et,DELEGATED_OIDC_COMPATIBILITY:sJ,DEVICE_CODE_SCOPE:zY,DMMemberCountCondition:g8,Device:_N,DeviceVerification:To,Direction:Ge,DuplicateStrategy:td,EVENT_VISIBILITY_CHANGE_TYPE:Ta,EventEmitterEvents:AD,EventStatus:je,EventTimeline:we,EventTimelineSet:Bl,EventType:V,FILTER_RELATED_BY_REL_TYPES:oc,FILTER_RELATED_BY_SENDERS:ic,FeatureSupport:Vr,Filter:gn,GET_LOGIN_TOKEN_CAPABILITY:k7,GroupCall:Lw,GroupCallEvent:yt,GroupCallIntent:wN,GroupCallState:Dt,GroupCallStatsReportEvent:Du,GroupCallType:km,GuestAccess:gv,HTTPError:_c,HistoryVisibility:Jw,HttpApiEvent:Ub,IdentityPrefix:ho,IdentityProviderBrand:aJ,IndexedDBCryptoStore:_e,IndexedDBStore:iJ,InteractiveAuth:ZY,InvalidCryptoStoreError:Vw,InvalidCryptoStoreState:Kw,JoinRule:WN,KNOWN_SAFE_ROOM_VERSION:fN,KeySignatureUploadError:Nu,KnownMembership:Be,LOCAL_NOTIFICATION_SETTINGS_PREFIX:UD,LocalStorageCryptoStore:xm,LocalStorageErrors:cJ,LocationAssetType:yc,MAIN_ROOM_TIMELINE:Tf,MSC3912_RELATION_BASED_REDACTIONS_PROP:Mb,M_ASSET:Ef,M_BEACON:Ib,M_BEACON_INFO:xw,M_HTML:uH,M_LOCATION:wf,M_MESSAGE:cH,M_POLL_END:sv,M_POLL_KIND_DISCLOSED:xH,M_POLL_KIND_UNDISCLOSED:OH,M_POLL_RESPONSE:Fd,M_POLL_START:PH,M_TEXT:Cw,M_TIMESTAMP:Gs,M_TOPIC:Pw,MatrixClient:qc,MatrixError:hr,MatrixEvent:pr,MatrixEventEvent:ot,MatrixHttpApi:cN,MatrixScheduler:Rc,MediaHandlerEvent:va,MediaPrefix:Zl,MemoryCryptoStore:Sm,MemoryStore:Mm,Method:Z,MsgType:xi,NoAuthFlowFoundError:SL,NotificationCountType:it,OidcError:Wr,OidcTokenRefresher:JY,PUSHER_DEVICE_ID:MH,PUSHER_ENABLED:Ab,PendingEventOrdering:Cc,Poll:rN,PollEvent:cs,Preset:Yw,PushRuleActionName:ks,PushRuleKind:Er,REFERENCE_RELATION:yD,ReceiptType:Xr,RelationType:Nt,Relations:Ow,RelationsEvent:rp,RestrictedAllowType:o7,Room:Tm,RoomCreateTypeField:av,RoomEvent:pe,RoomMember:cv,RoomMemberEvent:Ar,RoomNameType:Ni,RoomState:Gd,RoomStateEvent:Me,RoomSummary:KD,RoomType:Ql,RoomVersionStability:uN,RoomWidgetClient:oL,RoomWidgetClientEvent:up,RuleId:br,SERVICE_TYPES:Xb,SSOAction:lJ,SearchOrderBy:qN,SearchResult:Pm,SecretStorage:p9,ServerCapabilities:dN,SetPresence:hN,SlidingSyncEvent:p_,StatsReport:Ro,SyncAccumulator:sL,SyncState:ct,THREAD_RELATION_TYPE:vt,Thread:Et,ThreadEvent:Qr,ThreadFilterType:di,ThreepidMedium:oJ,TimelineIndex:T_,TimelineWindow:QY,ToDeviceMessageId:tn,TweakName:Uw,TypedEventEmitter:Tt,UNSIGNED_MEMBERSHIP_FIELD:jD,UNSIGNED_THREAD_ID_FIELD:lv,UNSTABLE_ELEMENT_FUNCTIONAL_USERS:LD,UNSTABLE_MSC2666_MUTUAL_ROOMS:XN,UNSTABLE_MSC2666_QUERY_MUTUAL_ROOMS:QN,UNSTABLE_MSC2666_SHARED_ROOMS:JN,UNSTABLE_MSC2716_MARKER:ND,UNSTABLE_MSC3088_ENABLED:Ob,UNSTABLE_MSC3088_PURPOSE:xb,UNSTABLE_MSC3089_BRANCH:So,UNSTABLE_MSC3089_LEAF:DD,UNSTABLE_MSC3089_TREE_SUBTYPE:Pb,UNSTABLE_MSC3852_LAST_SEEN_UA:C7,UNSTABLE_MSC4133_EXTENDED_PROFILES:ZN,UNSTABLE_MSC4140_DELAYED_EVENTS:Wi,UpdateDelayedEventAction:sp,User:ko,UserEvent:ar,Visibility:i7,anySignal:sN,calculateRetryBackoff:lN,completeAuthorizationCodeGrant:HY,createClient:RL,createNewMatrixCall:Kd,createRoomWidgetClient:dJ,decodeBase64:Dr,decodeIdToken:pL,determineFeatureSupport:lp,discoverAndValidateOIDCIssuerWellKnown:yL,encodeBase64:Zr,encodeUnpaddedBase64:Rm,encodeUnpaddedBase64Url:Cm,fixNotificationCountOnDecryption:eL,generateAuthorizationParams:$Y,generateAuthorizationUrl:WY,generateOidcAuthorizationUrl:qY,generateScope:Bm,getBeaconInfoIdentifier:uv,getHttpUriForMxc:bm,inMainTimelineForReceipt:qd,isDmMemberCountCondition:y8,isEventTypeSame:dH,isPollEvent:nN,isTimestampInDuration:Nb,isValidatedIssuerMetadata:hL,parseErrorResponse:Dw,registerOidcClient:YY,retryNetworkOperation:aN,safeGetRetryAfterMs:Aw,setCryptoStoreFactory:wL,threadFilterTypeToFilter:tL,threadIdForReceipt:kc,timeoutSignal:wm,validateBearerTokenResponse:gL,validateIdToken:vL,validateOIDCIssuerWellKnown:i0,validateStoredUserState:mL},Symbol.toStringTag,{value:"Module"}));if(globalThis.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");globalThis.__js_sdk_entrypoint=!0;var C_;try{C_=globalThis.indexedDB}catch{}C_&&wL(()=>new _e(C_,"matrix-js-sdk:crypto"));globalThis.matrixcs=fJ;class hJ{constructor(e){this.namespace=e}k(e){return`${this.namespace}:${e}`}get(e){return localStorage.getItem(this.k(e))}set(e,t){localStorage.setItem(this.k(e),t)}remove(e){localStorage.removeItem(this.k(e))}getJSON(e){const t=this.get(e);if(t===null)return null;try{return JSON.parse(t)}catch{return null}}setJSON(e,t){this.set(e,JSON.stringify(t))}}const _y=new hJ("zoon");class pJ{constructor(){Ne(this,"client",null);Ne(this,"listeners",new Set)}safeGet(){return this.client}get(){if(!this.client)throw new Error("MatrixClientPeg: not logged in");return this.client}set(e){return this.client&&this.client.stopClient(),this.client=RL({baseUrl:e.homeserverUrl,accessToken:e.accessToken,userId:e.userId,deviceId:e.deviceId,store:new Mm({localStorage:globalThis.localStorage})}),_y.setJSON("session",e),this.emit(),this.client}reset(){if(this.client)try{this.client.stopClient()}catch{}this.client=null,_y.remove("session"),this.emit()}injectClientForTest(e){if(this.client)try{this.client.stopClient()}catch{}this.client=e,this.emit()}restoreFromStorage(){const e=_y.getJSON("session");return e?(this.set(e),e):null}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(){for(const e of this.listeners)e()}}const de=new pJ,bI=r=>typeof r=="boolean"?`${r}`:r===0?"0":r,_I=U1,o0=(r,e)=>t=>{var n;if((e==null?void 0:e.variants)==null)return _I(r,t==null?void 0:t.class,t==null?void 0:t.className);const{variants:i,defaultVariants:o}=e,s=Object.keys(i).map(c=>{const u=t==null?void 0:t[c],d=o==null?void 0:o[c];if(u===null)return null;const f=bI(u)||bI(d);return i[c][f]}),a=t&&Object.entries(t).reduce((c,u)=>{let[d,f]=u;return f===void 0||(c[d]=f),c},{}),l=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((c,u)=>{let{class:d,className:f,...p}=u;return Object.entries(p).every(h=>{let[m,E]=h;return Array.isArray(E)?E.includes({...o,...a}[m]):{...o,...a}[m]===E})?[...c,d,f]:c},[]);return _I(r,s,l,t==null?void 0:t.class,t==null?void 0:t.className)};function vJ({className:r,...e}){return g.jsx("div",{"data-slot":"empty",className:Le("flex w-full min-w-0 flex-1 flex-col items-center justify-center gap-4 rounded-xl border-dashed p-6 text-center text-balance",r),...e})}function mJ({className:r,...e}){return g.jsx("div",{"data-slot":"empty-header",className:Le("flex max-w-sm flex-col items-center gap-2",r),...e})}const gJ=o0("mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",{variants:{variant:{default:"bg-transparent",icon:"flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-4"}},defaultVariants:{variant:"default"}});function yJ({className:r,variant:e="default",...t}){return g.jsx("div",{"data-slot":"empty-icon","data-variant":e,className:Le(gJ({variant:e,className:r})),...t})}function SJ({className:r,...e}){return g.jsx("div",{"data-slot":"empty-description",className:Le("text-sm/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",r),...e})}function bJ({className:r,...e}){return g.jsx(Hv,{role:"status","aria-label":"Loading",className:Le("size-4 animate-spin",r),...e})}async function _J(r){const e=await fetch(`${r}/_matrix/client/v3/login`);if(!e.ok)throw await s0(e);return(await e.json()).flows}async function EJ(r,e,t){const n=await fetch(`${r}/_matrix/client/v3/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"m.login.password",identifier:{type:"m.id.user",user:e},password:t,initial_device_display_name:"Zoon Web"})});if(!n.ok)throw await s0(n);return CL(r,await n.json())}async function wJ(r,e){const t=await fetch(`${r}/_matrix/client/v3/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"m.login.token",token:e,initial_device_display_name:"Zoon Web"})});if(!t.ok)throw await s0(t);return CL(r,await t.json())}function EI(r,e,t){const n=t?`/_matrix/client/v3/login/sso/redirect/${encodeURIComponent(t)}`:"/_matrix/client/v3/login/sso/redirect";return`${r}${n}?redirectUrl=${encodeURIComponent(e)}`}function CL(r,e){const t=e;return{homeserverUrl:r,accessToken:t.access_token,userId:t.user_id,deviceId:t.device_id}}async function s0(r){try{const e=await r.json();return new Error(e.error??e.errcode??`HTTP ${r.status}`)}catch{return new Error(`HTTP ${r.status}`)}}function TJ({homeserverUrl:r}){const[e]=nM(),t=e.get("loginToken"),[n,i]=_.useState(null),[o,s]=_.useState(!1);return _.useEffect(()=>{t&&wJ(r,t).then(a=>{de.set(a),s(!0)}).catch(a=>i(a instanceof Error?a.message:String(a)))},[r,t]),t?n?g.jsx("div",{role:"alert",children:n}):o?g.jsx(Vp,{to:"/",replace:!0}):g.jsx(vJ,{className:"min-h-screen",role:"status",children:g.jsxs(mJ,{children:[g.jsx(yJ,{children:g.jsx(bJ,{"aria-label":"Completing sign-in"})}),g.jsx(SJ,{children:"Completing sign-in…"})]})}):g.jsx(Vp,{to:"/login",replace:!0})}const RJ=o0("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground [a]:hover:bg-primary/80",outline:"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",ghost:"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",destructive:"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",xs:"h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",lg:"h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",icon:"size-8","icon-xs":"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg","icon-lg":"size-9"}},defaultVariants:{variant:"default",size:"default"}}),At=_.forwardRef(function({className:e,variant:t="default",size:n="default",asChild:i=!1,...o},s){const a=i?zK:"button";return g.jsx(a,{ref:s,"data-slot":"button","data-variant":t,"data-size":n,className:Le(RJ({variant:t,size:n,className:e})),...o})});function k_({className:r,size:e="default",...t}){return g.jsx("div",{"data-slot":"card","data-size":e,className:Le("group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",r),...t})}function I_({className:r,...e}){return g.jsx("div",{"data-slot":"card-header",className:Le("group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",r),...e})}function x_({className:r,...e}){return g.jsx("div",{"data-slot":"card-title",className:Le("font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",r),...e})}function wI({className:r,...e}){return g.jsx("div",{"data-slot":"card-description",className:Le("text-sm text-muted-foreground",r),...e})}function hp({className:r,...e}){return g.jsx("div",{"data-slot":"card-content",className:Le("px-4 group-data-[size=sm]/card:px-3",r),...e})}function CJ({className:r,...e}){return g.jsx("div",{"data-slot":"card-footer",className:Le("flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",r),...e})}function Qd({className:r,type:e,...t}){return g.jsx("input",{type:e,"data-slot":"input",className:Le("h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",r),...t})}function Zd({className:r,...e}){return g.jsx(D$,{"data-slot":"label",className:Le("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",r),...e})}function kJ({className:r,orientation:e="horizontal",decorative:t=!0,...n}){return g.jsx(hW,{"data-slot":"separator",decorative:t,orientation:e,className:Le("shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",r),...n})}function IJ({homeserverUrl:r,defaultIdpLabel:e}){const[t,n]=_.useState(null),[i,o]=_.useState(null),[s,a]=_.useState(!1),l=_.useRef(!1);_.useEffect(()=>{_J(r).then(n).catch(E=>o(String(E.message??E)))},[r]);const c=!0,u=!!t&&!t.some(E=>E.type==="m.login.password")&&(()=>{const E=t.find(S=>S.type==="m.login.sso");return((E==null?void 0:E.identity_providers)??(E?[{id:""}]:[])).length===1})();if(_.useEffect(()=>{var R;if(!t||l.current||!c||!u)return;const E=t.find(k=>k.type==="m.login.sso"),y=(E==null?void 0:E.identity_providers)??(E?[{id:""}]:[]);l.current=!0;const S=`${window.location.origin}/auth/callback`;window.location.assign(EI(r,S,((R=y[0])==null?void 0:R.id)||void 0))},[t,r,c,u]),!t)return g.jsx("div",{role:"status",children:"Loading login options…"});if(u)return g.jsx("div",{role:"status",children:"Redirecting to sign in…"});const d=t.find(E=>E.type==="m.login.password"),f=t.find(E=>E.type==="m.login.sso"),p=async E=>{E.preventDefault(),o(null),a(!0);const y=new FormData(E.currentTarget);try{const S=await EJ(r,String(y.get("username")??""),String(y.get("password")??""));de.set(S)}catch(S){o(S instanceof Error?S.message:String(S))}finally{a(!1)}},h=E=>{const y=`${window.location.origin}/auth/callback`;window.location.assign(EI(r,y,E))},m=(f==null?void 0:f.identity_providers)??(f?[{id:"",name:e??"SSO"}]:[]);return g.jsx("div",{className:"flex min-h-screen items-center justify-center p-6",children:g.jsxs(k_,{className:"w-full max-w-sm",children:[g.jsx(I_,{children:g.jsx(x_,{children:"Sign in"})}),g.jsxs(hp,{className:"flex flex-col gap-4",children:[i&&g.jsx("div",{role:"alert",className:"text-destructive text-sm",children:i}),d&&g.jsxs("form",{onSubmit:p,className:"flex flex-col gap-3",children:[g.jsxs("div",{className:"flex flex-col gap-1.5",children:[g.jsx(Zd,{htmlFor:"login-username",children:"Username"}),g.jsx(Qd,{id:"login-username",name:"username",autoComplete:"username",required:!0})]}),g.jsxs("div",{className:"flex flex-col gap-1.5",children:[g.jsx(Zd,{htmlFor:"login-password",children:"Password"}),g.jsx(Qd,{id:"login-password",name:"password",type:"password",autoComplete:"current-password",required:!0})]}),g.jsx(At,{type:"submit",disabled:s,children:"Sign in"})]}),d&&f&&g.jsx(kJ,{}),m.map(E=>g.jsxs(At,{type:"button",variant:"outline",onClick:()=>h(E.id||void 0),children:["Sign in with ",E.name]},E.id||"default-sso"))]})]})})}function xJ(r,e){const[t,n]=_.useState([]),[i,o]=_.useState(!1),s=_.useCallback(async()=>{const a=de.safeGet();if(!(!a||!r)){o(!0);try{const c=(await a.getRoomHierarchy(r)??{rooms:[]}).rooms.filter(u=>u.room_id!==r&&u.room_type!=="m.space").filter(u=>!a.getRoom(u.room_id)).map(u=>({roomId:u.room_id,name:u.name,topic:u.topic,memberCount:u.num_joined_members??0}));n(c)}finally{o(!1)}}},[r]);return _.useEffect(()=>{s()},[e,s]),{rooms:t,loading:i,refresh:s}}function OJ(){const{spaceId:r}=HF();return r?g.jsx(PJ,{spaceId:r}):g.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"No space selected."})}function PJ({spaceId:r}){var o,s;const{rooms:e,loading:t,refresh:n}=xJ(r,!0),i=(s=(o=de.safeGet())==null?void 0:o.getRoom(r))==null?void 0:s.name;return g.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[g.jsxs("header",{className:"border-b border-border px-6 py-4",children:[g.jsx("h1",{className:"font-heading text-lg font-medium",children:"Browse rooms"}),i&&g.jsx("p",{className:"text-sm text-muted-foreground",children:i})]}),g.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-6",children:t&&e.length===0?g.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading rooms…"}):e.length===0?g.jsx("p",{className:"text-sm text-muted-foreground",children:"No rooms to join — you're already in all of them."}):g.jsx("ul",{className:"flex flex-col gap-2",children:e.map(a=>g.jsx(MJ,{room:a,onJoined:n},a.roomId))})})]})}function MJ({room:r,onJoined:e}){const[t,n]=_.useState(!1),i=Vs(),o=async()=>{const s=de.safeGet();if(s){n(!0);try{await s.joinRoom(r.roomId),e(),i(`/room/${r.roomId}`)}finally{n(!1)}}};return g.jsxs("li",{className:"flex items-center gap-3 rounded-lg border border-border p-3",children:[g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("p",{className:"truncate text-sm font-medium",children:r.name??r.roomId}),r.topic&&g.jsx("p",{className:"truncate text-xs text-muted-foreground",children:r.topic}),g.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.memberCount," member",r.memberCount!==1?"s":""]})]}),g.jsx(At,{size:"sm",variant:"outline",disabled:t,onClick:()=>void o(),children:"Join"})]})}const Ey=768;function AJ(){const[r,e]=_.useState(void 0);return _.useEffect(()=>{const t=window.matchMedia(`(max-width: ${Ey-1}px)`),n=()=>{e(window.innerWidth<Ey)};return t.addEventListener("change",n),e(window.innerWidth<Ey),()=>t.removeEventListener("change",n)},[]),!!r}function DJ({...r}){return g.jsx(HE,{"data-slot":"sheet",...r})}function NJ({...r}){return g.jsx(zE,{"data-slot":"sheet-portal",...r})}function LJ({className:r,...e}){return g.jsx(YE,{"data-slot":"sheet-overlay",className:Le("fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",r),...e})}function UJ({className:r,children:e,side:t="right",showCloseButton:n=!0,...i}){return g.jsxs(NJ,{children:[g.jsx(LJ,{}),g.jsxs(JE,{"data-slot":"sheet-content","data-side":t,className:Le("fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10",r),...i,children:[e,n&&g.jsx(XE,{"data-slot":"sheet-close",asChild:!0,children:g.jsxs(At,{variant:"ghost",className:"absolute top-3 right-3",size:"icon-sm",children:[g.jsx(BE,{}),g.jsx("span",{className:"sr-only",children:"Close"})]})})]})]})}function jJ({className:r,...e}){return g.jsx("div",{"data-slot":"sheet-header",className:Le("flex flex-col gap-0.5 p-4",r),...e})}function FJ({className:r,...e}){return g.jsx(FM,{"data-slot":"sheet-title",className:Le("font-heading text-base font-medium text-foreground",r),...e})}function BJ({className:r,...e}){return g.jsx(BM,{"data-slot":"sheet-description",className:Le("text-sm text-muted-foreground",r),...e})}const KJ="sidebar_state",VJ=60*60*24*7,$J="16rem",WJ="18rem",qJ="3rem",GJ="b",kL=_.createContext(null);function a0(){const r=_.useContext(kL);if(!r)throw new Error("useSidebar must be used within a SidebarProvider.");return r}function HJ({defaultOpen:r=!0,open:e,onOpenChange:t,className:n,style:i,children:o,...s}){const a=AJ(),[l,c]=_.useState(!1),[u,d]=_.useState(r),f=e??u,p=_.useCallback(y=>{const S=typeof y=="function"?y(f):y;t?t(S):d(S),document.cookie=`${KJ}=${S}; path=/; max-age=${VJ}`},[t,f]),h=_.useCallback(()=>a?c(y=>!y):p(y=>!y),[a,p,c]);_.useEffect(()=>{const y=S=>{S.key===GJ&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),h())};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[h]);const m=f?"expanded":"collapsed",E=_.useMemo(()=>({state:m,open:f,setOpen:p,isMobile:a,openMobile:l,setOpenMobile:c,toggleSidebar:h}),[m,f,p,a,l,c,h]);return g.jsx(kL.Provider,{value:E,children:g.jsx("div",{"data-slot":"sidebar-wrapper",style:{"--sidebar-width":$J,"--sidebar-width-icon":qJ,...i},className:Le("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",n),...s,children:o})})}function zJ({side:r="left",variant:e="sidebar",collapsible:t="offcanvas",className:n,children:i,dir:o,...s}){const{isMobile:a,state:l,openMobile:c,setOpenMobile:u}=a0();return t==="none"?g.jsx("div",{"data-slot":"sidebar",className:Le("flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",n),...s,children:i}):a?g.jsx(DJ,{open:c,onOpenChange:u,...s,children:g.jsxs(UJ,{dir:o,"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",className:"w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":WJ},side:r,children:[g.jsxs(jJ,{className:"sr-only",children:[g.jsx(FJ,{children:"Sidebar"}),g.jsx(BJ,{children:"Displays the mobile sidebar."})]}),g.jsx("div",{className:"flex h-full w-full flex-col",children:i})]})}):g.jsxs("div",{className:"group peer hidden text-sidebar-foreground md:block","data-state":l,"data-collapsible":l==="collapsed"?t:"","data-variant":e,"data-side":r,"data-slot":"sidebar",children:[g.jsx("div",{"data-slot":"sidebar-gap",className:Le("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",e==="floating"||e==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)")}),g.jsx("div",{"data-slot":"sidebar-container","data-side":r,className:Le("fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex",e==="floating"||e==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...s,children:g.jsx("div",{"data-sidebar":"sidebar","data-slot":"sidebar-inner",className:"flex size-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 group-data-[variant=floating]:ring-sidebar-border",children:i})})]})}function YJ({className:r,onClick:e,...t}){const{toggleSidebar:n}=a0();return g.jsxs(At,{"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon-sm",className:Le(r),onClick:i=>{e==null||e(i),n()},...t,children:[g.jsx(lM,{}),g.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})}function JJ({className:r,...e}){return g.jsx("main",{"data-slot":"sidebar-inset",className:Le("relative flex w-full flex-1 flex-col bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",r),...e})}function XJ({className:r,...e}){return g.jsx("div",{"data-slot":"sidebar-header","data-sidebar":"header",className:Le("flex flex-col gap-2 p-2",r),...e})}function QJ({className:r,...e}){return g.jsx("div",{"data-slot":"sidebar-content","data-sidebar":"content",className:Le("no-scrollbar flex min-h-0 flex-1 flex-col gap-0 overflow-auto group-data-[collapsible=icon]:overflow-hidden",r),...e})}function ZJ(){const{isMobile:r,setOpenMobile:e}=a0();return g.jsx("div",{className:"flex h-full items-center justify-center p-6 sm:p-10",children:g.jsxs("div",{className:"flex max-w-sm flex-col items-center text-center",children:[g.jsx("div",{className:"mb-5 flex h-14 w-14 items-center justify-center rounded-2xl bg-accent text-accent-foreground",children:g.jsx(aM,{className:"h-7 w-7","aria-hidden":!0})}),g.jsx("h2",{className:"text-xl font-semibold tracking-tight text-foreground",children:"Pick a room to get started"}),g.jsx("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:r?"Open the room list to choose a conversation, or start a new one.":"Choose a room from the sidebar to view its conversation, or start a new one."}),r?g.jsxs("button",{type:"button",onClick:()=>e(!0),className:"mt-6 inline-flex items-center gap-2 rounded-md border border-border bg-background px-3 py-2 text-sm font-medium shadow-sm hover:bg-muted",children:[g.jsx(lM,{className:"h-4 w-4","aria-hidden":!0}),"Open room list"]}):null]})})}function Hi(r){return r.replace(/&/g,"&amp;").replace(/'/g,"&apos;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function eX(r){var e,t,n,i,o,s,a;const l=(e=r.meta)===null||e===void 0?void 0:e.title,c=(t=r.meta)===null||t===void 0?void 0:t.creator,u=(n=r.meta)===null||n===void 0?void 0:n.source,d=(o=(i=r.meta)===null||i===void 0?void 0:i.license)===null||o===void 0?void 0:o.url,f=tX(r);return!l&&!c&&!u&&!d&&!f?"":'<metadata xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/"><rdf:RDF><rdf:Description>'+(l?`<dc:title>${Hi(l)}</dc:title>`:"")+(c?`<dc:creator>${Hi(c)}</dc:creator>`:"")+(u?`<dc:source xsi:type="dcterms:URI">${Hi((a=(s=r.meta)===null||s===void 0?void 0:s.source)!==null&&a!==void 0?a:"")}</dc:source>`:"")+(d?`<dcterms:license xsi:type="dcterms:URI">${Hi(d)}</dcterms:license>`:"")+(f?`<dc:rights>${Hi(f)}</dc:rights>`:"")+"</rdf:Description></rdf:RDF></metadata>"}function tX(r){var e,t,n,i,o,s,a,l,c,u,d,f,p,h,m;let E=!((e=r.meta)===null||e===void 0)&&e.title?`„${(t=r.meta)===null||t===void 0?void 0:t.title}”`:"Design",y=`„${(i=(n=r.meta)===null||n===void 0?void 0:n.creator)!==null&&i!==void 0?i:"Unknown"}”`;!((o=r.meta)===null||o===void 0)&&o.source&&(E+=` (${r.meta.source})`);let S="";return((a=(s=r.meta)===null||s===void 0?void 0:s.license)===null||a===void 0?void 0:a.name)!=="MIT"&&((l=r.meta)===null||l===void 0?void 0:l.creator)!=="DiceBear"&&(!((c=r.meta)===null||c===void 0)&&c.title)&&(S+="Remix of "),S+=`${E} by ${y}`,!((d=(u=r.meta)===null||u===void 0?void 0:u.license)===null||d===void 0)&&d.name&&(S+=`, licensed under „${(p=(f=r.meta)===null||f===void 0?void 0:f.license)===null||p===void 0?void 0:p.name}”`,!((m=(h=r.meta)===null||h===void 0?void 0:h.license)===null||m===void 0)&&m.url&&(S+=` (${r.meta.license.url})`)),S}const TI=-2147483648,rX=2147483647,nX=1024;function IL(r){return r^=r<<13,r^=r>>17,r^=r<<5,r}function iX(r){let e=0;for(let t=0;t<r.length;t++)e=(e<<5)-e+r.charCodeAt(t)|0,e=IL(e);return e}function _v(r=""){r=r.toString().slice(0,nX);let e=iX(r)||1;const t=()=>e=IL(e),n=(i,o)=>Math.floor((t()-TI)/(rX-TI)*(o+1-i)+i);return{seed:r,next:t,bool(i=50){return n(1,100)<=i},integer(i,o){return n(i,o)},pick(i,o){var s;return i.length===0?(t(),o):(s=i[n(0,i.length-1)])!==null&&s!==void 0?s:o},shuffle(i){const o=_v(t().toString()),s=[...i];for(let a=s.length-1;a>0;a--){const l=o.integer(0,a);[s[a],s[l]]=[s[l],s[a]]}return s},string(i,o="abcdefghijklmnopqrstuvwxyz1234567890"){const s=_v(t().toString());let a="";for(let l=0;l<i;l++)a+=o[s.integer(0,o.length-1)];return a}}}function Yc(r){let e=r.attributes.viewBox.split(" "),t=parseInt(e[0]),n=parseInt(e[1]),i=parseInt(e[2]),o=parseInt(e[3]);return{x:t,y:n,width:i,height:o}}function oX(r,e,t,n,i){let{width:o,height:s,x:a,y:l}=Yc(r);const c=`<rect fill="${Hi(e)}" width="${o}" height="${s}" x="${a}" y="${l}" />`;switch(n){case"solid":return c+r.body;case"gradientLinear":return`<rect fill="url(#backgroundLinear)" width="${o}" height="${s}" x="${a}" y="${l}" /><defs><linearGradient id="backgroundLinear" gradientTransform="rotate(${i} 0.5 0.5)"><stop stop-color="${Hi(e)}"/><stop offset="1" stop-color="${Hi(t)}"/></linearGradient></defs>`+r.body}}function sX(r,e){let{width:t,height:n,x:i,y:o}=Yc(r),s=e?(e-100)/100:0,a=(t/2+i)*s*-1,l=(n/2+o)*s*-1;return`<g transform="translate(${a} ${l}) scale(${e/100})">${r.body}</g>`}function aX(r,e,t){let n=Yc(r),i=(n.width+n.x*2)*((e??0)/100),o=(n.height+n.y*2)*((t??0)/100);return`<g transform="translate(${i} ${o})">${r.body}</g>`}function lX(r,e){let{width:t,height:n,x:i,y:o}=Yc(r);return`<g transform="rotate(${e}, ${t/2+i}, ${n/2+o})">${r.body}</g>`}function cX(r){let{width:e,x:t}=Yc(r);return`<g transform="scale(-1 1) translate(${e*-1-t*2} 0)">${r.body}</g>`}function uX(r,e){let{width:t,height:n,x:i,y:o}=Yc(r),s=e?t*e/100:0,a=e?n*e/100:0;return`<mask id="viewboxMask"><rect width="${t}" height="${n}" rx="${s}" ry="${a}" x="${i}" y="${o}" fill="#fff" /></mask><g mask="url(#viewboxMask)">${r.body}</g>`}function dX(r){const e={xmlns:"http://www.w3.org/2000/svg",...r.attributes};return Object.keys(e).map(t=>`${Hi(t)}="${Hi(e[t])}"`).join(" ")}function fX(r){const e=_v(Math.random().toString()),t={};return r.body.replace(/(id="|url\(#)([a-z0-9-_]+)([")])/gi,(n,i,o,s)=>(t[o]=t[o]||e.string(8),`${i}${t[o]}${s}`))}const hX={properties:{seed:{type:"string"},flip:{type:"boolean",default:!1},rotate:{type:"integer",minimum:0,maximum:360,default:0},scale:{type:"integer",minimum:0,maximum:200,default:100},radius:{type:"integer",minimum:0,maximum:50,default:0},size:{type:"integer",minimum:1},backgroundColor:{type:"array",items:{type:"string",pattern:"^(transparent|[a-fA-F0-9]{6})$"}},backgroundType:{type:"array",items:{type:"string",enum:["solid","gradientLinear"]},default:["solid"]},backgroundRotation:{type:"array",items:{type:"integer",minimum:-360,maximum:360},default:[0,360]},translateX:{type:"integer",minimum:-100,maximum:100,default:0},translateY:{type:"integer",minimum:-100,maximum:100,default:0},clip:{type:"boolean",default:!0},randomizeIds:{type:"boolean",default:!1}}};function RI(r){var e;let t={},n=(e=r.properties)!==null&&e!==void 0?e:{};return Object.keys(n).forEach(i=>{let o=n[i];typeof o=="object"&&o.default!==void 0&&(Array.isArray(o.default)?t[i]=[...o.default]:typeof o.default=="object"?t[i]={...o.default}:t[i]=o.default)}),t}function pX(r,e){var t;let n={...RI(hX),...RI((t=r.schema)!==null&&t!==void 0?t:{}),...e};return JSON.parse(JSON.stringify(n))}function CI(r){return r==="transparent"?r:`#${r}`}function vX(r,e,t){var n;let i=r.shuffle(e);i.length<=1||e.length==2&&t=="gradientLinear"?(i=e,r.next()):i=r.shuffle(e),i.length===0&&(i=["transparent"]);const o=i[0],s=(n=i[1])!==null&&n!==void 0?n:i[0];return{primary:CI(o),secondary:CI(s)}}function mX(r,e={}){var t,n,i,o,s;e=pX(r,e);const a=_v(e.seed),l=r.create({prng:a,options:e}),c=a.pick((t=e.backgroundType)!==null&&t!==void 0?t:[],"solid"),{primary:u,secondary:d}=vX(a,(n=e.backgroundColor)!==null&&n!==void 0?n:[],c),f=a.integer(!((i=e.backgroundRotation)===null||i===void 0)&&i.length?Math.min(...e.backgroundRotation):0,!((o=e.backgroundRotation)===null||o===void 0)&&o.length?Math.max(...e.backgroundRotation):0);e.size&&(l.attributes.width=e.size.toString(),l.attributes.height=e.size.toString()),e.scale!==void 0&&e.scale!==100&&(l.body=sX(l,e.scale)),e.flip&&(l.body=cX(l)),e.rotate&&(l.body=lX(l,e.rotate)),(e.translateX||e.translateY)&&(l.body=aX(l,e.translateX,e.translateY)),u!=="transparent"&&d!=="transparent"&&(l.body=oX(l,u,d,c,f)),(e.radius||e.clip)&&(l.body=uX(l,(s=e.radius)!==null&&s!==void 0?s:0)),e.randomizeIds&&(l.body=fX(l));const p=dX(l),h=eX(r),m=`<svg ${p}>${h}${l.body}</svg>`;return{toString:()=>m,toJson:()=>{var E;return{svg:m,extra:{primaryBackgroundColor:u,secondaryBackgroundColor:d,backgroundType:c,backgroundRotation:f,...(E=l.extra)===null||E===void 0?void 0:E.call(l)}}},toDataUri:()=>`data:image/svg+xml;utf8,${encodeURIComponent(m)}`}}const gX={g:(r,e)=>'<path d="M101.6 51.2a20 20 0 0 0-14.7-14.5q-3.9-1-8.5-1-10 0-17 4.7A30 30 0 0 0 50.9 54q-3.6 9-3.6 21.6 0 12.8 3.5 21.8 3.4 9 10.3 14a29 29 0 0 0 17.2 4.8q9 0 15-2.6 6-2.7 9-7.5t3-11.4l6.8.7H78.7v-28h64.5v20q0 20-8.4 34.1a56 56 0 0 1-23.2 21.6Q97 150.7 78 150.7q-21.3 0-37.3-9t-25-25.8q-9-16.5-9-39.7a87 87 0 0 1 5.4-32 67 67 0 0 1 38-38q12.9-5 27.6-5 12.9 0 24 3.7 11.1 3.6 19.7 10.4a50 50 0 0 1 20.2 36z" fill="white"/>',r:(r,e)=>'<path d="M17.6 148.7V3.2h62.8q16.2 0 28.3 6 12 5.8 18.9 16.9a50 50 0 0 1 6.7 26.6q0 15.6-7 26.3A43 43 0 0 1 108 95.2q-12.5 5.5-29 5.5H41.3V70H71q7 0 11.8-1.7a15 15 0 0 0 7.6-5.6 17 17 0 0 0 2.7-10q0-6.3-2.7-10.2a15 15 0 0 0-7.6-5.8q-4.9-2-11.8-2H57v114zm85.2-66.8 36.4 66.8h-43L60.9 81.9z" fill="white"/>',a:(r,e)=>'<path d="M42.6 148.7H0L48 3.2h54l48 145.5h-42.7L75.5 43.3h-1.1zm-8-57.4h80.1v29.5h-80z" fill="white"/>',d:(r,e)=>'<path d="M67 148.7H11V3.2h55.4q22.5 0 38.8 8.8a60 60 0 0 1 25.3 25q9 16.2 9 39 0 22.6-9 39a61 61 0 0 1-25 25 81 81 0 0 1-38.5 8.7m-16.5-33.5h15a44 44 0 0 0 18.5-3.5q7.6-3.5 11.6-12t4-23.8q0-15-4-23.7a24 24 0 0 0-12-12 47 47 0 0 0-19.2-3.5H50.5z" fill="white"/>',i:(r,e)=>'<path d="M94.8 3.2v145.5H55.3V3.2z" fill="white"/>',e:(r,e)=>'<path d="M22.2 148.7V3.2H127V35H61.7v25h59.9v32h-60v25h65.1v31.8z" fill="white"/>',n:(r,e)=>'<path d="M138 3.2v145.5h-33L52.5 72.3h-1v76.4H12.2V3.2h33.5l51.7 76.2h1.2V3.2z" fill="white"/>',t:(r,e)=>'<path d="M11.7 35V3.2h126.5V35H94.4v113.7h-39V35z" fill="white"/>'},yX={g:(r,e)=>'<path d="M101.6 51.1a20 20 0 0 0-14.7-14.5q-3.9-1-8.5-1.1-10 0-17 4.8A30 30 0 0 0 50.9 54q-3.6 9-3.6 21.6 0 12.8 3.5 21.8 3.4 9 10.3 14a29 29 0 0 0 17.2 4.8q9 0 15-2.6 6-2.7 9-7.5t3-11.4l6.8.7H78.7v-28h64.5v20q0 20-8.4 34.1a56 56 0 0 1-23.2 21.6Q97 150.6 78 150.6q-21.3 0-37.3-9t-25-25.8-9-39.7a87 87 0 0 1 5.4-32 67 67 0 0 1 38-38Q63 1 77.6 1q12.9 0 24 3.7 11.1 3.6 19.7 10.4a50 50 0 0 1 20.2 36z" fill="white"/>',r:(r,e)=>'<path d="M17.6 148.6V3h62.8q16.2 0 28.3 6 12 5.8 18.9 16.9a50 50 0 0 1 6.7 26.5q0 15.7-7 26.4A43 43 0 0 1 108 95q-12.5 5.5-29 5.5H41.3V69.9H71q7 0 11.8-1.7a15 15 0 0 0 7.6-5.6 17 17 0 0 0 2.7-10q0-6.3-2.7-10.2a15 15 0 0 0-7.6-5.8q-4.9-2-11.8-2H57v114zm85.2-66.8 36.4 66.8h-43L60.9 81.8z" fill="white"/>',a:(r,e)=>'<path d="M42.6 148.6H0L48 3h54l48 145.5h-42.7L75.5 43.2h-1.1zm-8-57.4h80.1v29.5h-80z" fill="white"/>',d:(r,e)=>'<path d="M67 148.6H11V3h55.4q22.5 0 38.8 8.7a60 60 0 0 1 25.3 25q9 16.4 9 39 0 22.8-9 39.1a61 61 0 0 1-25 25 81 81 0 0 1-38.5 8.7M50.5 115h15a44 44 0 0 0 18.5-3.4q7.6-3.6 11.6-12t4-23.8q0-15-4-23.7a24 24 0 0 0-12-12 47 47 0 0 0-19.2-3.5H50.5z" fill="white"/>',i:(r,e)=>'<path d="M94.8 3.1v145.5H55.3V3z" fill="white"/>',e:(r,e)=>'<path d="M22.2 148.6V3H127v32H61.7v25h59.9v31.8h-60v25h65.1v31.9z" fill="white"/>',n:(r,e)=>'<path d="M138 3.1v145.5h-33L52.5 72h-1v76.5H12.2V3h33.5l51.7 76.1h1.2v-76z" fill="white"/>',t:(r,e)=>'<path d="M11.7 35V3h126.5v32H94.4v113.7h-39V34.9z" fill="white"/>'},SX=Object.freeze(Object.defineProperty({__proto__:null,shape1:yX,shape2:gX},Symbol.toStringTag,{value:"Module"}));function kI({prng:r,group:e,width:t,height:n,values:i=[],rotation:o,offsetX:s,offsetY:a}){const l=SX,c=r.pick(i),u=r.integer(Math.min(...o),Math.max(...o)),d=r.integer(Math.min(...s),Math.max(...s)),f=r.integer(Math.min(...a),Math.max(...a));if(c&&l[e][c])return{name:c,value(p,h){var m,E,y;let S=l[e][c](p,h);return(this.rotation||this.offsetX||this.offsetY)&&(S=`<g transform="translate(${(m=this.offsetX)!==null&&m!==void 0?m:0}, ${(E=this.offsetY)!==null&&E!==void 0?E:0}) rotate(${(y=this.rotation)!==null&&y!==void 0?y:0} ${t/2} ${n/2})">${S}</g>`),S},rotation:u,offsetX:d,offsetY:f}}function bX({prng:r,options:e}){var t,n,i,o,s,a;const l=kI({prng:r,group:"shape2",values:e.shape2,width:150,height:150,rotation:!((t=e.shape2Rotation)===null||t===void 0)&&t.length?e.shape2Rotation:[0],offsetX:!((n=e.shape2OffsetX)===null||n===void 0)&&n.length?e.shape2OffsetX:[0],offsetY:!((i=e.shape2OffsetY)===null||i===void 0)&&i.length?e.shape2OffsetY:[0]}),c=kI({prng:r,group:"shape1",values:e.shape1,width:150,height:150,rotation:!((o=e.shape1Rotation)===null||o===void 0)&&o.length?e.shape1Rotation:[0],offsetX:!((s=e.shape1OffsetX)===null||s===void 0)&&s.length?e.shape1OffsetX:[0],offsetY:!((a=e.shape1OffsetY)===null||a===void 0)&&a.length?e.shape1OffsetY:[0]});return{shape2:l,shape1:c}}function _X({prng:r,options:e}){return{}}const EX={$schema:"http://json-schema.org/draft-07/schema#",properties:{backgroundColor:{type:"array",items:{type:"string",pattern:"^(transparent|[a-fA-F0-9]{6})$"},default:["eb4747","eb6247","eb7e47","eb9947","ebb447","ebd047","ebeb47","d0eb47","b4eb47","99eb47","7eeb47","62eb47","47eb47","47eb62","47eb7e","47eb99","47ebb4","47ebd0","47ebeb","47d0eb","47b4eb","4799eb","477eeb","4762eb","4747eb","6247eb","7e47eb","9947eb","b447eb","d047eb","eb47eb","eb47d0","eb4799","eb477e","eb4762"]},shape1:{type:"array",items:{type:"string",enum:["g","r","a","d","i","e","n","t"]},default:["g","r","a","d","i","e","n","t"]},shape1OffsetX:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape1OffsetY:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape1Rotation:{type:"array",items:{type:"integer",minimum:-180,maximum:180},maxItems:2,default:[-180,180]},shape2:{type:"array",items:{type:"string",enum:["g","r","a","d","i","e","n","t"]},default:["g","r","a","d","i","e","n","t"]},shape2OffsetX:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape2OffsetY:{type:"array",items:{type:"integer",minimum:-80,maximum:80},maxItems:2,default:[-80,80]},shape2Rotation:{type:"array",items:{type:"integer",minimum:-160,maximum:160},maxItems:2,default:[-160,160]}}},wX={title:"Glass",creator:"DiceBear",source:"https://www.dicebear.com",homepage:"https://www.dicebear.com",license:{name:"CC0 1.0",url:"https://creativecommons.org/publicdomain/zero/1.0/"}},TX=({prng:r,options:e})=>{var t,n,i,o;const s=bX({prng:r,options:e}),a=_X({prng:r,options:e});return{attributes:{viewBox:"0 0 100 100",fill:"none","shape-rendering":"auto"},body:`<g style="mix-blend-mode:screen" opacity="0.6" filter="url(#dicebearGlass-a)"><g transform="translate(-25 -25)">${(n=(t=s.shape2)===null||t===void 0?void 0:t.value(s,a))!==null&&n!==void 0?n:""}</g></g><g style="mix-blend-mode:screen" opacity="0.6" filter="url(#dicebearGlass-b)"><g transform="translate(-25 -25)">${(o=(i=s.shape1)===null||i===void 0?void 0:i.value(s,a))!==null&&o!==void 0?o:""}</g></g><defs><filter id="dicebearGlass-a" x="-57" y="-57" width="214" height="214" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="16" result="effect1_foregroundBlur_25_7"/></filter><filter id="dicebearGlass-b" x="-57" y="-57" width="214" height="214" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="16" result="effect1_foregroundBlur_25_7"/></filter></defs>`,extra:()=>({...Object.entries(s).reduce((l,[c,u])=>(l[c]=u==null?void 0:u.name,l),{}),...Object.entries(a).reduce((l,[c,u])=>(l[`${c}Color`]=u,l),{})})}},RX=Object.freeze(Object.defineProperty({__proto__:null,create:TX,meta:wX,schema:EX},Symbol.toStringTag,{value:"Module"}));function xL({className:r,size:e="default",...t}){return g.jsx(V3,{"data-slot":"avatar","data-size":e,className:Le("group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",r),...t})}function CX({className:r,...e}){return g.jsx($3,{"data-slot":"avatar-fallback",className:Le("flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",r),...e})}function kX({className:r,...e}){return g.jsx("span",{"data-slot":"avatar-badge",className:Le("absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none","group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden","group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2","group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",r),...e})}function IX(r){const e=r.indexOf(":");if(e>0){const t=r.slice(1,e);return`${r.slice(e+1)}+${t}`}return r}const II={online:"bg-green-400",unavailable:"bg-yellow-400",offline:"bg-zinc-500"};function l0({userId:r,size:e="default",presence:t,className:n}){const i=mX(RX,{seed:IX(r)}).toDataUri();return g.jsxs(xL,{size:e,className:Le(n),children:[g.jsx("img",{src:i,alt:r,className:"aspect-square size-full rounded-full object-cover"}),t!==void 0&&g.jsx(kX,{"data-presence":t,className:Le(II[t]??II.offline)})]})}function Pf({...r}){return g.jsx(T$,{"data-slot":"dropdown-menu",...r})}function Mf({...r}){return g.jsx(R$,{"data-slot":"dropdown-menu-trigger",...r})}function Af({className:r,align:e="start",sideOffset:t=4,...n}){return g.jsx(C$,{children:g.jsx(k$,{"data-slot":"dropdown-menu-content",sideOffset:t,align:e,className:Le("z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:overflow-hidden data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",r),...n})})}function Oa({className:r,inset:e,variant:t="default",...n}){return g.jsx(I$,{"data-slot":"dropdown-menu-item","data-inset":e,"data-variant":t,className:Le("group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",r),...n})}function xX({...r}){return g.jsx(x$,{"data-slot":"dropdown-menu-radio-group",...r})}function xI({className:r,children:e,inset:t,...n}){return g.jsxs(O$,{"data-slot":"dropdown-menu-radio-item","data-inset":t,className:Le("relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",r),...n,children:[g.jsx("span",{className:"pointer-events-none absolute right-2 flex items-center justify-center","data-slot":"dropdown-menu-radio-item-indicator",children:g.jsx(P$,{children:g.jsx(FE,{})})}),e]})}function OL({className:r,...e}){return g.jsx(M$,{"data-slot":"dropdown-menu-separator",className:Le("-mx-1 my-1 h-px bg-border",r),...e})}function OX(r,e){const[t,n]=_.useState({ready:!1,spaceId:null});return _.useEffect(()=>{let i=!1;return(async()=>{const o=de.safeGet();if(!o)return;const s=`#${r}:${e}`;try{const a=await o.getRoomIdForAlias(s);if(i)return;if(!a){n({ready:!0,spaceId:null});return}const l=a.room_id;o.getRoom(l)||await o.joinRoom(s),i||n({ready:!0,spaceId:l})}catch{i||n({ready:!0,spaceId:null})}})(),()=>{i=!0}},[r,e]),t}function PL(){const r=_.useSyncExternalStore(e=>de.subscribe(e),()=>de.safeGet(),()=>null);if(!r)throw new Error("useMatrixClient called when not logged in");return r}function xc(r){const e=/^@([^:]+):/.exec(r);return e?e[1]:r}function ML(r){return r.name||xc(r.userId)}function $a(r){let e=0;for(let n=0;n<r.length;n++)e=e*31+r.charCodeAt(n)|0;return`hsl(${(e%360+360)%360} 70% 72%)`}const AL=/(@[A-Za-z0-9._\-=/+]+:[A-Za-z0-9.\-]+)/g,PX=/^@[A-Za-z0-9._\-=/+]+:[A-Za-z0-9.\-]+$/;function MX(r,e){const t=new Map;for(const s of e){const a=xc(s.userId);a!==s.userId&&!t.has(a)&&t.set(a,s.userId)}const n=new Set;for(const s of r.match(AL)??[])n.add(s);const i=/(^|\s)@([A-Za-z0-9._\-=/+]+)(?!:[A-Za-z0-9.\-])/g;return{body:r.replace(i,(s,a,l)=>{const c=t.get(l);return c?(n.add(c),`${a}${c}`):s}),userIds:Array.from(n)}}function DL(r){return r.split(AL).map(t=>PX.test(t)?{text:t,userId:t}:{text:t,userId:null})}function AX(r,e){const t=de.safeGet();if(!t)return xc(r);if(e){const i=t.getRoom(e),o=i==null?void 0:i.getMember(r);if(o)return ML(o)}const n=t.getUser(r);return n!=null&&n.displayName?n.displayName:xc(r)}function $o(r,e){return _.useSyncExternalStore(t=>{const n=de.subscribe(t),i=de.safeGet();if(!i)return n;const o=e?i.getRoom(e)??null:null,s=()=>t();o==null||o.currentState.on(Me.Members,s);const a=i.getUser(r),l=()=>t();return a==null||a.on(ar.DisplayName,l),()=>{o==null||o.currentState.off(Me.Members,s),a==null||a.off(ar.DisplayName,l),n()}},()=>AX(r,e),()=>xc(r))}const Kl=[];let li=Kl;function DX(){const r=de.safeGet();if(!r)return li!==Kl&&(li=Kl),li;const e=r.getAccountData("m.direct");if(!e)return li!==Kl&&(li=Kl),li;const t=e.getContent(),n=new Set;for(const o of Object.values(t))for(const s of o??[])n.add(s);const i=Array.from(n).map(o=>r.getRoom(o)).filter(o=>!!o);return li.length===i.length&&li.every((o,s)=>o===i[s])||(li=i),li}function NX(){return _.useSyncExternalStore(r=>{const e=de.safeGet();if(!e)return de.subscribe(r);const t=()=>r();e.on(be.AccountData,t);const n=de.subscribe(r);return()=>{e.off(be.AccountData,t),n()}},DX,()=>Kl)}const Ev=[];let Qo=Ev;function LX(){const r=de.safeGet();if(!r)return Qo!==Ev&&(Qo=Ev),Qo;const e=r.getRooms().filter(t=>{var n;return!!((n=t.tags)!=null&&n["m.favourite"])});return Qo.length===e.length&&Qo.every((t,n)=>t===e[n])||(Qo=e),Qo}function UX(){return _.useSyncExternalStore(r=>{const e=de.safeGet();if(!e)return de.subscribe(r);const t=()=>r();for(const i of e.getRooms())i.on(pe.Tags,t);const n=de.subscribe(r);return()=>{for(const i of e.getRooms())i.off(pe.Tags,t);n()}},LX,()=>Ev)}const NL={level:0,canSendEvent:()=>!1,canSendStateEvent:()=>!1},OI=new Map;function jX(r){var d;const e=de.safeGet(),t=e==null?void 0:e.getRoom(r),n=e==null?void 0:e.getUserId();if(!t||!n)return NL;const i=t.currentState.getStateEvents(V.RoomPowerLevels,"")??null,o=OI.get(r);if(o&&o.plEvent===i)return o.result;const s=(i==null?void 0:i.getContent())??{},a=((d=s.users)==null?void 0:d[n])??s.users_default??0,l=s.events_default??0,c=s.state_default??50,u={level:a,canSendEvent:f=>{var p;return a>=(((p=s.events)==null?void 0:p[f])??l)},canSendStateEvent:f=>{var p;return a>=(((p=s.events)==null?void 0:p[f])??c)}};return OI.set(r,{plEvent:i,result:u}),u}function Df(r){return _.useSyncExternalStore(e=>{const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return de.subscribe(e);const i=()=>e();n.currentState.on(Me.Events,i);const o=de.subscribe(e);return()=>{n.currentState.off(Me.Events,i),o()}},()=>jX(r),()=>NL)}const c0=[];let kh=c0;function FX(){var e;const r=((e=de.safeGet())==null?void 0:e.getRooms())??c0;return kh.length===r.length&&kh.every((t,n)=>t===r[n])?kh:(kh=r,r)}function BX(){return _.useSyncExternalStore(r=>{const e=de.safeGet();if(!e)return de.subscribe(r);const t=()=>r();e.on(be.Room,t),e.on(be.DeleteRoom,t);const n=de.subscribe(r);return()=>{e.off(be.Room,t),e.off(be.DeleteRoom,t),n()}},FX,()=>c0)}const wy={total:0,highlight:0};function KX(r){let e=0,t=0;for(const n of r)e+=n.getUnreadNotificationCount(it.Total),t+=n.getUnreadNotificationCount(it.Highlight);return{total:e,highlight:t}}function Ty(r){const e=_.useRef(wy);return _.useSyncExternalStore(t=>{const n=()=>t();for(const o of r)o.on(pe.UnreadNotifications,n);const i=de.subscribe(t);return()=>{for(const o of r)o.off(pe.UnreadNotifications,n);i()}},()=>{const t=KX(r),n=e.current;if(n.total===t.total&&n.highlight===t.highlight)return n;const i=t.total===0&&t.highlight===0?wy:t;return e.current=i,i},()=>wy)}const ju=[],Ry=new Map;function VX(r){const e=de.safeGet(),t=e==null?void 0:e.getRoom(r),n=Ry.get(r)??ju;if(!e||!t)return n!==ju&&Ry.set(r,ju),ju;const o=t.currentState.getStateEvents("m.space.child").map(s=>s.getStateKey()).filter(s=>!!s).map(s=>e.getRoom(s)).filter(s=>!!s);return n.length===o.length&&n.every((s,a)=>s===o[a])?n:(Ry.set(r,o),o)}function $X(r){return _.useSyncExternalStore(e=>{const t=de.safeGet();if(!t)return de.subscribe(e);let n=null;const i=()=>{if(n)return;const a=t.getRoom(r);if(!a)return;const l=()=>e();a.currentState.on(Me.Events,l),n=()=>a.currentState.off(Me.Events,l)};i();const o=()=>{i(),e()};t.on(be.Room,o);const s=de.subscribe(e);return()=>{t.off(be.Room,o),n&&n(),s()}},()=>VX(r),()=>ju)}function WX({className:r,children:e,...t}){return g.jsxs(aW,{"data-slot":"scroll-area",className:Le("relative",r),...t,children:[g.jsx(lW,{"data-slot":"scroll-area-viewport",className:"size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1",children:e}),g.jsx(qX,{}),g.jsx(cW,{})]})}function qX({className:r,orientation:e="vertical",...t}){return g.jsx(g1,{"data-slot":"scroll-area-scrollbar","data-orientation":e,orientation:e,className:Le("flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",r),...t,children:g.jsx(_1,{"data-slot":"scroll-area-thumb",className:"relative flex-1 rounded-full bg-border"})})}var PI=1,GX=.9,HX=.8,zX=.17,Cy=.1,ky=.999,YX=.9999,JX=.99,XX=/[\\\/_+.#"@\[\(\{&]/,QX=/[\\\/_+.#"@\[\(\{&]/g,ZX=/[\s-]/,LL=/[\s-]/g;function O_(r,e,t,n,i,o,s){if(o===e.length)return i===r.length?PI:JX;var a=`${i},${o}`;if(s[a]!==void 0)return s[a];for(var l=n.charAt(o),c=t.indexOf(l,i),u=0,d,f,p,h;c>=0;)d=O_(r,e,t,n,c+1,o+1,s),d>u&&(c===i?d*=PI:XX.test(r.charAt(c-1))?(d*=HX,p=r.slice(i,c-1).match(QX),p&&i>0&&(d*=Math.pow(ky,p.length))):ZX.test(r.charAt(c-1))?(d*=GX,h=r.slice(i,c-1).match(LL),h&&i>0&&(d*=Math.pow(ky,h.length))):(d*=zX,i>0&&(d*=Math.pow(ky,c-i))),r.charAt(c)!==e.charAt(o)&&(d*=YX)),(d<Cy&&t.charAt(c-1)===n.charAt(o+1)||n.charAt(o+1)===n.charAt(o)&&t.charAt(c-1)!==n.charAt(o))&&(f=O_(r,e,t,n,c+1,o+2,s),f*Cy>d&&(d=f*Cy)),d>u&&(u=d),c=t.indexOf(l,c+1);return s[a]=u,u}function MI(r){return r.toLowerCase().replace(LL," ")}function eQ(r,e,t){return r=t&&t.length>0?`${r+" "+t.join(" ")}`:r,O_(r,e,MI(r),MI(e),0,0,{})}var Ru='[cmdk-group=""]',Iy='[cmdk-group-items=""]',tQ='[cmdk-group-heading=""]',UL='[cmdk-item=""]',AI=`${UL}:not([aria-disabled="true"])`,P_="cmdk-item-select",Tl="data-value",rQ=(r,e,t)=>eQ(r,e,t),jL=_.createContext(void 0),Nf=()=>_.useContext(jL),FL=_.createContext(void 0),u0=()=>_.useContext(FL),BL=_.createContext(void 0),KL=_.forwardRef((r,e)=>{let t=Rl(()=>{var Y,le;return{search:"",value:(le=(Y=r.value)!=null?Y:r.defaultValue)!=null?le:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=Rl(()=>new Set),i=Rl(()=>new Map),o=Rl(()=>new Map),s=Rl(()=>new Set),a=VL(r),{label:l,children:c,value:u,onValueChange:d,filter:f,shouldFilter:p,loop:h,disablePointerSelection:m=!1,vimBindings:E=!0,...y}=r,S=Tn(),R=Tn(),k=Tn(),x=_.useRef(null),T=hQ();Wa(()=>{if(u!==void 0){let Y=u.trim();t.current.value=Y,O.emit()}},[u]),Wa(()=>{T(6,$)},[]);let O=_.useMemo(()=>({subscribe:Y=>(s.current.add(Y),()=>s.current.delete(Y)),snapshot:()=>t.current,setState:(Y,le,B)=>{var W,A,D,P;if(!Object.is(t.current[Y],le)){if(t.current[Y]=le,Y==="search")ie(),F(),T(1,H);else if(Y==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let M=document.getElementById(k);M?M.focus():(W=document.getElementById(S))==null||W.focus()}if(T(7,()=>{var M;t.current.selectedItemId=(M=X())==null?void 0:M.id,O.emit()}),B||T(5,$),((A=a.current)==null?void 0:A.value)!==void 0){let M=le??"";(P=(D=a.current).onValueChange)==null||P.call(D,M);return}}O.emit()}},emit:()=>{s.current.forEach(Y=>Y())}}),[]),C=_.useMemo(()=>({value:(Y,le,B)=>{var W;le!==((W=o.current.get(Y))==null?void 0:W.value)&&(o.current.set(Y,{value:le,keywords:B}),t.current.filtered.items.set(Y,N(le,B)),T(2,()=>{F(),O.emit()}))},item:(Y,le)=>(n.current.add(Y),le&&(i.current.has(le)?i.current.get(le).add(Y):i.current.set(le,new Set([Y]))),T(3,()=>{ie(),F(),t.current.value||H(),O.emit()}),()=>{o.current.delete(Y),n.current.delete(Y),t.current.filtered.items.delete(Y);let B=X();T(4,()=>{ie(),(B==null?void 0:B.getAttribute("id"))===Y&&H(),O.emit()})}),group:Y=>(i.current.has(Y)||i.current.set(Y,new Set),()=>{o.current.delete(Y),i.current.delete(Y)}),filter:()=>a.current.shouldFilter,label:l||r["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:S,inputId:k,labelId:R,listInnerRef:x}),[]);function N(Y,le){var B,W;let A=(W=(B=a.current)==null?void 0:B.filter)!=null?W:rQ;return Y?A(Y,t.current.search,le):0}function F(){if(!t.current.search||a.current.shouldFilter===!1)return;let Y=t.current.filtered.items,le=[];t.current.filtered.groups.forEach(W=>{let A=i.current.get(W),D=0;A.forEach(P=>{let M=Y.get(P);D=Math.max(M,D)}),le.push([W,D])});let B=x.current;oe().sort((W,A)=>{var D,P;let M=W.getAttribute("id"),I=A.getAttribute("id");return((D=Y.get(I))!=null?D:0)-((P=Y.get(M))!=null?P:0)}).forEach(W=>{let A=W.closest(Iy);A?A.appendChild(W.parentElement===A?W:W.closest(`${Iy} > *`)):B.appendChild(W.parentElement===B?W:W.closest(`${Iy} > *`))}),le.sort((W,A)=>A[1]-W[1]).forEach(W=>{var A;let D=(A=x.current)==null?void 0:A.querySelector(`${Ru}[${Tl}="${encodeURIComponent(W[0])}"]`);D==null||D.parentElement.appendChild(D)})}function H(){let Y=oe().find(B=>B.getAttribute("aria-disabled")!=="true"),le=Y==null?void 0:Y.getAttribute(Tl);O.setState("value",le||void 0)}function ie(){var Y,le,B,W;if(!t.current.search||a.current.shouldFilter===!1){t.current.filtered.count=n.current.size;return}t.current.filtered.groups=new Set;let A=0;for(let D of n.current){let P=(le=(Y=o.current.get(D))==null?void 0:Y.value)!=null?le:"",M=(W=(B=o.current.get(D))==null?void 0:B.keywords)!=null?W:[],I=N(P,M);t.current.filtered.items.set(D,I),I>0&&A++}for(let[D,P]of i.current)for(let M of P)if(t.current.filtered.items.get(M)>0){t.current.filtered.groups.add(D);break}t.current.filtered.count=A}function $(){var Y,le,B;let W=X();W&&(((Y=W.parentElement)==null?void 0:Y.firstChild)===W&&((B=(le=W.closest(Ru))==null?void 0:le.querySelector(tQ))==null||B.scrollIntoView({block:"nearest"})),W.scrollIntoView({block:"nearest"}))}function X(){var Y;return(Y=x.current)==null?void 0:Y.querySelector(`${UL}[aria-selected="true"]`)}function oe(){var Y;return Array.from(((Y=x.current)==null?void 0:Y.querySelectorAll(AI))||[])}function re(Y){let le=oe()[Y];le&&O.setState("value",le.getAttribute(Tl))}function ae(Y){var le;let B=X(),W=oe(),A=W.findIndex(P=>P===B),D=W[A+Y];(le=a.current)!=null&&le.loop&&(D=A+Y<0?W[W.length-1]:A+Y===W.length?W[0]:W[A+Y]),D&&O.setState("value",D.getAttribute(Tl))}function q(Y){let le=X(),B=le==null?void 0:le.closest(Ru),W;for(;B&&!W;)B=Y>0?dQ(B,Ru):fQ(B,Ru),W=B==null?void 0:B.querySelector(AI);W?O.setState("value",W.getAttribute(Tl)):ae(Y)}let z=()=>re(oe().length-1),Q=Y=>{Y.preventDefault(),Y.metaKey?z():Y.altKey?q(1):ae(1)},Ie=Y=>{Y.preventDefault(),Y.metaKey?re(0):Y.altKey?q(-1):ae(-1)};return _.createElement(Je.div,{ref:e,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:Y=>{var le;(le=y.onKeyDown)==null||le.call(y,Y);let B=Y.nativeEvent.isComposing||Y.keyCode===229;if(!(Y.defaultPrevented||B))switch(Y.key){case"n":case"j":{E&&Y.ctrlKey&&Q(Y);break}case"ArrowDown":{Q(Y);break}case"p":case"k":{E&&Y.ctrlKey&&Ie(Y);break}case"ArrowUp":{Ie(Y);break}case"Home":{Y.preventDefault(),re(0);break}case"End":{Y.preventDefault(),z();break}case"Enter":{Y.preventDefault();let W=X();if(W){let A=new Event(P_);W.dispatchEvent(A)}}}}},_.createElement("label",{"cmdk-label":"",htmlFor:C.inputId,id:C.labelId,style:vQ},l),Km(r,Y=>_.createElement(FL.Provider,{value:O},_.createElement(jL.Provider,{value:C},Y))))}),nQ=_.forwardRef((r,e)=>{var t,n;let i=Tn(),o=_.useRef(null),s=_.useContext(BL),a=Nf(),l=VL(r),c=(n=(t=l.current)==null?void 0:t.forceMount)!=null?n:s==null?void 0:s.forceMount;Wa(()=>{if(!c)return a.item(i,s==null?void 0:s.id)},[c]);let u=$L(i,o,[r.value,r.children,o],r.keywords),d=u0(),f=Us(T=>T.value&&T.value===u.current),p=Us(T=>c||a.filter()===!1?!0:T.search?T.filtered.items.get(i)>0:!0);_.useEffect(()=>{let T=o.current;if(!(!T||r.disabled))return T.addEventListener(P_,h),()=>T.removeEventListener(P_,h)},[p,r.onSelect,r.disabled]);function h(){var T,O;m(),(O=(T=l.current).onSelect)==null||O.call(T,u.current)}function m(){d.setState("value",u.current,!0)}if(!p)return null;let{disabled:E,value:y,onSelect:S,forceMount:R,keywords:k,...x}=r;return _.createElement(Je.div,{ref:Do(o,e),...x,id:i,"cmdk-item":"",role:"option","aria-disabled":!!E,"aria-selected":!!f,"data-disabled":!!E,"data-selected":!!f,onPointerMove:E||a.getDisablePointerSelection()?void 0:m,onClick:E?void 0:h},r.children)}),iQ=_.forwardRef((r,e)=>{let{heading:t,children:n,forceMount:i,...o}=r,s=Tn(),a=_.useRef(null),l=_.useRef(null),c=Tn(),u=Nf(),d=Us(p=>i||u.filter()===!1?!0:p.search?p.filtered.groups.has(s):!0);Wa(()=>u.group(s),[]),$L(s,a,[r.value,r.heading,l]);let f=_.useMemo(()=>({id:s,forceMount:i}),[i]);return _.createElement(Je.div,{ref:Do(a,e),...o,"cmdk-group":"",role:"presentation",hidden:d?void 0:!0},t&&_.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:c},t),Km(r,p=>_.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":t?c:void 0},_.createElement(BL.Provider,{value:f},p))))}),oQ=_.forwardRef((r,e)=>{let{alwaysRender:t,...n}=r,i=_.useRef(null),o=Us(s=>!s.search);return!t&&!o?null:_.createElement(Je.div,{ref:Do(i,e),...n,"cmdk-separator":"",role:"separator"})}),sQ=_.forwardRef((r,e)=>{let{onValueChange:t,...n}=r,i=r.value!=null,o=u0(),s=Us(c=>c.search),a=Us(c=>c.selectedItemId),l=Nf();return _.useEffect(()=>{r.value!=null&&o.setState("search",r.value)},[r.value]),_.createElement(Je.input,{ref:e,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:i?r.value:s,onChange:c=>{i||o.setState("search",c.target.value),t==null||t(c.target.value)}})}),aQ=_.forwardRef((r,e)=>{let{children:t,label:n="Suggestions",...i}=r,o=_.useRef(null),s=_.useRef(null),a=Us(c=>c.selectedItemId),l=Nf();return _.useEffect(()=>{if(s.current&&o.current){let c=s.current,u=o.current,d,f=new ResizeObserver(()=>{d=requestAnimationFrame(()=>{let p=c.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return f.observe(c),()=>{cancelAnimationFrame(d),f.unobserve(c)}}},[]),_.createElement(Je.div,{ref:Do(o,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":n,id:l.listId},Km(r,c=>_.createElement("div",{ref:Do(s,l.listInnerRef),"cmdk-list-sizer":""},c)))}),lQ=_.forwardRef((r,e)=>{let{open:t,onOpenChange:n,overlayClassName:i,contentClassName:o,container:s,...a}=r;return _.createElement(HE,{open:t,onOpenChange:n},_.createElement(zE,{container:s},_.createElement(YE,{"cmdk-overlay":"",className:i}),_.createElement(JE,{"aria-label":r.label,"cmdk-dialog":"",className:o},_.createElement(KL,{ref:e,...a}))))}),cQ=_.forwardRef((r,e)=>Us(t=>t.filtered.count===0)?_.createElement(Je.div,{ref:e,...r,"cmdk-empty":"",role:"presentation"}):null),uQ=_.forwardRef((r,e)=>{let{progress:t,children:n,label:i="Loading...",...o}=r;return _.createElement(Je.div,{ref:e,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},Km(r,s=>_.createElement("div",{"aria-hidden":!0},s)))}),Jc=Object.assign(KL,{List:aQ,Item:nQ,Input:sQ,Group:iQ,Separator:oQ,Dialog:lQ,Empty:cQ,Loading:uQ});function dQ(r,e){let t=r.nextElementSibling;for(;t;){if(t.matches(e))return t;t=t.nextElementSibling}}function fQ(r,e){let t=r.previousElementSibling;for(;t;){if(t.matches(e))return t;t=t.previousElementSibling}}function VL(r){let e=_.useRef(r);return Wa(()=>{e.current=r}),e}var Wa=typeof window>"u"?_.useEffect:_.useLayoutEffect;function Rl(r){let e=_.useRef();return e.current===void 0&&(e.current=r()),e}function Us(r){let e=u0(),t=()=>r(e.snapshot());return _.useSyncExternalStore(e.subscribe,t,t)}function $L(r,e,t,n=[]){let i=_.useRef(),o=Nf();return Wa(()=>{var s;let a=(()=>{var c;for(let u of t){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(c=u.current.textContent)==null?void 0:c.trim():i.current}})(),l=n.map(c=>c.trim());o.value(r,a,l),(s=e.current)==null||s.setAttribute(Tl,a),i.current=a}),i}var hQ=()=>{let[r,e]=_.useState(),t=Rl(()=>new Map);return Wa(()=>{t.current.forEach(n=>n()),t.current=new Map},[r]),(n,i)=>{t.current.set(n,i),e({})}};function pQ(r){let e=r.type;return typeof e=="function"?e(r.props):"render"in e?e.render(r.props):r}function Km({asChild:r,children:e},t){return r&&_.isValidElement(e)?_.cloneElement(pQ(e),{ref:e.ref},t(e.props.children)):t(e)}var vQ={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function Vm({...r}){return g.jsx(HE,{"data-slot":"dialog",...r})}function mQ({...r}){return g.jsx(zE,{"data-slot":"dialog-portal",...r})}function gQ({className:r,...e}){return g.jsx(YE,{"data-slot":"dialog-overlay",className:Le("fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",r),...e})}function $m({className:r,children:e,showCloseButton:t=!0,...n}){return g.jsxs(mQ,{children:[g.jsx(gQ,{}),g.jsxs(JE,{"data-slot":"dialog-content",className:Le("fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",r),...n,children:[e,t&&g.jsx(XE,{"data-slot":"dialog-close",asChild:!0,children:g.jsxs(At,{variant:"ghost",className:"absolute top-2 right-2",size:"icon-sm",children:[g.jsx(BE,{}),g.jsx("span",{className:"sr-only",children:"Close"})]})})]})]})}function Wm({className:r,...e}){return g.jsx("div",{"data-slot":"dialog-header",className:Le("flex flex-col gap-2",r),...e})}function qm({className:r,showCloseButton:e=!1,children:t,...n}){return g.jsxs("div",{"data-slot":"dialog-footer",className:Le("-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",r),...n,children:[t,e&&g.jsx(XE,{asChild:!0,children:g.jsx(At,{variant:"outline",children:"Close"})})]})}function Gm({className:r,...e}){return g.jsx(FM,{"data-slot":"dialog-title",className:Le("font-heading text-base leading-none font-medium",r),...e})}function d0({className:r,...e}){return g.jsx(BM,{"data-slot":"dialog-description",className:Le("text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",r),...e})}function yQ({className:r,...e}){return g.jsx("div",{"data-slot":"input-group",role:"group",className:Le("group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",r),...e})}const SQ=o0("flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",{variants:{align:{"inline-start":"order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]","inline-end":"order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]","block-start":"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2","block-end":"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2"}},defaultVariants:{align:"inline-start"}});function bQ({className:r,align:e="inline-start",...t}){return g.jsx("div",{role:"group","data-slot":"input-group-addon","data-align":e,className:Le(SQ({align:e}),r),onClick:n=>{var i,o;n.target.closest("button")||(o=(i=n.currentTarget.parentElement)==null?void 0:i.querySelector("input"))==null||o.focus()},...t})}function WL({className:r,...e}){return g.jsx(Jc,{"data-slot":"command",className:Le("flex size-full flex-col overflow-hidden rounded-xl! bg-popover p-1 text-popover-foreground",r),...e})}function qL({className:r,...e}){return g.jsx("div",{"data-slot":"command-input-wrapper",className:"p-1 pb-0",children:g.jsxs(yQ,{className:"h-8! rounded-lg! border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!",children:[g.jsx(Jc.Input,{"data-slot":"command-input",className:Le("w-full text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",r),...e}),g.jsx(bQ,{children:g.jsx(jK,{className:"size-4 shrink-0 opacity-50"})})]})})}function GL({className:r,...e}){return g.jsx(Jc.List,{"data-slot":"command-list",className:Le("no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none",r),...e})}function HL({className:r,...e}){return g.jsx(Jc.Empty,{"data-slot":"command-empty",className:Le("py-6 text-center text-sm",r),...e})}function zL({className:r,...e}){return g.jsx(Jc.Group,{"data-slot":"command-group",className:Le("overflow-hidden p-1 text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground",r),...e})}function YL({className:r,children:e,...t}){return g.jsxs(Jc.Item,{"data-slot":"command-item",className:Le("group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-lg! data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-selected:*:[svg]:text-foreground",r),...t,children:[e,g.jsx(FE,{className:"ml-auto opacity-0 group-has-data-[slot=command-shortcut]/command-item:hidden group-data-[checked=true]/command-item:opacity-100"})]})}const pp=[],DI=new Map;function _Q(r){var i;if(!r)return pp;const e=(i=de.safeGet())==null?void 0:i.getRoom(r);if(!e)return pp;const t=DI.get(r)??pp,n=e.getJoinedMembers();return t.length===n.length&&t.every((o,s)=>o===n[s])?t:(DI.set(r,n),n)}function EQ(r){return _.useSyncExternalStore(e=>{const t=de.safeGet(),n=r?t==null?void 0:t.getRoom(r):null;if(!n)return de.subscribe(e);const i=()=>e();n.currentState.on(Me.Members,i);const o=de.subscribe(e);return()=>{n.currentState.off(Me.Members,i),o()}},()=>_Q(r),()=>pp)}function wQ(r){if(!r||typeof r!="object")return null;const e=r;if(e.version!==1||!Array.isArray(e.agents))return null;const t=[];for(const n of e.agents)n.user_id&&t.push({userId:n.user_id,name:n.name??n.user_id,role:n.role,avatarUrl:n.avatar_url,rooms:Array.isArray(n.rooms)?n.rooms:[]});return t}function TQ(r){return new Set(r.map(e=>e.userId))}const JL={ready:!1,agents:[],isAgent:()=>!1},xy=new WeakMap;function RQ(r){var l;const e=(l=de.safeGet())==null?void 0:l.getRoom(r);if(!e)return JL;const t=xy.get(e),n=e.currentState.getStateEvents("eco.zoon.workforce",""),i=(n==null?void 0:n.getContent())??null,o=wQ(i);if(!o){if(t&&!t.ready)return t;const c={ready:!1,agents:[],isAgent:()=>!1};return xy.set(e,c),c}if(t!=null&&t.ready&&t.agents.length===o.length&&t.agents.every((c,u)=>c.userId===o[u].userId))return t;const s=TQ(o),a={ready:!0,agents:o,isAgent:c=>s.has(c)};return xy.set(e,a),a}function XL(r){return _.useSyncExternalStore(e=>{const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return de.subscribe(e);const i=()=>e();n.currentState.on(Me.Events,i);const o=de.subscribe(e);return()=>{n.currentState.off(Me.Events,i),o()}},()=>RQ(r),()=>JL)}function CQ({open:r,spaceId:e,onOpenChange:t}){var m;const n=EQ(e),{ready:i,isAgent:o}=XL(e),[s,a]=_.useState([]),[l,c]=_.useState(!1),u=Vs(),d=(m=de.safeGet())==null?void 0:m.getUserId(),f=_.useMemo(()=>n.filter(E=>E.userId!==d).filter(E=>!i||!o(E.userId)),[n,d,i,o]),p=E=>{a(y=>y.includes(E)?y.filter(S=>S!==E):[...y,E])},h=async()=>{var y;if(!s.length)return;const E=de.safeGet();if(E){c(!0);try{const S=await E.createRoom({is_direct:!0,preset:"trusted_private_chat",invite:s}),R=((y=E.getAccountData("m.direct"))==null?void 0:y.getContent())??{},k={...R},x=s[0];k[x]=[...R[x]??[],S.room_id],await E.setAccountData("m.direct",k),t(!1),a([]),u(`/room/${S.room_id}`)}finally{c(!1)}}};return g.jsx(Vm,{open:r,onOpenChange:t,children:g.jsxs($m,{children:[g.jsxs(Wm,{children:[g.jsx(Gm,{children:"Start a DM"}),g.jsxs(d0,{children:["DMs are private to the people you invite. Agents are managed via ",g.jsx("code",{children:"zooid.yaml"}),"."]})]}),!i&&g.jsx("p",{className:"rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:"Agent list unavailable — the picker may include agents until the workforce roster publishes."}),g.jsxs(WL,{children:[g.jsx(qL,{placeholder:"Search humans…"}),g.jsxs(GL,{children:[g.jsx(HL,{children:"No humans found."}),g.jsx(zL,{children:f.map(E=>g.jsxs(YL,{value:`${E.name??E.userId} ${E.userId}`,onSelect:()=>p(E.userId),"data-selected":s.includes(E.userId)||void 0,children:[g.jsx("span",{className:"flex-1 truncate",children:E.name??E.userId}),g.jsx("span",{className:"text-xs text-muted-foreground",children:E.userId})]},E.userId))})]})]}),g.jsxs(qm,{children:[g.jsx(At,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),g.jsx(At,{disabled:!s.length||l,onClick:h,children:"Start DM"})]})]})})}function kQ({open:r,spaceId:e,onOpenChange:t}){const[n,i]=_.useState(""),[o,s]=_.useState(""),[a,l]=_.useState("space"),[c,u]=_.useState(!1),d=Vs(),f=()=>{i(""),s(""),l("space"),u(!1)},p=async h=>{var y;h.preventDefault();const m=de.safeGet();if(!m)return;const E=n.trim();if(E){u(!0);try{const S=((y=m.getUserId())==null?void 0:y.split(":")[1])??"",R=[{type:"m.space.parent",state_key:e,content:{via:[S],canonical:!0}}];a==="space"&&R.push({type:"m.room.join_rules",state_key:"",content:{join_rule:"restricted",allow:[{type:"m.room_membership",room_id:e}]}});const x=(await m.createRoom({name:E,topic:o.trim()||void 0,preset:"private_chat",initial_state:R})).room_id;await m.sendStateEvent(e,"m.space.child",{via:[S]},x),t(!1),f(),d(`/room/${x}`)}finally{u(!1)}}};return g.jsx(Vm,{open:r,onOpenChange:h=>{t(h),h||f()},children:g.jsx($m,{children:g.jsxs("form",{onSubmit:p,children:[g.jsxs(Wm,{children:[g.jsx(Gm,{children:"Create room"}),g.jsx(d0,{children:"Rooms are joinable by everyone in this space by default."})]}),g.jsxs("div",{className:"flex flex-col gap-3 py-2",children:[g.jsxs("div",{className:"flex flex-col gap-1.5",children:[g.jsx(Zd,{htmlFor:"room-name",children:"Name"}),g.jsx(Qd,{id:"room-name",value:n,onChange:h=>i(h.target.value),autoFocus:!0,placeholder:"design"})]}),g.jsxs("div",{className:"flex flex-col gap-1.5",children:[g.jsx(Zd,{htmlFor:"room-topic",children:"Topic"}),g.jsx(Qd,{id:"room-topic",value:o,onChange:h=>s(h.target.value),placeholder:"What is this channel about?"})]}),g.jsxs("fieldset",{className:"flex flex-col gap-2",children:[g.jsx("legend",{className:"text-sm font-medium",children:"Who can join"}),g.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[g.jsx("input",{type:"radio",name:"privacy",value:"space",checked:a==="space",onChange:()=>l("space")}),"Space members — anyone in this space can join"]}),g.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[g.jsx("input",{type:"radio",name:"privacy",value:"invite",checked:a==="invite",onChange:()=>l("invite")}),"Invite only — added manually"]})]})]}),g.jsxs(qm,{children:[g.jsx(At,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),g.jsx(At,{type:"submit",disabled:!n.trim()||c,children:"Create room"})]})]})})})}function IQ(r){var t,n;if(!r)return!1;const e=(t=de.safeGet())==null?void 0:t.getRoom(r);return!!((n=e==null?void 0:e.tags)!=null&&n["m.favourite"])}function QL(r){const e=_.useSyncExternalStore(n=>{const i=de.safeGet();if(!i||!r)return de.subscribe(n);let o=null;const s=()=>{if(o)return;const c=i.getRoom(r);if(!c)return;const u=()=>n();c.on(pe.Tags,u),o=()=>c.off(pe.Tags,u)};s();const a=()=>{s(),n()};i.on(be.Room,a);const l=de.subscribe(n);return()=>{i.off(be.Room,a),o&&o(),l()}},()=>IQ(r),()=>!1),t=_.useCallback(async()=>{if(!r)return;const n=de.safeGet();n&&(e?await n.deleteRoomTag(r,"m.favourite"):await n.setRoomTag(r,"m.favourite",{order:.5}))},[r,e]);return{isFavorite:e,toggle:t}}const Fu={total:0,highlight:0},Oy=new Map;function xQ(r){var i;const e=(i=de.safeGet())==null?void 0:i.getRoom(r),t=Oy.get(r)??Fu;if(!e)return t!==Fu&&Oy.set(r,Fu),Fu;const n={total:e.getUnreadNotificationCount(it.Total),highlight:e.getUnreadNotificationCount(it.Highlight)};return t.total===n.total&&t.highlight===n.highlight?t:(Oy.set(r,n),n)}function OQ(r){return _.useSyncExternalStore(e=>{const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return de.subscribe(e);const i=()=>e();n.on(pe.UnreadNotifications,i);const o=de.subscribe(e);return()=>{n.off(pe.UnreadNotifications,i),o()}},()=>xQ(r),()=>Fu)}function vp({total:r,highlight:e}){if(r<=0)return null;const t=r>99?"99+":String(r),n=e>0?"bg-destructive text-destructive-foreground":"bg-muted text-muted-foreground";return g.jsx("span",{"aria-label":`${r} unread`,className:`inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] font-medium tabular-nums ${n}`,children:t})}function Py({room:r}){const{isFavorite:e,toggle:t}=QL(r.roomId),{total:n,highlight:i}=OQ(r.roomId),o=n>0;return g.jsxs("div",{className:"group/row flex items-center gap-1 px-2 py-1.5 text-sm hover:bg-sidebar-accent",children:[g.jsxs(wB,{to:`/room/${r.roomId}`,className:"flex flex-1 items-center gap-2 truncate",children:[g.jsx(xL,{className:"size-6",children:g.jsx(CX,{children:(r.name??r.roomId).slice(0,2).toUpperCase()})}),g.jsx("span",{className:`truncate ${o?"font-semibold":""}`,children:r.name||r.roomId})]}),g.jsxs("div",{className:"relative h-5 min-w-5",children:[g.jsx("div",{className:"group-hover/row:invisible group-focus-within/row:invisible",children:g.jsx(vp,{total:n,highlight:i})}),g.jsxs(Pf,{children:[g.jsx(Mf,{asChild:!0,children:g.jsx("button",{type:"button","aria-label":"room actions",className:"absolute right-0 top-0 inline-flex h-5 w-5 items-center justify-center rounded-full text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground focus:opacity-100 group-hover/row:opacity-100 group-focus-within/row:opacity-100",children:g.jsx(bK,{className:"size-3"})})}),g.jsx(Af,{children:g.jsx(Oa,{onClick:t,children:e?"Remove from favorites":"Add to favorites"})})]})]})]})}function My({title:r,action:e,children:t,defaultExpanded:n=!0}){const[i,o]=_.useState(n);return g.jsxs("section",{role:"region","aria-label":r,className:"flex flex-col",children:[g.jsxs("header",{className:"flex items-center gap-1 px-2 py-1 text-xs uppercase text-muted-foreground",children:[g.jsxs("button",{type:"button","aria-label":`toggle ${r} section`,onClick:()=>o(s=>!s),className:"flex items-center gap-1",children:[i?g.jsx(oM,{className:"size-3"}):g.jsx(sM,{className:"size-3"}),g.jsx("h3",{className:"font-semibold",children:r})]}),g.jsx("div",{className:"ml-auto",children:e})]}),i&&g.jsx("div",{children:t})]})}const Ay="inline-flex h-5 w-5 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground";function PQ({scope:r,workforceSpaceId:e}){const t=r.kind==="space"?r.spaceId:"",n=UX(),i=NX(),o=$X(t),s=BX(),a=Df(t),l=r.kind==="space"&&a.canSendStateEvent("m.space.child"),c=r.kind==="space",[u,d]=_.useState(!1),[f,p]=_.useState(!1),h=Vs(),m=new Set,E=C=>{const N=[];for(const F of C)m.has(F.roomId)||(m.add(F.roomId),N.push(F));return N},y=r.kind==="space"?o:s.filter(C=>!C.isSpaceRoom()),S=E(n),R=E(i),k=E(y),x=Ty(S),T=Ty(R),O=Ty(k);return g.jsxs(WX,{className:"h-full",children:[g.jsxs("div",{className:"flex flex-col gap-2 p-2",children:[g.jsx(My,{title:"Favorites",action:g.jsx(vp,{total:x.total,highlight:x.highlight}),children:S.map(C=>g.jsx(Py,{room:C},C.roomId))}),g.jsxs(My,{title:"Rooms",action:g.jsx(eb,{children:g.jsxs("div",{className:"flex items-center gap-1",children:[g.jsx(vp,{total:O.total,highlight:O.highlight}),c?g.jsxs(qR,{children:[g.jsx(GR,{asChild:!0,children:g.jsx("button",{type:"button","aria-label":"browse rooms",onClick:()=>h("/browse"),className:Ay,children:g.jsx(yK,{className:"size-3"})})}),g.jsx(HR,{children:"Browse rooms"})]}):null,l?g.jsxs(qR,{children:[g.jsx(GR,{asChild:!0,children:g.jsx("button",{type:"button","aria-label":"add room",onClick:()=>d(!0),className:Ay,children:g.jsx(lR,{className:"size-3"})})}),g.jsx(HR,{children:"Create room"})]}):null]})}),children:[k.map(C=>g.jsx(Py,{room:C},C.roomId)),c&&k.length===0?g.jsx("button",{type:"button",onClick:()=>h("/browse"),className:"w-full rounded-md px-2 py-1.5 text-left text-sm text-muted-foreground hover:bg-muted hover:text-foreground",children:"Browse rooms…"}):null]}),g.jsx(My,{title:"DMs",defaultExpanded:!1,action:g.jsxs("div",{className:"flex items-center gap-1",children:[g.jsx(vp,{total:T.total,highlight:T.highlight}),g.jsx("button",{type:"button","aria-label":"start dm",onClick:()=>p(!0),className:Ay,children:g.jsx(lR,{className:"size-3"})})]}),children:R.map(C=>g.jsx(Py,{room:C},C.roomId))})]}),r.kind==="space"?g.jsx(kQ,{open:u,spaceId:r.spaceId,onOpenChange:d}):null,e?g.jsx(CQ,{open:f,spaceId:e,onOpenChange:p}):null]})}function MQ({scope:r,workforceSpaceId:e}){return g.jsx(PQ,{scope:r,workforceSpaceId:e})}const ZL=100,eU=50,tU=0;function rU(r){return r===ZL?{kind:"admin",level:r}:r===eU?{kind:"moderator",level:r}:r===tU?{kind:"default",level:r}:{kind:"custom",level:r}}function wv(r){switch(r.kind){case"admin":return"Admin";case"moderator":return"Moderator";case"default":return"Default";case"custom":return`Custom (${r.level})`}}function AQ(r){switch(r){case"admin":return ZL;case"moderator":return eU;case"default":return tU}}function DQ(r=1/0){return["admin","moderator","default"].map(e=>{const t=AQ(e);return{kind:e,level:t,label:wv({kind:e,level:t}),disabled:t>r}})}const NQ=[{kind:"admin",label:"Admins"},{kind:"moderator",label:"Moderators"},{kind:"member",label:"Members"}];function LQ(r){const e={admin:[],moderator:[],member:[]};for(const n of r){const i=n.role.kind==="admin"?"admin":n.role.kind==="moderator"?"moderator":"member";e[i].push(n)}const t=(n,i)=>i.powerLevel-n.powerLevel||n.displayName.localeCompare(i.displayName);return NQ.filter(({kind:n})=>e[n].length>0).map(({kind:n,label:i})=>({kind:n,label:i,members:e[n].sort(t)}))}const nU=[],NI=new WeakMap;function UQ(r){var l;const e=(l=de.safeGet())==null?void 0:l.getRoom(r);if(!e)return nU;const t=e.getJoinedMembers(),n=e.currentState.getStateEvents(V.RoomPowerLevels,"")??null,i=NI.get(e);if(i&&i.plEvent===n&&i.members.length===t.length&&i.members.every((c,u)=>c===t[u]))return i.result;const o=(n==null?void 0:n.getContent())??{},s=o.users_default??0,a=t.map(c=>{var d;const u=((d=o.users)==null?void 0:d[c.userId])??s;return{userId:c.userId,displayName:c.name,powerLevel:u,role:rU(u)}});return NI.set(e,{members:t,plEvent:n,result:a}),a}function f0(r){return _.useSyncExternalStore(e=>{const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return de.subscribe(e);const i=()=>e();n.currentState.on(Me.Members,i),n.currentState.on(Me.Events,i);const o=de.subscribe(e);return()=>{n.currentState.off(Me.Members,i),n.currentState.off(Me.Events,i),o()}},()=>UQ(r),()=>nU)}function jQ(r,e){const[t,n]=_.useState(r);return _.useEffect(()=>{const i=setTimeout(()=>n(r),e);return()=>clearTimeout(i)},[r,e]),t}const LI={results:[],loading:!1};function FQ(r){const e=jQ(r.trim(),300),[t,n]=_.useState(LI);return _.useEffect(()=>{const i=de.safeGet();if(!i||!e){n(LI);return}let o=!1;return n(s=>({...s,loading:!0})),i.searchUserDirectory({term:e,limit:10}).then(s=>{if(o)return;const a=i.getUserId(),l=s.results.filter(c=>c.user_id!==a).map(c=>({userId:c.user_id,displayName:c.display_name,avatarUrl:c.avatar_url}));n({results:l,loading:!1})}).catch(()=>{o||n({results:[],loading:!1})}),()=>{o=!0}},[e]),t}function BQ({open:r,roomId:e,spaceId:t,onOpenChange:n}){const[i,o]=_.useState(""),[s,a]=_.useState(null),[l,c]=_.useState(!1),{ready:u,isAgent:d}=XL(t),{results:f}=FQ(i),p=_.useMemo(()=>u?f.filter(E=>!d(E.userId)):f,[f,u,d]),h=()=>{o(""),a(null),c(!1)},m=async()=>{if(!s)return;const E=de.safeGet();if(E){c(!0);try{await E.invite(e,s),n(!1),h()}finally{c(!1)}}};return g.jsx(Vm,{open:r,onOpenChange:E=>{n(E),E||h()},children:g.jsxs($m,{children:[g.jsxs(Wm,{children:[g.jsx(Gm,{children:"Invite to room"}),g.jsxs(d0,{children:["Agent room membership is managed via ",g.jsx("code",{children:"zooid.yaml"}),"."]})]}),!u&&g.jsx("p",{className:"rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900",children:"Agent list unavailable — search may include agents until the workforce roster publishes."}),g.jsxs(WL,{shouldFilter:!1,children:[g.jsx(qL,{placeholder:"Search users…",value:i,onValueChange:o,autoFocus:!0}),g.jsxs(GL,{children:[g.jsx(HL,{children:i.trim()?"No users found.":"Type to search."}),g.jsx(zL,{children:p.map(E=>g.jsxs(YL,{value:`${E.displayName??E.userId} ${E.userId}`,onSelect:()=>a(E.userId),"data-selected":s===E.userId||void 0,children:[g.jsx("span",{className:"flex-1 truncate",children:E.displayName??E.userId}),g.jsx("span",{className:"text-xs text-muted-foreground",children:E.userId})]},E.userId))})]})]}),g.jsxs(qm,{children:[g.jsx(At,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),g.jsx(At,{onClick:m,disabled:!s||l,children:"Invite"})]})]})})}const KQ={presence:"offline",statusMsg:null};function UI(r){var t;const e=(t=de.safeGet())==null?void 0:t.getUser(r);return e?{presence:e.presence??"offline",statusMsg:e.presenceStatusMsg??null}:KQ}function iU(r){const[e,t]=_.useState(()=>UI(r));return _.useEffect(()=>{const n=de.safeGet();if(!n)return;const i=()=>t(UI(r)),o=n.getUser(r);o&&o.on(ar.Presence,i);const s=(a,l)=>{l.userId===r&&i()};return n.on(ar.Presence,s),()=>{o==null||o.off(ar.Presence,i),n.off(ar.Presence,s)}},[r]),e}const M_="m.room.power_levels";function jI(r){var d;const e=de.safeGet(),t=e==null?void 0:e.getRoom(r),n=e==null?void 0:e.getUserId();if(!e||!t||!n)throw new Error("no room/client");const i=t.currentState.getStateEvents(V.RoomPowerLevels,""),o={...(i==null?void 0:i.getContent())??{}},s={...o.users??{}},a=o.users_default??0,l=o.state_default??50,c=s[n]??a,u=((d=o.events)==null?void 0:d[M_])??l;return{client:e,roomId:r,me:n,content:o,users:s,usersDefault:a,myLevel:c,plGate:u}}function FI(r,e,t){if(r.myLevel<r.plGate)throw new Error("insufficient power to edit roles");if(t>r.myLevel)throw new Error("cannot set a level above your own");if(e!==r.me&&(r.users[e]??r.usersDefault)>=r.myLevel)throw new Error("cannot re-role a peer at or above you")}function VQ(r){const e=_.useCallback(async(n,i)=>{const o=jI(r);FI(o,n,i);const s={...o.users,[n]:i};await o.client.sendStateEvent(r,M_,{...o.content,users:s},"")},[r]),t=_.useCallback(async n=>{const i=jI(r);FI(i,n,i.usersDefault);const o={...i.users};delete o[n],await i.client.sendStateEvent(r,M_,{...i.content,users:o},"")},[r]);return{setLevel:e,resetToDefault:t}}function $Q({roomId:r,userId:e}){var f;const{presence:t}=iU(e),n=$o(e,r),i=f0(r),o=Df(r),s=(f=de.safeGet())==null?void 0:f.getUserId(),a=i.find(p=>p.userId===e),l=(a==null?void 0:a.role)??rU(0),c=o.canSendStateEvent("m.room.power_levels"),u=(a==null?void 0:a.powerLevel)??0,d=c&&(e===s?!0:u<o.level);return g.jsxs(g.Fragment,{children:[g.jsx(l0,{userId:e,size:"sm",presence:t}),g.jsx("span",{className:"text-sm truncate flex-1",children:n}),d?g.jsx(WQ,{roomId:r,userId:e,role:l,viewerLevel:o.level}):g.jsx("span",{className:"text-xs text-muted-foreground",children:wv(l)})]})}function WQ({roomId:r,userId:e,role:t,viewerLevel:n}){const{setLevel:i,resetToDefault:o}=VQ(r),s=DQ(n),a=async l=>{try{l==="0"?await o(e):await i(e,Number(l))}catch{}};return g.jsxs(Pf,{children:[g.jsx(Mf,{asChild:!0,children:g.jsx(At,{variant:"ghost",size:"sm",className:"h-6 px-1 text-xs",children:wv(t)})}),g.jsx(Af,{align:"end",children:g.jsxs(xX,{value:String(t.level),onValueChange:a,children:[s.map(l=>g.jsx(xI,{value:String(l.level),disabled:l.disabled,children:l.label},l.kind)),t.kind==="custom"&&g.jsx(xI,{value:String(t.level),disabled:!0,children:wv(t)})]})})]})}function qQ({roomId:r,spaceId:e}){var c,u,d;const t=f0(r),n=Df(r),[i,o]=_.useState(!1),s=(c=de.safeGet())==null?void 0:c.getRoom(r),a=((d=(u=s==null?void 0:s.currentState.getStateEvents("m.room.power_levels",""))==null?void 0:u.getContent())==null?void 0:d.invite)??50,l=n.level>=a;return g.jsxs("aside",{className:"flex h-full w-64 shrink-0 flex-col border-l border-border bg-background",children:[g.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[l&&e&&g.jsx(At,{variant:"outline",size:"sm",className:"mb-3 w-full",onClick:()=>o(!0),children:"Invite"}),g.jsx("div",{className:"space-y-4",children:LQ(t).map(f=>g.jsxs("section",{children:[g.jsxs("h3",{className:"mb-1 px-1 text-xs font-medium text-muted-foreground",children:[f.label," · ",f.members.length]}),g.jsx("ul",{className:"space-y-1",children:f.members.map(p=>g.jsx("li",{className:"flex items-center gap-2 py-0.5",children:g.jsx($Q,{roomId:r,userId:p.userId})},p.userId))})]},f.kind))})]}),e&&g.jsx(BQ,{open:i,roomId:r,spaceId:e,onOpenChange:o})]})}function GQ({open:r,roomId:e,currentName:t,onOpenChange:n}){const[i,o]=_.useState(t),[s,a]=_.useState(!1),[l,c]=_.useState(null);_.useEffect(()=>{r&&(o(t),c(null),a(!1))},[r,t]);const u=i.trim(),d=u.length>0&&u!==t&&!s,f=async()=>{const p=de.safeGet();if(p){a(!0),c(null);try{await p.setRoomName(e,u),n(!1)}catch(h){c(h instanceof Error?h.message:String(h)),a(!1)}}};return g.jsx(Vm,{open:r,onOpenChange:n,children:g.jsxs($m,{className:"sm:max-w-md",children:[g.jsx(Wm,{children:g.jsx(Gm,{children:"Rename room"})}),g.jsxs("div",{className:"space-y-2",children:[g.jsx(Zd,{htmlFor:"room-name",children:"Room name"}),g.jsx(Qd,{id:"room-name",value:i,onChange:p=>o(p.target.value),maxLength:256,autoFocus:!0}),l&&g.jsx("div",{role:"alert",className:"text-sm text-destructive",children:l})]}),g.jsxs(qm,{children:[g.jsx(At,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),g.jsx(At,{onClick:()=>void f(),disabled:!d,children:"Save"})]})]})})}function HQ({membersOpen:r,onToggleMembers:e}){const t=zP("/room/:roomId"),n=t==null?void 0:t.params.roomId,i=_.useSyncExternalStore(h=>de.subscribe(h),()=>de.safeGet(),()=>null),o=f0(n??""),s=Df(n??""),{isFavorite:a,toggle:l}=QL(n??""),[c,u]=_.useState(!1);if(!n||!i)return null;const d=i.getRoom(n),f=(d==null?void 0:d.name)??n,p=s.canSendStateEvent("m.room.name");return g.jsxs(g.Fragment,{children:[p?g.jsxs(Pf,{children:[g.jsx(Mf,{asChild:!0,children:g.jsxs(At,{variant:"ghost",size:"sm","aria-label":"Room actions",className:"h-7 max-w-48 gap-1 truncate px-1.5 text-sm font-medium",children:[g.jsx("span",{className:"truncate",children:f}),g.jsx(oM,{className:"size-3.5 text-muted-foreground"})]})}),g.jsx(Af,{align:"start",children:g.jsx(Oa,{onSelect:()=>u(!0),children:"Rename room"})})]}):g.jsx("span",{className:"text-sm font-medium truncate max-w-48",children:f}),g.jsx(At,{variant:"ghost",size:"icon","aria-label":a?"Remove from favorites":"Add to favorites",onClick:()=>void l(),className:"size-6 text-muted-foreground hover:text-foreground",children:g.jsx(WK,{className:`size-3.5 ${a?"fill-current text-amber-500":""}`})}),o.length>0&&g.jsxs(At,{variant:"ghost",size:"sm","aria-pressed":r,onClick:e,className:`h-6 px-1.5 text-xs ${r?"bg-accent text-accent-foreground":"text-muted-foreground"}`,children:[o.length," member",o.length!==1?"s":""]}),g.jsx(GQ,{open:c,roomId:n,currentName:f,onOpenChange:u})]})}const h0=[];let Ih=h0;function zQ(){var t;const e=(((t=de.safeGet())==null?void 0:t.getRooms())??h0).filter(n=>n.isSpaceRoom());return Ih.length===e.length&&Ih.every((n,i)=>n===e[i])?Ih:(Ih=e,e)}function YQ(){return _.useSyncExternalStore(r=>{const e=de.safeGet();if(!e)return de.subscribe(r);const t=()=>r();e.on(be.Room,t),e.on(be.DeleteRoom,t);const n=de.subscribe(r);return()=>{e.off(be.Room,t),e.off(be.DeleteRoom,t),n()}},zQ,()=>h0)}function JQ({scope:r,onSelect:e}){const t=YQ(),n=r.kind==="space"?t.find(o=>o.roomId===r.spaceId):void 0,i=r.kind==="home"?"Home":(n==null?void 0:n.name)??"Space";return g.jsxs(Pf,{children:[g.jsxs(Mf,{"aria-label":"switch space",className:"flex h-8 w-full items-center justify-between gap-2 rounded-md px-2 text-sm font-medium hover:bg-sidebar-accent",children:[g.jsx("span",{className:"truncate",children:i}),g.jsx(pK,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),g.jsxs(Af,{align:"start",className:"w-56",children:[g.jsx(Oa,{onSelect:()=>e({kind:"home"}),children:"Home"}),t.length>0?g.jsx(OL,{}):null,t.map(o=>g.jsx(Oa,{onSelect:()=>e({kind:"space",spaceId:o.roomId}),children:o.name??o.roomId},o.roomId))]})]})}function XQ(){const r=PL(),e=r.getUserId()??"",t=$o(e),n=e.split(":")[1]??e,i="dev",{spaceId:o}=OX(i,n),[s,a]=_.useState(null),[l,c]=_.useState(!1),u=zP("/room/:roomId"),d=(u==null?void 0:u.params.roomId)??null;_.useEffect(()=>{r.startClient({initialSyncLimit:10}).catch(()=>{})},[r]),_.useEffect(()=>{s||o&&a({kind:"space",spaceId:o})},[o,s]);const f=s??(o?{kind:"space",spaceId:o}:{kind:"home"});return g.jsxs(HJ,{className:"h-svh overflow-hidden",children:[g.jsxs(zJ,{collapsible:"icon",children:[g.jsx(XJ,{className:"h-12 flex-row items-center border-b border-sidebar-border px-2",children:g.jsx(JQ,{scope:f,onSelect:a})}),g.jsx(QJ,{children:g.jsx(MQ,{scope:f,workforceSpaceId:o})})]}),g.jsxs(JJ,{"data-testid":"logged-in-view",children:[g.jsxs("header",{className:"flex items-center justify-between border-b border-border px-4 h-12",children:[g.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[g.jsx(YJ,{"aria-label":"Toggle sidebar"}),g.jsx(HQ,{membersOpen:l,onToggleMembers:()=>c(p=>!p)})]}),g.jsxs(Pf,{children:[g.jsx(Mf,{asChild:!0,children:g.jsx(At,{variant:"ghost",size:"icon","aria-label":"User menu",className:"shrink-0",children:g.jsx(l0,{userId:e,size:"sm"})})}),g.jsxs(Af,{align:"end",className:"w-48",children:[g.jsx(Oa,{disabled:!0,className:"font-medium",children:t}),g.jsx(Oa,{disabled:!0,className:"text-xs text-muted-foreground",children:e}),g.jsx(OL,{}),g.jsx(Oa,{onSelect:()=>de.reset(),children:"Log out"})]})]})]}),g.jsx("main",{className:"flex-1 min-h-0 overflow-hidden",children:g.jsxs("div",{className:"flex h-full min-h-0",children:[g.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:g.jsx(dB,{context:{spaceId:o}})}),l&&d&&g.jsx(qQ,{roomId:d,spaceId:o})]})})]})]})}const oU=[{names:["clear","new"],description:"Reset the agent's memory of this thread",threadScopedOnly:!0,build:()=>({eventType:"eco.zoon.session_reset",content:{}})},{names:["interrupt","stop"],description:"Stop the agent's current turn in this thread",threadScopedOnly:!0,build:r=>({eventType:"eco.zoon.interrupt",content:r?{reason:r}:{}})}];function QQ(r,e={threadScoped:!1}){if(!r.startsWith("/"))return null;const t=r.indexOf(" "),n=(t===-1?r.slice(1):r.slice(1,t)).toLowerCase(),i=t===-1?"":r.slice(t+1).trim();for(const o of oU)if(o.names.includes(n))return o.threadScopedOnly&&!e.threadScoped?null:o.build(i);return null}function ZQ(r={threadScoped:!1}){return oU.flatMap(e=>e.threadScopedOnly&&!r.threadScoped?[]:e.names.map(t=>({name:t,description:e.description})))}const sU=[],BI=new WeakMap;function eZ(r){var i;const e=(i=de.safeGet())==null?void 0:i.getRoom(r);if(!e)return sU;const t=e.getJoinedMembers(),n=BI.get(e);return n&&n.length===t.length&&n.every((o,s)=>o===t[s])?n:(BI.set(e,t),t)}function tZ(r){return _.useSyncExternalStore(e=>{const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return de.subscribe(e);const i=()=>e();n.currentState.on(Me.Members,i);const o=de.subscribe(e);return()=>{n.currentState.off(Me.Members,i),o()}},()=>eZ(r),()=>sU)}const aU={events:[],pendingRootIds:[]},lU={events:[],totalCount:0},cU={root:void 0,rootPending:!1,events:[],totalCount:0},KI=new WeakMap,VI=new Map,$I=new Map,ef=new Map,Dy=new Set,WI=new Set,A_=new Set;function rZ(){for(const r of A_)r()}function uU(r,e,t){const n=`${e}:${t}`;ef.has(t)||Dy.has(n)||WI.has(n)||(Dy.add(n),r.fetchRoomEvent(e,t).then(i=>{ef.set(t,new pr(i)),rZ()}).catch(i=>{console.warn(`[useTimeline] fetchRoomEvent(${e}, ${t}) failed:`,i),WI.add(n)}).finally(()=>{Dy.delete(n)}))}function Lf(r){const e=r.getUnfilteredTimelineSet(),t=new Set,n=[];for(const i of e.getTimelines())for(const o of i.getEvents()){const s=o.getId()??`${o.getType()}-${o.getTs()}`;t.has(s)||(t.add(s),n.push(o))}return n.sort((i,o)=>i.getTs()-o.getTs()),n}function nZ(r){var u;const e=de.safeGet(),t=e==null?void 0:e.getRoom(r);if(!e||!t)return aU;const n=Lf(t),i=new Set,o=new Set,s=[];for(const d of n){const f=d.getId();f&&i.add(f);const p=(u=d.getContent())==null?void 0:u["m.relates_to"];(p==null?void 0:p.rel_type)==="m.thread"?p.event_id&&o.add(p.event_id):s.push(d)}const a=[];for(const d of o){if(i.has(d))continue;const f=ef.get(d);if(f){s.push(f);continue}const p=t.findEventById(d);if(p){s.push(p);continue}uU(e,r,d),a.push(d)}s.sort((d,f)=>d.getTs()-f.getTs());const l=KI.get(t);if(l&&l.events.length===s.length&&l.events[s.length-1]===s[s.length-1]&&l.pendingRootIds.length===a.length&&l.pendingRootIds.every((d,f)=>d===a[f]))return l;const c={events:s,pendingRootIds:a};return KI.set(t,c),c}function iZ(r,e){var p,h;const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return lU;const i=Lf(n),o=i.find(m=>m.getId()===e)??ef.get(e)??n.findEventById(e),s=o==null?void 0:o.getUnsigned(),a=((h=(p=s==null?void 0:s["m.relations"])==null?void 0:p["m.thread"])==null?void 0:h.count)??0,l=i.filter(m=>{var y;const E=(y=m.getContent())==null?void 0:y["m.relates_to"];return(E==null?void 0:E.rel_type)==="m.thread"&&E.event_id===e}),c=Math.max(a,l.length),u=`${r}:${e}`,d=VI.get(u);if(d&&d.replyCount===l.length&&d.totalCount===c)return d.state;const f={events:l.slice(-3),totalCount:c};return VI.set(u,{replyCount:l.length,totalCount:c,state:f}),f}function oZ(r,e){var h,m;const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!t||!n)return cU;const i=Lf(n),o=i.find(E=>E.getId()===e)??ef.get(e)??n.findEventById(e);let s=!1;o||(uU(t,r,e),s=!0);const a=o==null?void 0:o.getUnsigned(),l=((m=(h=a==null?void 0:a["m.relations"])==null?void 0:h["m.thread"])==null?void 0:m.count)??0,c=i.filter(E=>{var S;const y=(S=E.getContent())==null?void 0:S["m.relates_to"];return(y==null?void 0:y.rel_type)==="m.thread"&&y.event_id===e}),u=Math.max(l,c.length),d=`${r}:${e}`,f=$I.get(d);if(f&&f.replyCount===c.length&&f.totalCount===u&&f.root===o&&f.rootPending===s)return f.state;const p={root:o,rootPending:s,events:c,totalCount:u};return $I.set(d,{replyCount:c.length,totalCount:u,root:o,rootPending:s,state:p}),p}function Uf(r){return e=>{const t=de.safeGet();if(!t)return de.subscribe(e);const n=(a,l)=>{(l==null?void 0:l.roomId)===r&&e()},i=a=>{a.roomId===r&&e()};t.on(pe.Timeline,n),t.on(be.Room,i);const o=t.getRoom(r);o==null||o.on(pe.Timeline,n),A_.add(e);const s=de.subscribe(e);return()=>{t.off(pe.Timeline,n),t.off(be.Room,i),o==null||o.off(pe.Timeline,n),A_.delete(e),s()}}}function dU(r){return _.useSyncExternalStore(Uf(r),()=>nZ(r),()=>aU)}function fU(r,e){return _.useSyncExternalStore(Uf(r),()=>iZ(r,e),()=>lU)}function sZ(r,e){return _.useSyncExternalStore(Uf(r),()=>oZ(r,e),()=>cU)}const hU={status:null,content:null,rawInput:null,latestUpdateTs:0},qI=new Map;function aZ(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function lZ(r,e){const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return hU;const i=Lf(n);let o=-1,s=null,a=null,l=null;const c=[];for(const h of i){const m=h.getType();m!=="eco.zoon.tool_call"&&m!=="eco.zoon.tool_call_update"||h.getContent().tool_call_id!==e||c.push({ts:h.getTs(),ev:h})}c.sort((h,m)=>h.ts-m.ts);for(const{ts:h,ev:m}of c){const E=m.getType(),y=m.getContent();aZ(y.raw_input)&&(l={...l??{},...y.raw_input}),E==="eco.zoon.tool_call_update"&&typeof y.status=="string"&&h>=o&&(o=h,s=y.status,a=typeof y.content=="string"?y.content:null)}const u=l?JSON.stringify(l):"",d=`${r}:${e}`,f=qI.get(d);if(f&&f.ts===o&&f.status===s&&f.rawInputKey===u)return f.result;const p={status:s,content:a,rawInput:l,latestUpdateTs:o>0?o:0};return qI.set(d,{ts:o,status:s,rawInputKey:u,result:p}),p}function cZ(r,e){return _.useSyncExternalStore(Uf(r),()=>lZ(r,e),()=>hU)}const mp={toolInput:null,toolKind:null,toolTitle:null},Ny=new Map;function uZ(r,e){const t=de.safeGet(),n=t==null?void 0:t.getRoom(r);if(!n)return mp;const i=Lf(n);let o;for(const d of i){if(d.getType()!=="eco.zoon.approval_request")continue;if(d.getContent().tool_call_id===e){o=d;break}}const s=`${r}:${e}`,a=Ny.get(s),l=o==null?void 0:o.getId();if(a&&a.eventId===l)return a.result;if(!o)return Ny.set(s,{eventId:void 0,result:mp}),mp;const c=o.getContent(),u={toolInput:c.tool_input&&typeof c.tool_input=="object"&&!Array.isArray(c.tool_input)?c.tool_input:null,toolKind:typeof c.tool_kind=="string"?c.tool_kind:null,toolTitle:typeof c.tool_title=="string"?c.tool_title:null};return Ny.set(s,{eventId:l,result:u}),u}function dZ(r,e){return _.useSyncExternalStore(Uf(r),()=>uZ(r,e),()=>mp)}const fZ="field-sizing-content min-h-9 flex-1 bg-transparent px-2.5 py-2 text-base outline-none placeholder:text-muted-foreground resize-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",hZ="flex items-center rounded-lg border border-input bg-transparent transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30 pr-1.5";function pZ(r,e){const t=r.replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"…":t}function vZ({roomId:r,threadRootEventId:e,onExitThread:t}){const n=PL(),[i,o]=_.useState(""),[s,a]=_.useState(null),[l,c]=_.useState(null),[u,d]=_.useState(0),f=_.useRef(null),p=!!e,h=e??null,E=fU(r,e??"").events.at(-1),y=_.useMemo(()=>{var oe;if(E)return E.getContent().body??"";if(!e)return"";const $=n==null?void 0:n.getRoom(r),X=$==null?void 0:$.getLiveTimeline().getEvents().find(re=>re.getId()===e);return((oe=X==null?void 0:X.getContent())==null?void 0:oe.body)??""},[E,e,n,r]),S=tZ(r),R=_.useMemo(()=>S.map($=>({userId:$.userId,name:ML($)})),[S]),k=_.useMemo(()=>ZQ({threadScoped:p}),[p]),x=_.useMemo(()=>{if(!l||l.mode!=="mention")return[];const $=l.query.toLowerCase();return R.filter(X=>X.userId.toLowerCase().includes($)||X.name.toLowerCase().includes($)).slice(0,8)},[l,R]),T=_.useMemo(()=>{if(!l||l.mode!=="slash")return[];const $=l.query.toLowerCase();return $?k.filter(X=>X.name.startsWith($)||X.description.toLowerCase().includes($)):k},[l,k]),O=(l==null?void 0:l.mode)==="slash"?T:x;function C($,X){if($.startsWith("/")&&X>0&&!$.includes(" ")){const re=$.slice(1,X);c(ae=>(ae==null?void 0:ae.mode)==="slash"&&ae.query===re?ae:(((ae==null?void 0:ae.mode)!=="slash"||ae.query!==re)&&d(0),{mode:"slash",start:0,query:re}));return}let oe=X-1;for(;oe>=0;){const re=$[oe];if(re==="@"){if(oe===0||/\s/.test($[oe-1])){const ae=$.slice(oe+1,X);if(!/\s/.test(ae)&&!ae.includes(":")){c(q=>(q==null?void 0:q.mode)==="mention"&&q.start===oe&&q.query===ae?q:(d(0),{mode:"mention",start:oe,query:ae}));return}}break}if(/\s/.test(re))break;oe--}c(null)}function N($){if(!l)return;const X=i.slice(0,l.start),oe=i.slice(l.start+1+l.query.length),re=`@${xc($.userId)} `,ae=X+re+oe;o(ae),c(null),requestAnimationFrame(()=>{const q=f.current;if(!q)return;const z=X.length+re.length;q.focus(),q.setSelectionRange(z,z)})}function F($){const X=`/${$.name} `;o(X),c(null),requestAnimationFrame(()=>{const oe=f.current;oe&&(oe.focus(),oe.setSelectionRange(X.length,X.length))})}async function H(){const $=i.trim();if($){a(null);try{const X=QQ($,{threadScoped:p});if(X){const q=h?{...X.content,"m.relates_to":{rel_type:"m.thread",event_id:h}}:X.content;await n.sendEvent.call(n,r,h,X.eventType,q),o("");return}const{body:oe,userIds:re}=MX($,R),ae={msgtype:"m.text",body:oe};re.length>0&&(ae["m.mentions"]={user_ids:re}),await n.sendEvent.call(n,r,h,"m.room.message",ae),o("")}catch(X){a(X instanceof Error?X.message:String(X))}}}const ie=async $=>{if(l&&O.length>0){if($.key==="ArrowDown"){$.preventDefault(),d(X=>(X+1)%O.length);return}if($.key==="ArrowUp"){$.preventDefault(),d(X=>(X-1+O.length)%O.length);return}if($.key==="Enter"||$.key==="Tab"){if($.preventDefault(),l.mode==="slash"){const X=T[u];X&&$.key==="Enter"&&i.trim()===`/${X.name}`?(c(null),await H()):F(X)}else N(x[u]);return}if($.key==="Escape"){$.preventDefault(),c(null);return}}$.key!=="Enter"||$.shiftKey||($.preventDefault(),await H())};return g.jsxs("div",{className:"relative shrink-0 border-t border-border p-3",children:[s&&g.jsx("div",{role:"alert",className:"mb-2 text-sm text-destructive",children:s}),e&&g.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-2 min-w-0",children:[y?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"shrink-0",children:"Replying to"}),g.jsxs("span",{className:"truncate italic text-foreground/70",children:['"',pZ(y,60),'"']})]}):g.jsx("span",{className:"shrink-0",children:"Replying in current thread"}),g.jsx("button",{type:"button","aria-label":"Exit thread",onClick:()=>t==null?void 0:t(),className:"ml-auto shrink-0 rounded px-2 py-1 hover:bg-muted",children:"Cancel"})]}),l&&O.length>0&&g.jsx("ul",{role:"listbox","aria-label":l.mode==="slash"?"Command suggestions":"Mention suggestions",className:"absolute bottom-full left-3 right-3 mb-1 max-h-56 overflow-auto rounded-md border border-border bg-popover p-1 shadow-lg",children:l.mode==="slash"?T.map(($,X)=>g.jsxs("li",{role:"option","aria-selected":X===u,onMouseDown:oe=>{oe.preventDefault(),F($)},onMouseEnter:()=>d(X),className:"flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 text-sm "+(X===u?"bg-accent text-accent-foreground":""),children:[g.jsxs("span",{className:"font-mono font-semibold text-primary",children:["/",$.name]}),g.jsx("span",{className:"text-xs text-muted-foreground",children:$.description})]},$.name)):x.map(($,X)=>g.jsxs("li",{role:"option","aria-selected":X===u,onMouseDown:oe=>{oe.preventDefault(),N($)},onMouseEnter:()=>d(X),className:"flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1 text-sm "+(X===u?"bg-accent text-accent-foreground":""),children:[g.jsx("span",{className:"font-semibold",style:{color:$a($.userId)},children:$.name}),g.jsx("span",{className:"text-xs text-muted-foreground",children:$.userId})]},$.userId))}),g.jsxs("div",{className:hZ,children:[g.jsx("textarea",{ref:f,"data-slot":"textarea","aria-label":"Message",placeholder:"Send a message…",value:i,onChange:$=>{o($.target.value),C($.target.value,$.target.selectionStart)},onKeyUp:$=>{if(!(l&&($.key==="ArrowDown"||$.key==="ArrowUp"))&&($.key.startsWith("Arrow")||$.key==="Home"||$.key==="End")){const X=$.currentTarget;C(X.value,X.selectionStart)}},onClick:$=>{const X=$.currentTarget;C(X.value,X.selectionStart)},onBlur:()=>c(null),onKeyDown:ie,rows:1,className:Le(fZ)}),g.jsx("button",{type:"button",onClick:()=>void H(),disabled:!i.trim(),"aria-label":"Send message",className:"shrink-0 self-center rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40",children:g.jsx(BK,{className:"h-4 w-4"})})]})]})}function mZ({userId:r,roomId:e}){return g.jsx("span",{style:{color:$a(r)},children:$o(r,e)})}function gZ({typingUserIds:r,roomId:e}){if(r.length===0)return g.jsx("div",{className:"h-5","aria-hidden":!0});const t=2,n=r.slice(0,t),i=r.length-t;let o;i>0?o=` and ${i} other${i>1?"s":""} are typing…`:r.length===1?o=" is typing…":o=" are typing…";const s=[];return n.forEach((a,l)=>{l>0&&s.push(", "),s.push(g.jsx(mZ,{userId:a,roomId:e},a))}),g.jsxs("div",{className:"h-5 px-3 text-xs text-muted-foreground leading-5",children:[s,o]})}function yZ(r,e,t=50){const[n,i]=_.useState(!1);return{loadMore:_.useCallback(async()=>{if(n)return;const s=de.safeGet(),a=s==null?void 0:s.getRoom(r),l=(a==null?void 0:a.getThread(e))??null;if(!(!s||!l)){i(!0);try{await s.paginateEventTimeline(l.liveTimeline,{backwards:!0,limit:t})}catch(c){console.warn(`[useLoadMoreThread] paginate(${r}, ${e}) failed:`,c)}finally{i(!1)}}},[r,e,t,n]),loading:n}}const Oc={Request:"eco.zoon.approval_request",Response:"eco.zoon.approval_response"};function pU(r){if(r.getType()!==Oc.Request)return null;const e=r.getContent();if(typeof e.approval_id!="string"||typeof e.session_id!="string"||typeof e.tool_call_id!="string")return null;const n=(Array.isArray(e.options)?e.options:[]).map(i=>{if(!i||typeof i!="object")return null;const o=i,s=typeof o.optionId=="string"?o.optionId:typeof o.id=="string"?o.id:null,a=typeof o.name=="string"?o.name:typeof o.label=="string"?o.label:null,l=typeof o.kind=="string"?o.kind:"";return!s||!a?null:{optionId:s,name:a,kind:l}}).filter(i=>i!==null);return{approvalId:e.approval_id,sessionId:e.session_id,toolCallId:e.tool_call_id,toolKind:typeof e.tool_kind=="string"?e.tool_kind:void 0,toolTitle:typeof e.tool_title=="string"?e.tool_title:void 0,toolInput:e.tool_input,options:n}}function SZ(r){if(r.getType()!==Oc.Response)return null;const e=r.getContent();return typeof e.approval_id!="string"||e.decision!=="allow"&&e.decision!=="cancel"?null:{approvalId:e.approval_id,decision:e.decision,optionId:typeof e.option_id=="string"?e.option_id:void 0,respondedBy:r.getSender()??"?"}}function bZ(r,e){for(const t of r){const n=SZ(t);if(n&&n.approvalId===e)return n}return null}const Vi={SessionStart:"eco.zoon.session.start",TurnStart:"eco.zoon.turn.start",AgentMessageChunk:"eco.zoon.agent_message_chunk",ToolCall:"eco.zoon.tool_call",ToolCallUpdate:"eco.zoon.tool_call_update",Plan:"eco.zoon.plan",TurnEnd:"eco.zoon.turn.end",Error:"eco.zoon.error"},_Z=new Set(Object.values(Vi));function EZ(r){return _Z.has(r.getType())}function wZ(r){const e=r.getContent(),t=r.getType();if(t===Vi.Error)return typeof e.code!="string"||typeof e.message!="string"?null:{kind:"error",sessionId:typeof e.session_id=="string"?e.session_id:null,turnId:typeof e.turn_id=="string"?e.turn_id:null,code:e.code,message:e.message,detail:typeof e.detail=="string"?e.detail:void 0,transient:e.transient===!0,acpError:e.acp_error&&typeof e.acp_error=="object"?e.acp_error:void 0,recovery:typeof e.recovery=="string"?e.recovery:void 0};const n=typeof e.session_id=="string"?e.session_id:null;if(!n)return null;switch(t){case Vi.SessionStart:return{kind:"session.start",sessionId:n};case Vi.TurnStart:return{kind:"turn.start",sessionId:n};case Vi.AgentMessageChunk:return typeof e.content!="string"?null:{kind:"agent_message_chunk",sessionId:n,content:e.content};case Vi.ToolCall:{const i=typeof e.tool_call_id=="string"?e.tool_call_id:null,o=typeof e.title=="string"?e.title:null,s=typeof e.kind=="string"?e.kind:null;return!i||!o||!s?null:{kind:"tool_call",sessionId:n,toolCallId:i,title:o,toolKind:s,rawInput:GI(e.raw_input),locations:HI(e.locations)}}case Vi.ToolCallUpdate:{const i=typeof e.tool_call_id=="string"?e.tool_call_id:null,o=typeof e.status=="string"?e.status:null;return!i||!o?null:{kind:"tool_call_update",sessionId:n,toolCallId:i,status:o,content:TZ(e.content),rawInput:GI(e.raw_input),locations:HI(e.locations)}}case Vi.Plan:{if(!Array.isArray(e.entries))return null;const i=e.entries.map(o=>{if(!o||typeof o!="object")return null;const s=o;return typeof s.id!="string"||typeof s.title!="string"||typeof s.status!="string"?null:{id:s.id,title:s.title,status:s.status}}).filter(o=>o!==null);return{kind:"plan",sessionId:n,entries:i}}case Vi.TurnEnd:return{kind:"turn.end",sessionId:n,stopReason:typeof e.stop_reason=="string"?e.stop_reason:void 0};default:return null}}function GI(r){if(r&&typeof r=="object"&&!Array.isArray(r))return r}function HI(r){if(!Array.isArray(r)||r.length===0)return;const e=[];for(const t of r)if(t&&typeof t=="object"){const n=t;typeof n.path=="string"&&e.push({path:n.path,line:typeof n.line=="number"?n.line:void 0})}return e.length>0?e:void 0}function TZ(r){if(typeof r=="string")return r;if(!Array.isArray(r)||r.length===0)return;const e=[];for(const t of r){if(!t||typeof t!="object")continue;const n=t;if(n.type==="content"&&n.content&&typeof n.content=="object"){const i=n.content;i.type==="text"&&typeof i.text=="string"&&e.push(i.text)}}return e.length>0?e.join(`
301
- `):void 0}function RZ(r){const e=pU(r),t=r.getRoomId()??"",{events:n}=dU(t),i=e?bZ(n,e.approvalId):null,[o,s]=_.useState({sending:!1,error:null}),a=_.useRef(!1),l=_.useCallback(async(u,d)=>{if(e&&!i&&!a.current){a.current=!0,s({sending:!0,error:null});try{const f=de.get(),p={approval_id:e.approvalId,session_id:e.sessionId,decision:u};d&&(p.option_id=d),await f.sendEvent(t,Oc.Response,p),s({sending:!1,error:null})}catch(f){s({sending:!1,error:f instanceof Error?f.message:String(f)}),a.current=!1}}},[e,i,t]);let c="pending";return i?c="resolved":o.error?c="error":o.sending&&(c="sending"),{state:c,resolution:i,error:o.error,send:l}}function CZ({event:r}){const e=pU(r),t=r.getRoomId()??"",n=Df(t),{state:i,resolution:o,error:s,send:a}=RZ(r),[l,c]=_.useState(!1);if(!e)return null;const u=n.canSendEvent(Oc.Response),d=kZ(e.toolKind,e.toolTitle,e.toolInput);return i==="resolved"&&o?g.jsx(k_,{"data-testid":"approval-card",className:"my-2 max-w-xl",children:g.jsxs(I_,{children:[g.jsx(x_,{className:"text-base",children:d.title}),g.jsxs(wI,{children:[d.subtitle&&g.jsx("span",{className:"block",children:d.subtitle}),o.decision==="allow"?"Approved":"Cancelled"," by"," ",g.jsx("span",{children:o.respondedBy})]})]})}):g.jsxs(k_,{"data-testid":"approval-card",className:"my-2 max-w-xl",children:[g.jsxs(I_,{children:[g.jsx(x_,{className:"text-base",children:d.title}),d.subtitle&&g.jsx(wI,{className:"font-mono text-xs break-all",children:d.subtitle})]}),e.toolInput!==void 0&&g.jsxs(hp,{className:"pt-0",children:[g.jsx("button",{type:"button",onClick:()=>c(f=>!f),className:"text-xs text-muted-foreground hover:text-foreground","aria-expanded":l,children:l?"Hide details ▾":"Show details ▸"}),l&&g.jsx("pre",{className:"mt-2 max-h-64 overflow-auto rounded-md bg-muted/50 p-2 text-xs",children:IZ(e.toolInput)})]}),s&&g.jsx(hp,{children:g.jsx("div",{role:"alert",className:"text-destructive text-sm",children:s})}),u?g.jsx(CJ,{className:"gap-2",children:e.options.length===0?g.jsxs(g.Fragment,{children:[g.jsx(At,{type:"button",disabled:i==="sending",onClick:()=>a("allow"),children:"Allow"}),g.jsx(At,{type:"button",variant:"outline",disabled:i==="sending",onClick:()=>a("cancel"),children:"Cancel"})]}):e.options.map(f=>{const p=f.kind.startsWith("reject"),h=p?"cancel":"allow";return g.jsx(At,{type:"button",variant:p?"outline":"default",disabled:i==="sending",onClick:()=>a(h,f.optionId),children:f.name},f.optionId)})}):g.jsx(hp,{children:g.jsx("p",{className:"text-muted-foreground text-sm",children:"You have insufficient permission to respond to this approval."})})]})}function kZ(r,e,t){const n=e??r??"Tool call",i=t&&typeof t=="object"?t:null;if(r==="edit"&&i&&typeof i.filepath=="string")return{title:`Edit ${zI(i.filepath)}`,subtitle:i.filepath};if(r==="fetch"&&i&&typeof i.url=="string")return{title:"Fetch",subtitle:i.url};if(r==="execute"&&i&&typeof i.command=="string")return{title:"Run command",subtitle:i.command};if(r==="read"&&i&&typeof i.filepath=="string")return{title:`Read ${zI(i.filepath)}`,subtitle:i.filepath};if(i){const o=Object.entries(i).find(([s,a])=>typeof a=="string"&&s!=="diff"&&a.length<200);if(o)return{title:n,subtitle:String(o[1])}}return{title:n}}function zI(r){const e=r.split("/");return e[e.length-1]||r}function IZ(r){try{return JSON.stringify(r,null,2)}catch{return String(r)}}function xZ({decoded:r,sender:e,roomId:t,ts:n}){const i=$o(e,t);switch(r.kind){case"session.start":return g.jsx(YI,{text:`${i} started session`});case"turn.start":return null;case"turn.end":return g.jsx(YI,{text:`turn ended${r.stopReason?` (${r.stopReason})`:""}`});case"agent_message_chunk":return g.jsxs("div",{className:"py-1 text-sm text-foreground/80",children:[g.jsx("span",{className:"font-mono text-muted-foreground mr-2",children:i}),r.content]});case"tool_call":return g.jsx(NZ,{decoded:r,sender:e,roomId:t,ts:n});case"tool_call_update":return null;case"plan":return g.jsx(jZ,{decoded:r})}}function YI({text:r}){return g.jsxs("div",{className:"flex items-center gap-2 py-2 text-xs uppercase tracking-wider text-muted-foreground",children:[g.jsx("div",{className:"h-px flex-1 bg-border"}),g.jsx("span",{children:r}),g.jsx("div",{className:"h-px flex-1 bg-border"})]})}function OZ(r){switch(r){case"edit":return EK;case"read":return TK;case"fetch":return CK;case"execute":return cR;default:return cR}}function PZ({status:r}){return r?r==="completed"?g.jsx(FE,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):r==="failed"?g.jsx(BE,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}):r==="stalled"?g.jsx(zv,{className:"h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400","aria-label":"stalled"}):r==="in_progress"||r==="pending"?g.jsx(Hv,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):null:null}const MZ=5*60*1e3,AZ=30*1e3;function DZ(r){const[,e]=_.useState(0);_.useEffect(()=>{if(!r)return;const t=setInterval(()=>e(n=>n+1),AZ);return()=>clearInterval(t)},[r])}function NZ({decoded:r,sender:e,roomId:t,ts:n}){const[i,o]=_.useState(!1),{status:s,content:a,rawInput:l,latestUpdateTs:c}=cZ(t,r.toolCallId),u=dZ(t,r.toolCallId),d=$o(e,t),f=OZ(r.toolKind),p=r.title??r.toolKind??"Tool call",h=s===null||s==="pending"||s==="in_progress";DZ(h);const m=Math.max(n,c),E=h&&m>0&&Date.now()-m>MZ,y=E?"stalled":s??(h?"in_progress":null),S=(l&&Object.keys(l).length>0?l:u.toolInput)??void 0,R=LZ(r.toolKind,S,r.locations);return g.jsxs("div",{className:"my-1 rounded-md border border-border bg-muted/30",children:[g.jsxs("button",{type:"button",onClick:()=>o(k=>!k),"aria-expanded":i,className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-sm hover:bg-muted/50",children:[g.jsx(sM,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${i?"rotate-90":""}`}),g.jsx(f,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),g.jsx("span",{className:"font-medium",children:p}),R&&g.jsx("span",{className:"text-xs text-muted-foreground font-mono truncate",children:R}),g.jsx("span",{className:"ml-auto flex items-center gap-1.5",children:g.jsx(PZ,{status:y})})]}),i&&g.jsxs("div",{className:"border-t border-border px-2.5 py-2 text-xs text-muted-foreground space-y-1",children:[E&&g.jsxs("div",{className:"rounded-sm bg-amber-500/10 px-2 py-1 text-amber-700 dark:text-amber-400",children:["No updates for over 5 minutes — the tool may be stuck. Try",g.jsx("code",{className:"font-mono",children:" /interrupt"})," to cancel."]}),g.jsxs("div",{children:[g.jsx("span",{className:"text-foreground/70",children:"by"})," ",d]}),g.jsxs("div",{className:"font-mono break-all",children:["id: ",r.toolCallId]}),r.locations&&r.locations.length>0&&g.jsxs("div",{children:[g.jsx("span",{className:"text-foreground/70",children:"files: "}),r.locations.map((k,x)=>g.jsxs("span",{className:"font-mono break-all",children:[k.path,k.line!==void 0?`:${k.line}`:"",x<r.locations.length-1?", ":""]},x))]}),S&&Object.keys(S).length>0&&g.jsx("pre",{className:"mt-1 max-h-64 overflow-auto rounded-md bg-background/50 p-2 text-xs",children:UZ(S)}),a&&g.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words text-foreground/80",children:[g.jsx("span",{className:"text-foreground/70 block mb-0.5",children:"output:"}),a]})]})]})}function Ly(r){const e=r.split("/");return e[e.length-1]||r}function LZ(r,e,t){if(e){if(r==="edit"&&typeof e.filepath=="string"||r==="read"&&typeof e.filepath=="string")return Ly(e.filepath);if(r==="fetch"&&typeof e.url=="string")return e.url;if(r==="execute"&&typeof e.command=="string")return e.command;for(const[n,i]of Object.entries(e))if(n!=="diff"&&typeof i=="string"&&i.length<120)return i}return t&&t.length>0?Ly(t[0].path):null}function UZ(r){try{return JSON.stringify(r,null,2)}catch{return String(r)}}function jZ({decoded:r}){return g.jsxs("div",{className:"my-1 rounded-md border border-border bg-muted/30 px-2.5 py-2",children:[g.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[g.jsx(OK,{className:"h-3.5 w-3.5"}),"Plan"]}),g.jsx("ul",{className:"space-y-0.5 text-sm",children:r.entries.map(e=>g.jsxs("li",{className:"flex items-start gap-2",children:[g.jsx("span",{className:FZ(e.status),"aria-label":e.status}),g.jsx("span",{className:e.status==="completed"?"line-through text-muted-foreground":"text-foreground",children:e.title})]},e.id))})]})}function FZ(r){const e="mt-1.5 inline-block h-2 w-2 shrink-0 rounded-full ";switch(r){case"completed":return e+"bg-emerald-500";case"in_progress":return e+"bg-amber-500 animate-pulse";case"failed":return e+"bg-destructive";default:return e+"bg-muted-foreground/40"}}function BZ({decoded:r}){const e=()=>{const t={code:r.code,message:r.message};r.detail&&(t.detail=r.detail),r.acpError&&(t.acp_error=r.acpError),navigator.clipboard.writeText(JSON.stringify(t,null,2))};return g.jsx("div",{className:"my-2 rounded-md border border-border bg-muted/50 px-3 py-2 text-sm",children:g.jsxs("div",{className:"flex items-start gap-2",children:[g.jsx(zv,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),g.jsxs("div",{className:"flex-1",children:[g.jsx("div",{className:"font-medium",children:r.message}),r.detail&&g.jsxs("details",{className:"mt-1",children:[g.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground",children:"details"}),g.jsx("pre",{className:"mt-1 max-h-48 overflow-auto whitespace-pre-wrap text-xs",children:r.detail})]}),g.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-xs",children:[g.jsx("button",{type:"button",className:"rounded border border-border px-2 py-0.5 hover:bg-accent",onClick:e,children:"Copy details"}),r.recovery&&g.jsx("a",{href:r.recovery,target:"_blank",rel:"noreferrer",className:"rounded border border-border px-2 py-0.5 hover:bg-accent",children:"Learn more"})]})]})]})})}const Bu=new Map,Uy=new Map;function KZ(r,e){return`${r} ${e}`}function VZ(r,e){if(r.size!==e.size)return!1;for(const[t,n]of r){const i=e.get(t);if(!i||i.count!==n.count||i.mine!==n.mine||i.myEventId!==n.myEventId)return!1}return!0}function $Z(r,e){var c;const t=KZ(r,e),n=Uy.get(t)??Bu,i=de.safeGet(),o=i==null?void 0:i.getRoom(r);if(!i||!o)return n!==Bu&&Uy.set(t,Bu),Bu;const s=i.getSafeUserId(),a=new Map,l=o.getLiveTimeline().getEvents();for(const u of l){if(u.getType()!=="m.reaction"||(c=u.isRedacted)!=null&&c.call(u))continue;const f=u.getContent()["m.relates_to"];if((f==null?void 0:f.rel_type)!=="m.annotation"||f.event_id!==e)continue;const p=f.key??"";if(!p)continue;const h=u.getSender(),m=a.get(p)??{count:0,mine:!1,myEventId:void 0};m.count+=1,h===s&&(m.mine=!0,m.myEventId=u.getId()??m.myEventId),a.set(p,m)}return VZ(n,a)?n:(Uy.set(t,a),a)}function WZ(r,e){return _.useSyncExternalStore(t=>{const n=de.safeGet(),i=n==null?void 0:n.getRoom(r);if(!i)return de.subscribe(t);const o=()=>t();i.on(pe.Timeline,o),i.on(pe.Redaction,o);const s=de.subscribe(t);return()=>{i.off(pe.Timeline,o),i.off(pe.Redaction,o),s()}},()=>$Z(r,e),()=>Bu)}/*! @license DOMPurify 3.4.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.5/LICENSE */function JI(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function qZ(r){if(Array.isArray(r))return r}function GZ(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,o,s,a=[],l=!0,c=!1;try{if(o=(t=t.call(r)).next,e!==0)for(;!(l=(n=o.call(t)).done)&&(a.push(n.value),a.length!==e);l=!0);}catch(u){c=!0,i=u}finally{try{if(!l&&t.return!=null&&(s=t.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function HZ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
302
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function zZ(r,e){return qZ(r)||GZ(r,e)||YZ(r,e)||HZ()}function YZ(r,e){if(r){if(typeof r=="string")return JI(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?JI(r,e):void 0}}const vU=Object.entries,XI=Object.setPrototypeOf,JZ=Object.isFrozen,XZ=Object.getPrototypeOf,QZ=Object.getOwnPropertyDescriptor;let nn=Object.freeze,ti=Object.seal,Cl=Object.create,mU=typeof Reflect<"u"&&Reflect,D_=mU.apply,N_=mU.construct;nn||(nn=function(e){return e});ti||(ti=function(e){return e});D_||(D_=function(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;o<n;o++)i[o-2]=arguments[o];return e.apply(t,i)});N_||(N_=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return new e(...n)});const vl=ir(Array.prototype.forEach),ZZ=ir(Array.prototype.lastIndexOf),QI=ir(Array.prototype.pop),ml=ir(Array.prototype.push),eee=ir(Array.prototype.splice),Yr=Array.isArray,Ku=ir(String.prototype.toLowerCase),jy=ir(String.prototype.toString),ZI=ir(String.prototype.match),gl=ir(String.prototype.replace),ex=ir(String.prototype.indexOf),tee=ir(String.prototype.trim),ree=ir(Number.prototype.toString),nee=ir(Boolean.prototype.toString),tx=typeof BigInt>"u"?null:ir(BigInt.prototype.toString),rx=typeof Symbol>"u"?null:ir(Symbol.prototype.toString),Wt=ir(Object.prototype.hasOwnProperty),Cu=ir(Object.prototype.toString),Ir=ir(RegExp.prototype.test),xh=iee(TypeError);function ir(r){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return D_(r,e,n)}}function iee(r){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return N_(r,t)}}function Xe(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ku;if(XI&&XI(r,null),!Yr(e))return r;let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const o=t(i);o!==i&&(JZ(e)||(e[n]=o),i=o)}r[i]=!0}return r}function oee(r){for(let e=0;e<r.length;e++)Wt(r,e)||(r[e]=null);return r}function pn(r){const e=Cl(null);for(const n of vU(r)){var t=zZ(n,2);const i=t[0],o=t[1];Wt(r,i)&&(Yr(o)?e[i]=oee(o):o&&typeof o=="object"&&o.constructor===Object?e[i]=pn(o):e[i]=o)}return e}function see(r){switch(typeof r){case"string":return r;case"number":return ree(r);case"boolean":return nee(r);case"bigint":return tx?tx(r):"0";case"symbol":return rx?rx(r):"Symbol()";case"undefined":return Cu(r);case"function":case"object":{if(r===null)return Cu(r);const e=r,t=ma(e,"toString");if(typeof t=="function"){const n=t(e);return typeof n=="string"?n:Cu(n)}return Cu(r)}default:return Cu(r)}}function ma(r,e){for(;r!==null;){const n=QZ(r,e);if(n){if(n.get)return ir(n.get);if(typeof n.value=="function")return ir(n.value)}r=XZ(r)}function t(){return null}return t}function aee(r){try{return Ir(r,""),!0}catch{return!1}}const nx=nn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Fy=nn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),By=nn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),lee=nn(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ky=nn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),cee=nn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ix=nn(["#text"]),ox=nn(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Vy=nn(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),sx=nn(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Oh=nn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),uee=ti(/{{[\w\W]*|^[\w\W]*}}/g),dee=ti(/<%[\w\W]*|^[\w\W]*%>/g),fee=ti(/\${[\w\W]*/g),hee=ti(/^data-[\-\w.\u00B7-\uFFFF]+$/),pee=ti(/^aria-[\-\w]+$/),ax=ti(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),vee=ti(/^(?:\w+script|data):/i),mee=ti(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),gee=ti(/^html$/i),yee=ti(/^[a-z][.\w]*(-[.\w]+)+$/i),yl={element:1,text:3,progressingInstruction:7,comment:8,document:9},See=function(){return typeof window>"u"?null:window},bee=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let n=null;const i="data-tt-policy-suffix";t&&t.hasAttribute(i)&&(n=t.getAttribute(i));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},lx=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function gU(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:See();const e=De=>gU(De);if(e.version="3.4.5",e.removed=[],!r||!r.document||r.document.nodeType!==yl.document||!r.Element)return e.isSupported=!1,e;let t=r.document;const n=t,i=n.currentScript,o=r.DocumentFragment,s=r.HTMLTemplateElement,a=r.Node,l=r.Element,c=r.NodeFilter,u=r.NamedNodeMap,d=u===void 0?r.NamedNodeMap||r.MozNamedAttrMap:u,f=r.HTMLFormElement,p=r.DOMParser,h=r.trustedTypes,m=l.prototype,E=ma(m,"cloneNode"),y=ma(m,"remove"),S=ma(m,"nextSibling"),R=ma(m,"childNodes"),k=ma(m,"parentNode"),x=a&&a.prototype?ma(a.prototype,"nodeType"):null;if(typeof s=="function"){const De=t.createElement("template");De.content&&De.content.ownerDocument&&(t=De.content.ownerDocument)}let T,O="";const C=t,N=C.implementation,F=C.createNodeIterator,H=C.createDocumentFragment,ie=C.getElementsByTagName,$=n.importNode;let X=lx();e.isSupported=typeof vU=="function"&&typeof k=="function"&&N&&N.createHTMLDocument!==void 0;const oe=uee,re=dee,ae=fee,q=hee,z=pee,Q=vee,Ie=mee,Y=yee;let le=ax,B=null;const W=Xe({},[...nx,...Fy,...By,...Ky,...ix]);let A=null;const D=Xe({},[...ox,...Vy,...sx,...Oh]);let P=Object.seal(Cl(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),M=null,I=null;const j=Object.seal(Cl(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let U=!0,K=!0,G=!1,ee=!0,se=!1,Ce=!0,Re=!1,ge=!1,He=!1,Qe=!1,$e=!1,me=!1,We=!0,un=!1;const Rr="user-content-";let gt=!0,vr=!1,mr={},Rt=null;const Cn=Xe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ye=null;const fe=Xe({},["audio","video","img","source","image","track"]);let J=null;const te=Xe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ne="http://www.w3.org/1998/Math/MathML",ue="http://www.w3.org/2000/svg",Ee="http://www.w3.org/1999/xhtml";let Te=Ee,ze=!1,dt=null;const ht=Xe({},[ne,ue,Ee],jy);let Kt=Xe({},["mi","mo","mn","ms","mtext"]),Ue=Xe({},["annotation-xml"]);const pt=Xe({},["title","style","font","a","script"]);let Vt=null;const Hr=["application/xhtml+xml","text/html"],rl="text/html";let tt=null,or=null;const nl=t.createElement("form"),dn=function(L){return L instanceof RegExp||L instanceof Function},zr=function(){let L=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(or&&or===L)return;(!L||typeof L!="object")&&(L={}),L=pn(L),Vt=Hr.indexOf(L.PARSER_MEDIA_TYPE)===-1?rl:L.PARSER_MEDIA_TYPE,tt=Vt==="application/xhtml+xml"?jy:Ku,B=Wt(L,"ALLOWED_TAGS")&&Yr(L.ALLOWED_TAGS)?Xe({},L.ALLOWED_TAGS,tt):W,A=Wt(L,"ALLOWED_ATTR")&&Yr(L.ALLOWED_ATTR)?Xe({},L.ALLOWED_ATTR,tt):D,dt=Wt(L,"ALLOWED_NAMESPACES")&&Yr(L.ALLOWED_NAMESPACES)?Xe({},L.ALLOWED_NAMESPACES,jy):ht,J=Wt(L,"ADD_URI_SAFE_ATTR")&&Yr(L.ADD_URI_SAFE_ATTR)?Xe(pn(te),L.ADD_URI_SAFE_ATTR,tt):te,ye=Wt(L,"ADD_DATA_URI_TAGS")&&Yr(L.ADD_DATA_URI_TAGS)?Xe(pn(fe),L.ADD_DATA_URI_TAGS,tt):fe,Rt=Wt(L,"FORBID_CONTENTS")&&Yr(L.FORBID_CONTENTS)?Xe({},L.FORBID_CONTENTS,tt):Cn,M=Wt(L,"FORBID_TAGS")&&Yr(L.FORBID_TAGS)?Xe({},L.FORBID_TAGS,tt):pn({}),I=Wt(L,"FORBID_ATTR")&&Yr(L.FORBID_ATTR)?Xe({},L.FORBID_ATTR,tt):pn({}),mr=Wt(L,"USE_PROFILES")?L.USE_PROFILES&&typeof L.USE_PROFILES=="object"?pn(L.USE_PROFILES):L.USE_PROFILES:!1,U=L.ALLOW_ARIA_ATTR!==!1,K=L.ALLOW_DATA_ATTR!==!1,G=L.ALLOW_UNKNOWN_PROTOCOLS||!1,ee=L.ALLOW_SELF_CLOSE_IN_ATTR!==!1,se=L.SAFE_FOR_TEMPLATES||!1,Ce=L.SAFE_FOR_XML!==!1,Re=L.WHOLE_DOCUMENT||!1,Qe=L.RETURN_DOM||!1,$e=L.RETURN_DOM_FRAGMENT||!1,me=L.RETURN_TRUSTED_TYPE||!1,He=L.FORCE_BODY||!1,We=L.SANITIZE_DOM!==!1,un=L.SANITIZE_NAMED_PROPS||!1,gt=L.KEEP_CONTENT!==!1,vr=L.IN_PLACE||!1,le=aee(L.ALLOWED_URI_REGEXP)?L.ALLOWED_URI_REGEXP:ax,Te=typeof L.NAMESPACE=="string"?L.NAMESPACE:Ee,Kt=Wt(L,"MATHML_TEXT_INTEGRATION_POINTS")&&L.MATHML_TEXT_INTEGRATION_POINTS&&typeof L.MATHML_TEXT_INTEGRATION_POINTS=="object"?pn(L.MATHML_TEXT_INTEGRATION_POINTS):Xe({},["mi","mo","mn","ms","mtext"]),Ue=Wt(L,"HTML_INTEGRATION_POINTS")&&L.HTML_INTEGRATION_POINTS&&typeof L.HTML_INTEGRATION_POINTS=="object"?pn(L.HTML_INTEGRATION_POINTS):Xe({},["annotation-xml"]);const ce=Wt(L,"CUSTOM_ELEMENT_HANDLING")&&L.CUSTOM_ELEMENT_HANDLING&&typeof L.CUSTOM_ELEMENT_HANDLING=="object"?pn(L.CUSTOM_ELEMENT_HANDLING):Cl(null);if(P=Cl(null),Wt(ce,"tagNameCheck")&&dn(ce.tagNameCheck)&&(P.tagNameCheck=ce.tagNameCheck),Wt(ce,"attributeNameCheck")&&dn(ce.attributeNameCheck)&&(P.attributeNameCheck=ce.attributeNameCheck),Wt(ce,"allowCustomizedBuiltInElements")&&typeof ce.allowCustomizedBuiltInElements=="boolean"&&(P.allowCustomizedBuiltInElements=ce.allowCustomizedBuiltInElements),se&&(K=!1),$e&&(Qe=!0),mr&&(B=Xe({},ix),A=Cl(null),mr.html===!0&&(Xe(B,nx),Xe(A,ox)),mr.svg===!0&&(Xe(B,Fy),Xe(A,Vy),Xe(A,Oh)),mr.svgFilters===!0&&(Xe(B,By),Xe(A,Vy),Xe(A,Oh)),mr.mathMl===!0&&(Xe(B,Ky),Xe(A,sx),Xe(A,Oh))),j.tagCheck=null,j.attributeCheck=null,Wt(L,"ADD_TAGS")&&(typeof L.ADD_TAGS=="function"?j.tagCheck=L.ADD_TAGS:Yr(L.ADD_TAGS)&&(B===W&&(B=pn(B)),Xe(B,L.ADD_TAGS,tt))),Wt(L,"ADD_ATTR")&&(typeof L.ADD_ATTR=="function"?j.attributeCheck=L.ADD_ATTR:Yr(L.ADD_ATTR)&&(A===D&&(A=pn(A)),Xe(A,L.ADD_ATTR,tt))),Wt(L,"ADD_URI_SAFE_ATTR")&&Yr(L.ADD_URI_SAFE_ATTR)&&Xe(J,L.ADD_URI_SAFE_ATTR,tt),Wt(L,"FORBID_CONTENTS")&&Yr(L.FORBID_CONTENTS)&&(Rt===Cn&&(Rt=pn(Rt)),Xe(Rt,L.FORBID_CONTENTS,tt)),Wt(L,"ADD_FORBID_CONTENTS")&&Yr(L.ADD_FORBID_CONTENTS)&&(Rt===Cn&&(Rt=pn(Rt)),Xe(Rt,L.ADD_FORBID_CONTENTS,tt)),gt&&(B["#text"]=!0),Re&&Xe(B,["html","head","body"]),B.table&&(Xe(B,["tbody"]),delete M.tbody),L.TRUSTED_TYPES_POLICY){if(typeof L.TRUSTED_TYPES_POLICY.createHTML!="function")throw xh('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof L.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw xh('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');T=L.TRUSTED_TYPES_POLICY,O=T.createHTML("")}else T===void 0&&(T=bee(h,i)),T!==null&&typeof O=="string"&&(O=T.createHTML(""));nn&&nn(L),or=L},Xc=Xe({},[...Fy,...By,...lee]),Pi=Xe({},[...Ky,...cee]),O0=function(L){let ce=k(L);(!ce||!ce.tagName)&&(ce={namespaceURI:Te,tagName:"template"});const ke=Ku(L.tagName),rt=Ku(ce.tagName);return dt[L.namespaceURI]?L.namespaceURI===ue?ce.namespaceURI===Ee?ke==="svg":ce.namespaceURI===ne?ke==="svg"&&(rt==="annotation-xml"||Kt[rt]):!!Xc[ke]:L.namespaceURI===ne?ce.namespaceURI===Ee?ke==="math":ce.namespaceURI===ue?ke==="math"&&Ue[rt]:!!Pi[ke]:L.namespaceURI===Ee?ce.namespaceURI===ue&&!Ue[rt]||ce.namespaceURI===ne&&!Kt[rt]?!1:!Pi[ke]&&(pt[ke]||!Xc[ke]):!!(Vt==="application/xhtml+xml"&&dt[L.namespaceURI]):!1},ii=function(L){ml(e.removed,{element:L});try{k(L).removeChild(L)}catch{y(L)}},Js=function(L,ce){try{ml(e.removed,{attribute:ce.getAttributeNode(L),from:ce})}catch{ml(e.removed,{attribute:null,from:ce})}if(ce.removeAttribute(L),L==="is")if(Qe||$e)try{ii(ce)}catch{}else try{ce.setAttribute(L,"")}catch{}},P0=function(L){let ce=null,ke=null;if(He)L="<remove></remove>"+L;else{const er=ZI(L,/^[\r\n\t ]+/);ke=er&&er[0]}Vt==="application/xhtml+xml"&&Te===Ee&&(L='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+L+"</body></html>");const rt=T?T.createHTML(L):L;if(Te===Ee)try{ce=new p().parseFromString(rt,Vt)}catch{}if(!ce||!ce.documentElement){ce=N.createDocument(Te,"template",null);try{ce.documentElement.innerHTML=ze?O:rt}catch{}}const Zt=ce.body||ce.documentElement;return L&&ke&&Zt.insertBefore(t.createTextNode(ke),Zt.childNodes[0]||null),Te===Ee?ie.call(ce,Re?"html":"body")[0]:Re?ce.documentElement:Zt},M0=function(L){return F.call(L.ownerDocument||L,L,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},A0=function(L){L.normalize();const ce=F.call(L.ownerDocument||L,L,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let ke=ce.nextNode();for(;ke;){let rt=ke.data;vl([oe,re,ae],Zt=>{rt=gl(rt,Zt," ")}),ke.data=rt,ke=ce.nextNode()}},eg=function(L){return L instanceof f&&(typeof L.nodeName!="string"||typeof L.textContent!="string"||typeof L.removeChild!="function"||!(L.attributes instanceof d)||typeof L.removeAttribute!="function"||typeof L.setAttribute!="function"||typeof L.namespaceURI!="string"||typeof L.insertBefore!="function"||typeof L.hasChildNodes!="function")},jf=function(L){if(!x||typeof L!="object"||L===null)return!1;try{return typeof x(L)=="number"}catch{return!1}};function so(De,L,ce){vl(De,ke=>{ke.call(e,L,ce,or)})}const D0=function(L){let ce=null;if(so(X.beforeSanitizeElements,L,null),eg(L))return ii(L),!0;const ke=tt(L.nodeName);if(so(X.uponSanitizeElement,L,{tagName:ke,allowedTags:B}),Ce&&L.hasChildNodes()&&!jf(L.firstElementChild)&&Ir(/<[/\w!]/g,L.innerHTML)&&Ir(/<[/\w!]/g,L.textContent)||Ce&&L.namespaceURI===Ee&&ke==="style"&&jf(L.firstElementChild)||L.nodeType===yl.progressingInstruction||Ce&&L.nodeType===yl.comment&&Ir(/<[/\w]/g,L.data))return ii(L),!0;if(M[ke]||!(j.tagCheck instanceof Function&&j.tagCheck(ke))&&!B[ke]){if(!M[ke]&&L0(ke)&&(P.tagNameCheck instanceof RegExp&&Ir(P.tagNameCheck,ke)||P.tagNameCheck instanceof Function&&P.tagNameCheck(ke)))return!1;if(gt&&!Rt[ke]){const rt=k(L)||L.parentNode,Zt=R(L)||L.childNodes;if(Zt&&rt){const er=Zt.length;for(let fn=er-1;fn>=0;--fn){const Wo=E(Zt[fn],!0);rt.insertBefore(Wo,S(L))}}}return ii(L),!0}return L instanceof l&&!O0(L)||(ke==="noscript"||ke==="noembed"||ke==="noframes")&&Ir(/<\/no(script|embed|frames)/i,L.innerHTML)?(ii(L),!0):(se&&L.nodeType===yl.text&&(ce=L.textContent,vl([oe,re,ae],rt=>{ce=gl(ce,rt," ")}),L.textContent!==ce&&(ml(e.removed,{element:L.cloneNode()}),L.textContent=ce)),so(X.afterSanitizeElements,L,null),!1)},N0=function(L,ce,ke){if(I[ce]||We&&(ce==="id"||ce==="name")&&(ke in t||ke in nl))return!1;const rt=A[ce]||j.attributeCheck instanceof Function&&j.attributeCheck(ce,L);if(!(K&&!I[ce]&&Ir(q,ce))){if(!(U&&Ir(z,ce))){if(!rt||I[ce]){if(!(L0(L)&&(P.tagNameCheck instanceof RegExp&&Ir(P.tagNameCheck,L)||P.tagNameCheck instanceof Function&&P.tagNameCheck(L))&&(P.attributeNameCheck instanceof RegExp&&Ir(P.attributeNameCheck,ce)||P.attributeNameCheck instanceof Function&&P.attributeNameCheck(ce,L))||ce==="is"&&P.allowCustomizedBuiltInElements&&(P.tagNameCheck instanceof RegExp&&Ir(P.tagNameCheck,ke)||P.tagNameCheck instanceof Function&&P.tagNameCheck(ke))))return!1}else if(!J[ce]){if(!Ir(le,gl(ke,Ie,""))){if(!((ce==="src"||ce==="xlink:href"||ce==="href")&&L!=="script"&&ex(ke,"data:")===0&&ye[L])){if(!(G&&!Ir(Q,gl(ke,Ie,"")))){if(ke)return!1}}}}}}return!0},VU=Xe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),L0=function(L){return!VU[Ku(L)]&&Ir(Y,L)},U0=function(L){so(X.beforeSanitizeAttributes,L,null);const ce=L.attributes;if(!ce||eg(L))return;const ke={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:A,forceKeepAttr:void 0};let rt=ce.length;for(;rt--;){const Zt=ce[rt],er=Zt.name,fn=Zt.namespaceURI,Wo=Zt.value,ao=tt(er),rg=Wo;let gr=er==="value"?rg:tee(rg);if(ke.attrName=ao,ke.attrValue=gr,ke.keepAttr=!0,ke.forceKeepAttr=void 0,so(X.uponSanitizeAttribute,L,ke),gr=ke.attrValue,un&&(ao==="id"||ao==="name")&&ex(gr,Rr)!==0&&(Js(er,L),gr=Rr+gr),Ce&&Ir(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,gr)){Js(er,L);continue}if(ao==="attributename"&&ZI(gr,"href")){Js(er,L);continue}if(ke.forceKeepAttr)continue;if(!ke.keepAttr){Js(er,L);continue}if(!ee&&Ir(/\/>/i,gr)){Js(er,L);continue}se&&vl([oe,re,ae],F0=>{gr=gl(gr,F0," ")});const j0=tt(L.nodeName);if(!N0(j0,ao,gr)){Js(er,L);continue}if(T&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!fn)switch(h.getAttributeType(j0,ao)){case"TrustedHTML":{gr=T.createHTML(gr);break}case"TrustedScriptURL":{gr=T.createScriptURL(gr);break}}if(gr!==rg)try{fn?L.setAttributeNS(fn,er,gr):L.setAttribute(er,gr),eg(L)?ii(L):QI(e.removed)}catch{Js(er,L)}}so(X.afterSanitizeAttributes,L,null)},tg=function(L){let ce=null;const ke=M0(L);for(so(X.beforeSanitizeShadowDOM,L,null);ce=ke.nextNode();)so(X.uponSanitizeShadowNode,ce,null),D0(ce),U0(ce),ce.content instanceof o&&tg(ce.content);so(X.afterSanitizeShadowDOM,L,null)},Ff=function(L){if(L.nodeType===yl.element&&L.shadowRoot instanceof o){const rt=L.shadowRoot;Ff(rt),tg(rt)}const ce=L.childNodes;if(!ce)return;const ke=[];vl(ce,rt=>{ml(ke,rt)});for(const rt of ke)Ff(rt)};return e.sanitize=function(De){let L=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ce=null,ke=null,rt=null,Zt=null;if(ze=!De,ze&&(De="<!-->"),typeof De!="string"&&!jf(De)&&(De=see(De),typeof De!="string"))throw xh("dirty is not a string, aborting");if(!e.isSupported)return De;if(ge||zr(L),e.removed=[],typeof De=="string"&&(vr=!1),vr){const Wo=De.nodeName;if(typeof Wo=="string"){const ao=tt(Wo);if(!B[ao]||M[ao])throw xh("root node is forbidden and cannot be sanitized in-place")}Ff(De)}else if(jf(De))ce=P0("<!---->"),ke=ce.ownerDocument.importNode(De,!0),ke.nodeType===yl.element&&ke.nodeName==="BODY"||ke.nodeName==="HTML"?ce=ke:ce.appendChild(ke),Ff(ke);else{if(!Qe&&!se&&!Re&&De.indexOf("<")===-1)return T&&me?T.createHTML(De):De;if(ce=P0(De),!ce)return Qe?null:me?O:""}ce&&He&&ii(ce.firstChild);const er=M0(vr?De:ce);for(;rt=er.nextNode();)D0(rt),U0(rt),rt.content instanceof o&&tg(rt.content);if(vr)return se&&A0(De),De;if(Qe){if(se&&A0(ce),$e)for(Zt=H.call(ce.ownerDocument);ce.firstChild;)Zt.appendChild(ce.firstChild);else Zt=ce;return(A.shadowroot||A.shadowrootmode)&&(Zt=$.call(n,Zt,!0)),Zt}let fn=Re?ce.outerHTML:ce.innerHTML;return Re&&B["!doctype"]&&ce.ownerDocument&&ce.ownerDocument.doctype&&ce.ownerDocument.doctype.name&&Ir(gee,ce.ownerDocument.doctype.name)&&(fn="<!DOCTYPE "+ce.ownerDocument.doctype.name+`>
303
- `+fn),se&&vl([oe,re,ae],Wo=>{fn=gl(fn,Wo," ")}),T&&me?T.createHTML(fn):fn},e.setConfig=function(){let De=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};zr(De),ge=!0},e.clearConfig=function(){or=null,ge=!1},e.isValidAttribute=function(De,L,ce){or||zr({});const ke=tt(De),rt=tt(L);return N0(ke,rt,ce)},e.addHook=function(De,L){typeof L=="function"&&ml(X[De],L)},e.removeHook=function(De,L){if(L!==void 0){const ce=ZZ(X[De],L);return ce===-1?void 0:eee(X[De],ce,1)[0]}return QI(X[De])},e.removeHooks=function(De){X[De]=[]},e.removeAllHooks=function(){X=lx()},e}var _ee=gU(),p0={},v0={};Object.defineProperty(v0,"__esModule",{value:!0});var bt;(function(r){r.Root="root",r.Text="text",r.Directive="directive",r.Comment="comment",r.Script="script",r.Style="style",r.Tag="tag",r.CDATA="cdata",r.Doctype="doctype"})(bt||(bt={}));function Eee(r){return r.type===bt.Tag||r.type===bt.Script||r.type===bt.Style}bt.Root;bt.Text;bt.Directive;bt.Comment;bt.Script;bt.Style;bt.Tag;bt.CDATA;bt.Doctype;let yU=class{constructor(){Ne(this,"parent",null);Ne(this,"prev",null);Ne(this,"next",null);Ne(this,"startIndex",null);Ne(this,"endIndex",null)}get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return wU(this,e)}},m0=class extends yU{constructor(t){super();Ne(this,"data");this.data=t}get nodeValue(){return this.data}set nodeValue(t){this.data=t}},SU=class extends m0{constructor(){super(...arguments);Ne(this,"type",bt.Text)}get nodeType(){return 3}},bU=class extends m0{constructor(){super(...arguments);Ne(this,"type",bt.Comment)}get nodeType(){return 8}},_U=class extends m0{constructor(t,n){super(n);Ne(this,"type",bt.Directive);Ne(this,"name");Ne(this,"x-name");Ne(this,"x-publicId");Ne(this,"x-systemId");this.name=t}get nodeType(){return 1}},g0=class extends yU{constructor(t){super();Ne(this,"children");this.children=t}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(t){this.children=t}},wee=class extends g0{constructor(){super(...arguments);Ne(this,"type",bt.CDATA)}get nodeType(){return 4}},Tee=class extends g0{constructor(){super(...arguments);Ne(this,"type",bt.Root)}get nodeType(){return 9}},EU=class extends g0{constructor(t,n,i=[],o=t==="script"?bt.Script:t==="style"?bt.Style:bt.Tag){super(i);Ne(this,"name");Ne(this,"attribs");Ne(this,"type");Ne(this,"namespace");Ne(this,"x-attribsNamespace");Ne(this,"x-attribsPrefix");this.name=t,this.attribs=n,this.type=o}get nodeType(){return 1}get tagName(){return this.name}set tagName(t){this.name=t}get attributes(){return Object.keys(this.attribs).map(t=>{var n,i;return{name:t,value:this.attribs[t],namespace:(n=this["x-attribsNamespace"])==null?void 0:n[t],prefix:(i=this["x-attribsPrefix"])==null?void 0:i[t]}})}};function Ree(r){return Eee(r)}function Cee(r){return r.type===bt.CDATA}function kee(r){return r.type===bt.Text}function Iee(r){return r.type===bt.Comment}function xee(r){return r.type===bt.Directive}function Oee(r){return r.type===bt.Root}function wU(r,e=!1){let t;if(kee(r))t=new SU(r.data);else if(Iee(r))t=new bU(r.data);else if(Ree(r)){const n=e?$y(r.children):[],i=new EU(r.name,{...r.attribs},n);for(const o of n)o.parent=i;r.namespace!=null&&(i.namespace=r.namespace),r["x-attribsNamespace"]&&(i["x-attribsNamespace"]={...r["x-attribsNamespace"]}),r["x-attribsPrefix"]&&(i["x-attribsPrefix"]={...r["x-attribsPrefix"]}),t=i}else if(Cee(r)){const n=e?$y(r.children):[],i=new wee(n);for(const o of n)o.parent=i;t=i}else if(Oee(r)){const n=e?$y(r.children):[],i=new Tee(n);for(const o of n)o.parent=i;r["x-mode"]&&(i["x-mode"]=r["x-mode"]),t=i}else if(xee(r)){const n=new _U(r.name,r.data);r["x-name"]!=null&&(n["x-name"]=r["x-name"],n["x-publicId"]=r["x-publicId"],n["x-systemId"]=r["x-systemId"]),t=n}else throw new Error(`Not implemented yet: ${r.type}`);return t.startIndex=r.startIndex,t.endIndex=r.endIndex,r.sourceCodeLocation!=null&&(t.sourceCodeLocation=r.sourceCodeLocation),t}function $y(r){const e=r.map(t=>wU(t,!0));for(let t=1;t<e.length;t++)e[t].prev=e[t-1],e[t-1].next=e[t];return e}var Pee=["animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","linearGradient","radialGradient","textPath"],Mee=Pee.reduce(function(r,e){return r[e.toLowerCase()]=e,r},{}),TU="\r",Aee=new RegExp(TU,"g"),RU="__HTML_DOM_PARSER_CARRIAGE_RETURN_PLACEHOLDER_".concat(Date.now().toString(),"__"),Dee=new RegExp(RU,"g");function Nee(r){return Mee[r]}function Lee(r){for(var e={},t=0,n=r.length;t<n;t++){var i=r[t];e[i.name]=i.value}return e}function Uee(r){r=r.toLowerCase();var e=Nee(r);return e||r}function Ph(r,e){var t="<"+e,n=r.toLowerCase().indexOf(t);if(n===-1)return!1;var i=r[n+t.length];return i===">"||i===" "||i===" "||i===`
304
- `||i==="\r"||i==="/"}function jee(r){return r.replace(Aee,RU)}function Fee(r){return r.replace(Dee,TU)}function CU(r,e,t){var n,i,o,s;e===void 0&&(e=null);for(var a=[],l,c=0,u=r.length;c<u;c++){var d=r[c];switch(d.nodeType){case 1:{var f=Uee(d.nodeName);l=new EU(f,Lee(d.attributes)),l.children=CU(f==="template"?d.content.childNodes:d.childNodes,l);break}case 3:l=new SU(Fee((n=d.nodeValue)!==null&&n!==void 0?n:""));break;case 8:l=new bU((i=d.nodeValue)!==null&&i!==void 0?i:"");break;default:continue}var p=(o=a[c-1])!==null&&o!==void 0?o:null;p&&(p.next=l),l.parent=e,l.prev=p,l.next=null,a.push(l)}return t&&(l=new _U(t.substring(0,t.indexOf(" ")).toLowerCase(),t),l.next=(s=a[0])!==null&&s!==void 0?s:null,l.parent=e,a.unshift(l),a[1]&&(a[1].prev=a[0])),a}var cx="html",Mh="head",Sl="body",Bee=/<([a-zA-Z]+[0-9]?)/;function L_(r,e){return e?e.createHTML(r):r}var Tv=function(r,e,t){throw new Error("This browser does not support `document.implementation.createHTMLDocument`")},U_=function(r,e,t){throw new Error("This browser does not support `DOMParser.prototype.parseFromString`")},ux=typeof window=="object"&&window.DOMParser;if(typeof ux=="function"){var Kee=new ux,Vee="text/html";U_=function(r,e,t){return e&&(r="<".concat(e,">").concat(r,"</").concat(e,">")),Kee.parseFromString(r,Vee)},Tv=U_}if(typeof document=="object"&&document.implementation){var Ah=document.implementation.createHTMLDocument();Tv=function(r,e,t){if(e){var n=Ah.documentElement.querySelector(e);return n&&(n.innerHTML=L_(r,t)),Ah}return Ah.documentElement.innerHTML=L_(r,t),Ah}}var Dh=typeof document=="object"&&document.createElement("template"),j_;Dh&&Dh.content&&(j_=function(r,e){return Dh.innerHTML=L_(r,e),Dh.content.childNodes});var dx=function(){return document.createDocumentFragment().childNodes};function $ee(r,e){var t,n,i,o,s,a;r=jee(r);var l=Bee.exec(r),c=(t=l==null?void 0:l[1])===null||t===void 0?void 0:t.toLowerCase();switch(c){case cx:{var u=U_(r);if(!Ph(r,Mh)){var d=u.querySelector(Mh);(n=d==null?void 0:d.parentNode)===null||n===void 0||n.removeChild(d)}if(!Ph(r,Sl)){var d=u.querySelector(Sl);(i=d==null?void 0:d.parentNode)===null||i===void 0||i.removeChild(d)}return u.querySelectorAll(cx)}case Mh:case Sl:{var f=Tv(r,void 0,e).querySelectorAll(c);return Ph(r,Sl)&&Ph(r,Mh)?(s=(o=f[0].parentNode)===null||o===void 0?void 0:o.childNodes)!==null&&s!==void 0?s:dx():f}default:{if(j_)return j_(r,e);var d=Tv(r,Sl,e).querySelector(Sl);return(a=d==null?void 0:d.childNodes)!==null&&a!==void 0?a:dx()}}}var Wee=/<(![a-zA-Z\s]+)>/;function qee(r,e){if(typeof r!="string")throw new TypeError("First argument must be a string");if(!r)return[];var t=Wee.exec(r),n=t?t[1]:void 0;return CU($ee(r,e==null?void 0:e.trustedTypePolicy),null,n)}v0.default=qee;var Hm={},Oi={},zm={},Gee=0;zm.SAME=Gee;var Hee=1;zm.CAMELCASE=Hee;zm.possibleStandardNames={accept:0,acceptCharset:1,"accept-charset":"acceptCharset",accessKey:1,action:0,allowFullScreen:1,alt:0,as:0,async:0,autoCapitalize:1,autoComplete:1,autoCorrect:1,autoFocus:1,autoPlay:1,autoSave:1,capture:0,cellPadding:1,cellSpacing:1,challenge:0,charSet:1,checked:0,children:0,cite:0,class:"className",classID:1,className:1,cols:0,colSpan:1,content:0,contentEditable:1,contextMenu:1,controls:0,controlsList:1,coords:0,crossOrigin:1,dangerouslySetInnerHTML:1,data:0,dateTime:1,default:0,defaultChecked:1,defaultValue:1,defer:0,dir:0,disabled:0,disablePictureInPicture:1,disableRemotePlayback:1,download:0,draggable:0,encType:1,enterKeyHint:1,for:"htmlFor",form:0,formMethod:1,formAction:1,formEncType:1,formNoValidate:1,formTarget:1,frameBorder:1,headers:0,height:0,hidden:0,high:0,href:0,hrefLang:1,htmlFor:1,httpEquiv:1,"http-equiv":"httpEquiv",icon:0,id:0,innerHTML:1,inputMode:1,integrity:0,is:0,itemID:1,itemProp:1,itemRef:1,itemScope:1,itemType:1,keyParams:1,keyType:1,kind:0,label:0,lang:0,list:0,loop:0,low:0,manifest:0,marginWidth:1,marginHeight:1,max:0,maxLength:1,media:0,mediaGroup:1,method:0,min:0,minLength:1,multiple:0,muted:0,name:0,noModule:1,nonce:0,noValidate:1,open:0,optimum:0,pattern:0,placeholder:0,playsInline:1,poster:0,preload:0,profile:0,radioGroup:1,readOnly:1,referrerPolicy:1,rel:0,required:0,reversed:0,role:0,rows:0,rowSpan:1,sandbox:0,scope:0,scoped:0,scrolling:0,seamless:0,selected:0,shape:0,size:0,sizes:0,span:0,spellCheck:1,src:0,srcDoc:1,srcLang:1,srcSet:1,start:0,step:0,style:0,summary:0,tabIndex:1,target:0,title:0,type:0,useMap:1,value:0,width:0,wmode:0,wrap:0,about:0,accentHeight:1,"accent-height":"accentHeight",accumulate:0,additive:0,alignmentBaseline:1,"alignment-baseline":"alignmentBaseline",allowReorder:1,alphabetic:0,amplitude:0,arabicForm:1,"arabic-form":"arabicForm",ascent:0,attributeName:1,attributeType:1,autoReverse:1,azimuth:0,baseFrequency:1,baselineShift:1,"baseline-shift":"baselineShift",baseProfile:1,bbox:0,begin:0,bias:0,by:0,calcMode:1,capHeight:1,"cap-height":"capHeight",clip:0,clipPath:1,"clip-path":"clipPath",clipPathUnits:1,clipRule:1,"clip-rule":"clipRule",color:0,colorInterpolation:1,"color-interpolation":"colorInterpolation",colorInterpolationFilters:1,"color-interpolation-filters":"colorInterpolationFilters",colorProfile:1,"color-profile":"colorProfile",colorRendering:1,"color-rendering":"colorRendering",contentScriptType:1,contentStyleType:1,cursor:0,cx:0,cy:0,d:0,datatype:0,decelerate:0,descent:0,diffuseConstant:1,direction:0,display:0,divisor:0,dominantBaseline:1,"dominant-baseline":"dominantBaseline",dur:0,dx:0,dy:0,edgeMode:1,elevation:0,enableBackground:1,"enable-background":"enableBackground",end:0,exponent:0,externalResourcesRequired:1,fill:0,fillOpacity:1,"fill-opacity":"fillOpacity",fillRule:1,"fill-rule":"fillRule",filter:0,filterRes:1,filterUnits:1,floodOpacity:1,"flood-opacity":"floodOpacity",floodColor:1,"flood-color":"floodColor",focusable:0,fontFamily:1,"font-family":"fontFamily",fontSize:1,"font-size":"fontSize",fontSizeAdjust:1,"font-size-adjust":"fontSizeAdjust",fontStretch:1,"font-stretch":"fontStretch",fontStyle:1,"font-style":"fontStyle",fontVariant:1,"font-variant":"fontVariant",fontWeight:1,"font-weight":"fontWeight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:1,"glyph-name":"glyphName",glyphOrientationHorizontal:1,"glyph-orientation-horizontal":"glyphOrientationHorizontal",glyphOrientationVertical:1,"glyph-orientation-vertical":"glyphOrientationVertical",glyphRef:1,gradientTransform:1,gradientUnits:1,hanging:0,horizAdvX:1,"horiz-adv-x":"horizAdvX",horizOriginX:1,"horiz-origin-x":"horizOriginX",ideographic:0,imageRendering:1,"image-rendering":"imageRendering",in2:0,in:0,inlist:0,intercept:0,k1:0,k2:0,k3:0,k4:0,k:0,kernelMatrix:1,kernelUnitLength:1,kerning:0,keyPoints:1,keySplines:1,keyTimes:1,lengthAdjust:1,letterSpacing:1,"letter-spacing":"letterSpacing",lightingColor:1,"lighting-color":"lightingColor",limitingConeAngle:1,local:0,markerEnd:1,"marker-end":"markerEnd",markerHeight:1,markerMid:1,"marker-mid":"markerMid",markerStart:1,"marker-start":"markerStart",markerUnits:1,markerWidth:1,mask:0,maskContentUnits:1,maskUnits:1,mathematical:0,mode:0,numOctaves:1,offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:1,"overline-position":"overlinePosition",overlineThickness:1,"overline-thickness":"overlineThickness",paintOrder:1,"paint-order":"paintOrder",panose1:0,"panose-1":"panose1",pathLength:1,patternContentUnits:1,patternTransform:1,patternUnits:1,pointerEvents:1,"pointer-events":"pointerEvents",points:0,pointsAtX:1,pointsAtY:1,pointsAtZ:1,prefix:0,preserveAlpha:1,preserveAspectRatio:1,primitiveUnits:1,property:0,r:0,radius:0,refX:1,refY:1,renderingIntent:1,"rendering-intent":"renderingIntent",repeatCount:1,repeatDur:1,requiredExtensions:1,requiredFeatures:1,resource:0,restart:0,result:0,results:0,rotate:0,rx:0,ry:0,scale:0,security:0,seed:0,shapeRendering:1,"shape-rendering":"shapeRendering",slope:0,spacing:0,specularConstant:1,specularExponent:1,speed:0,spreadMethod:1,startOffset:1,stdDeviation:1,stemh:0,stemv:0,stitchTiles:1,stopColor:1,"stop-color":"stopColor",stopOpacity:1,"stop-opacity":"stopOpacity",strikethroughPosition:1,"strikethrough-position":"strikethroughPosition",strikethroughThickness:1,"strikethrough-thickness":"strikethroughThickness",string:0,stroke:0,strokeDasharray:1,"stroke-dasharray":"strokeDasharray",strokeDashoffset:1,"stroke-dashoffset":"strokeDashoffset",strokeLinecap:1,"stroke-linecap":"strokeLinecap",strokeLinejoin:1,"stroke-linejoin":"strokeLinejoin",strokeMiterlimit:1,"stroke-miterlimit":"strokeMiterlimit",strokeWidth:1,"stroke-width":"strokeWidth",strokeOpacity:1,"stroke-opacity":"strokeOpacity",suppressContentEditableWarning:1,suppressHydrationWarning:1,surfaceScale:1,systemLanguage:1,tableValues:1,targetX:1,targetY:1,textAnchor:1,"text-anchor":"textAnchor",textDecoration:1,"text-decoration":"textDecoration",textLength:1,textRendering:1,"text-rendering":"textRendering",to:0,transform:0,typeof:0,u1:0,u2:0,underlinePosition:1,"underline-position":"underlinePosition",underlineThickness:1,"underline-thickness":"underlineThickness",unicode:0,unicodeBidi:1,"unicode-bidi":"unicodeBidi",unicodeRange:1,"unicode-range":"unicodeRange",unitsPerEm:1,"units-per-em":"unitsPerEm",unselectable:0,vAlphabetic:1,"v-alphabetic":"vAlphabetic",values:0,vectorEffect:1,"vector-effect":"vectorEffect",version:0,vertAdvY:1,"vert-adv-y":"vertAdvY",vertOriginX:1,"vert-origin-x":"vertOriginX",vertOriginY:1,"vert-origin-y":"vertOriginY",vHanging:1,"v-hanging":"vHanging",vIdeographic:1,"v-ideographic":"vIdeographic",viewBox:1,viewTarget:1,visibility:0,vMathematical:1,"v-mathematical":"vMathematical",vocab:0,widths:0,wordSpacing:1,"word-spacing":"wordSpacing",writingMode:1,"writing-mode":"writingMode",x1:0,x2:0,x:0,xChannelSelector:1,xHeight:1,"x-height":"xHeight",xlinkActuate:1,"xlink:actuate":"xlinkActuate",xlinkArcrole:1,"xlink:arcrole":"xlinkArcrole",xlinkHref:1,"xlink:href":"xlinkHref",xlinkRole:1,"xlink:role":"xlinkRole",xlinkShow:1,"xlink:show":"xlinkShow",xlinkTitle:1,"xlink:title":"xlinkTitle",xlinkType:1,"xlink:type":"xlinkType",xmlBase:1,"xml:base":"xmlBase",xmlLang:1,"xml:lang":"xmlLang",xmlns:0,"xml:space":"xmlSpace",xmlnsXlink:1,"xmlns:xlink":"xmlnsXlink",xmlSpace:1,y1:0,y2:0,y:0,yChannelSelector:1,z:0,zoomAndPan:1};const kU=0,Ys=1,Ym=2,Jm=3,y0=4,IU=5,xU=6;function zee(r){return Ur.hasOwnProperty(r)?Ur[r]:null}function cn(r,e,t,n,i,o,s){this.acceptsBooleans=e===Ym||e===Jm||e===y0,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=t,this.propertyName=r,this.type=e,this.sanitizeURL=o,this.removeEmptyString=s}const Ur={},Yee=["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"];Yee.forEach(r=>{Ur[r]=new cn(r,kU,!1,r,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(([r,e])=>{Ur[r]=new cn(r,Ys,!1,e,null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(r=>{Ur[r]=new cn(r,Ym,!1,r.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(r=>{Ur[r]=new cn(r,Ym,!1,r,null,!1,!1)});["allowFullScreen","async","autoFocus","autoPlay","controls","default","defer","disabled","disablePictureInPicture","disableRemotePlayback","formNoValidate","hidden","loop","noModule","noValidate","open","playsInline","readOnly","required","reversed","scoped","seamless","itemScope"].forEach(r=>{Ur[r]=new cn(r,Jm,!1,r.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(r=>{Ur[r]=new cn(r,Jm,!0,r,null,!1,!1)});["capture","download"].forEach(r=>{Ur[r]=new cn(r,y0,!1,r,null,!1,!1)});["cols","rows","size","span"].forEach(r=>{Ur[r]=new cn(r,xU,!1,r,null,!1,!1)});["rowSpan","start"].forEach(r=>{Ur[r]=new cn(r,IU,!1,r.toLowerCase(),null,!1,!1)});const S0=/[\-\:]([a-z])/g,b0=r=>r[1].toUpperCase();["accent-height","alignment-baseline","arabic-form","baseline-shift","cap-height","clip-path","clip-rule","color-interpolation","color-interpolation-filters","color-profile","color-rendering","dominant-baseline","enable-background","fill-opacity","fill-rule","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","horiz-adv-x","horiz-origin-x","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","overline-position","overline-thickness","paint-order","panose-1","pointer-events","rendering-intent","shape-rendering","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-rendering","underline-position","underline-thickness","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","vector-effect","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","writing-mode","xmlns:xlink","x-height"].forEach(r=>{const e=r.replace(S0,b0);Ur[e]=new cn(e,Ys,!1,r,null,!1,!1)});["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(r=>{const e=r.replace(S0,b0);Ur[e]=new cn(e,Ys,!1,r,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(r=>{const e=r.replace(S0,b0);Ur[e]=new cn(e,Ys,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(r=>{Ur[r]=new cn(r,Ys,!1,r.toLowerCase(),null,!1,!1)});const Jee="xlinkHref";Ur[Jee]=new cn("xlinkHref",Ys,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(r=>{Ur[r]=new cn(r,Ys,!1,r.toLowerCase(),null,!0,!0)});const{CAMELCASE:Xee,SAME:Qee,possibleStandardNames:fx}=zm,Zee=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",ete=Zee+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",tte=RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+ete+"]*$")),rte=Object.keys(fx).reduce((r,e)=>{const t=fx[e];return t===Qee?r[e]=e:t===Xee?r[e.toLowerCase()]=e:r[e]=t,r},{});Oi.BOOLEAN=Jm;Oi.BOOLEANISH_STRING=Ym;Oi.NUMERIC=IU;Oi.OVERLOADED_BOOLEAN=y0;Oi.POSITIVE_NUMERIC=xU;Oi.RESERVED=kU;Oi.STRING=Ys;Oi.getPropertyInfo=zee;Oi.isCustomAttribute=tte;Oi.possibleStandardNames=rte;var _0={},E0={},hx=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,nte=/\n/g,ite=/^\s*/,ote=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,ste=/^:\s*/,ate=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,lte=/^[;\s]*/,cte=/^\s+|\s+$/g,ute=`
305
- `,px="/",vx="*",ba="",dte="comment",fte="declaration";function hte(r,e){if(typeof r!="string")throw new TypeError("First argument must be a string");if(!r)return[];e=e||{};var t=1,n=1;function i(h){var m=h.match(nte);m&&(t+=m.length);var E=h.lastIndexOf(ute);n=~E?h.length-E:n+h.length}function o(){var h={line:t,column:n};return function(m){return m.position=new s(h),c(),m}}function s(h){this.start=h,this.end={line:t,column:n},this.source=e.source}s.prototype.content=r;function a(h){var m=new Error(e.source+":"+t+":"+n+": "+h);if(m.reason=h,m.filename=e.source,m.line=t,m.column=n,m.source=r,!e.silent)throw m}function l(h){var m=h.exec(r);if(m){var E=m[0];return i(E),r=r.slice(E.length),m}}function c(){l(ite)}function u(h){var m;for(h=h||[];m=d();)m!==!1&&h.push(m);return h}function d(){var h=o();if(!(px!=r.charAt(0)||vx!=r.charAt(1))){for(var m=2;ba!=r.charAt(m)&&(vx!=r.charAt(m)||px!=r.charAt(m+1));)++m;if(m+=2,ba===r.charAt(m-1))return a("End of comment missing");var E=r.slice(2,m-2);return n+=2,i(E),r=r.slice(m),n+=2,h({type:dte,comment:E})}}function f(){var h=o(),m=l(ote);if(m){if(d(),!l(ste))return a("property missing ':'");var E=l(ate),y=h({type:fte,property:mx(m[0].replace(hx,ba)),value:E?mx(E[0].replace(hx,ba)):ba});return l(lte),y}}function p(){var h=[];u(h);for(var m;m=f();)m!==!1&&(h.push(m),u(h));return h}return c(),p()}function mx(r){return r?r.replace(cte,ba):ba}var pte=hte,vte=wi&&wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(E0,"__esModule",{value:!0});E0.default=gte;const mte=vte(pte);function gte(r,e){let t=null;if(!r||typeof r!="string")return t;const n=(0,mte.default)(r),i=typeof e=="function";return n.forEach(o=>{if(o.type!=="declaration")return;const{property:s,value:a}=o;i?e(s,a,o):a&&(t=t||{},t[s]=a)}),t}var Xm={};Object.defineProperty(Xm,"__esModule",{value:!0});Xm.camelCase=void 0;var yte=/^--[a-zA-Z0-9_-]+$/,Ste=/-([a-z])/g,bte=/^[^-]+$/,_te=/^-(webkit|moz|ms|o|khtml)-/,Ete=/^-(ms)-/,wte=function(r){return!r||bte.test(r)||yte.test(r)},Tte=function(r,e){return e.toUpperCase()},gx=function(r,e){return"".concat(e,"-")},Rte=function(r,e){return e===void 0&&(e={}),wte(r)?r:(r=r.toLowerCase(),e.reactCompat?r=r.replace(Ete,gx):r=r.replace(_te,gx),r.replace(Ste,Tte))};Xm.camelCase=Rte;var Cte=wi&&wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},kte=Cte(E0),Ite=Xm;function F_(r,e){var t={};return!r||typeof r!="string"||(0,kte.default)(r,function(n,i){n&&i&&(t[(0,Ite.camelCase)(n,e)]=i)}),t}F_.default=F_;var xte=F_;(function(r){var e=wi&&wi.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(r,"__esModule",{value:!0}),r.returnFirstArg=r.canTextBeChildOfNode=r.ELEMENTS_WITH_NO_TEXT_CHILDREN=r.PRESERVE_CUSTOM_ATTRIBUTES=void 0,r.isCustomComponent=o,r.setStyleProp=a;const t=_,n=e(xte),i=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function o(u,d){return u.includes("-")?!i.has(u):!!(d&&typeof d.is=="string")}const s={reactCompat:!0};function a(u,d){if(typeof u=="string"){if(!u.trim()){d.style={};return}try{d.style=(0,n.default)(u,s)}catch{d.style={}}}}r.PRESERVE_CUSTOM_ATTRIBUTES=Number(t.version.split(".")[0])>=16,r.ELEMENTS_WITH_NO_TEXT_CHILDREN=new Set(["tr","tbody","thead","tfoot","colgroup","table","head","html","frameset"]);const l=u=>!r.ELEMENTS_WITH_NO_TEXT_CHILDREN.has(u.name);r.canTextBeChildOfNode=l;const c=u=>u;r.returnFirstArg=c})(_0);Object.defineProperty(Hm,"__esModule",{value:!0});Hm.default=Ate;const Vu=Oi,yx=_0,Ote=["checked","value"],Pte=["input","select","textarea"],Mte={reset:!0,submit:!0};function Ate(r={},e){const t={},n=!!(r.type&&Mte[r.type]);for(const i in r){const o=r[i];if((0,Vu.isCustomAttribute)(i)){t[i]=o;continue}const s=i.toLowerCase();let a=Sx(s);if(a){const l=(0,Vu.getPropertyInfo)(a);switch(Ote.includes(a)&&Pte.includes(e)&&!n&&(a=Sx("default"+s)),t[a]=o,l==null?void 0:l.type){case Vu.BOOLEAN:t[a]=!0;break;case Vu.OVERLOADED_BOOLEAN:o===""&&(t[a]=!0);break}continue}yx.PRESERVE_CUSTOM_ATTRIBUTES&&(t[i]=o)}return(0,yx.setStyleProp)(r.style,t),t}function Sx(r){return Vu.possibleStandardNames[r]}var w0={},ut;(function(r){r.Root="root",r.Text="text",r.Directive="directive",r.Comment="comment",r.Script="script",r.Style="style",r.Tag="tag",r.CDATA="cdata",r.Doctype="doctype"})(ut||(ut={}));function Dte(r){return r.type===ut.Tag||r.type===ut.Script||r.type===ut.Style}ut.Root;ut.Text;ut.Directive;ut.Comment;ut.Script;ut.Style;ut.Tag;ut.CDATA;ut.Doctype;let T0=class{constructor(){Ne(this,"parent",null);Ne(this,"prev",null);Ne(this,"next",null);Ne(this,"startIndex",null);Ne(this,"endIndex",null)}get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return x0(this,e)}};class Qm extends T0{constructor(t){super();Ne(this,"data");this.data=t}get nodeValue(){return this.data}set nodeValue(t){this.data=t}}class Rv extends Qm{constructor(){super(...arguments);Ne(this,"type",ut.Text)}get nodeType(){return 3}}class R0 extends Qm{constructor(){super(...arguments);Ne(this,"type",ut.Comment)}get nodeType(){return 8}}class C0 extends Qm{constructor(t,n){super(n);Ne(this,"type",ut.Directive);Ne(this,"name");Ne(this,"x-name");Ne(this,"x-publicId");Ne(this,"x-systemId");this.name=t}get nodeType(){return 1}}class Zm extends T0{constructor(t){super();Ne(this,"children");this.children=t}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(t){this.children=t}}class k0 extends Zm{constructor(){super(...arguments);Ne(this,"type",ut.CDATA)}get nodeType(){return 4}}class Cv extends Zm{constructor(){super(...arguments);Ne(this,"type",ut.Root)}get nodeType(){return 9}}let I0=class extends Zm{constructor(t,n,i=[],o=t==="script"?ut.Script:t==="style"?ut.Style:ut.Tag){super(i);Ne(this,"name");Ne(this,"attribs");Ne(this,"type");Ne(this,"namespace");Ne(this,"x-attribsNamespace");Ne(this,"x-attribsPrefix");this.name=t,this.attribs=n,this.type=o}get nodeType(){return 1}get tagName(){return this.name}set tagName(t){this.name=t}get attributes(){return Object.keys(this.attribs).map(t=>{var n,i;return{name:t,value:this.attribs[t],namespace:(n=this["x-attribsNamespace"])==null?void 0:n[t],prefix:(i=this["x-attribsPrefix"])==null?void 0:i[t]}})}};function OU(r){return Dte(r)}function PU(r){return r.type===ut.CDATA}function MU(r){return r.type===ut.Text}function AU(r){return r.type===ut.Comment}function DU(r){return r.type===ut.Directive}function NU(r){return r.type===ut.Root}function Nte(r){return Object.hasOwn(r,"children")}function x0(r,e=!1){let t;if(MU(r))t=new Rv(r.data);else if(AU(r))t=new R0(r.data);else if(OU(r)){const n=e?Wy(r.children):[],i=new I0(r.name,{...r.attribs},n);for(const o of n)o.parent=i;r.namespace!=null&&(i.namespace=r.namespace),r["x-attribsNamespace"]&&(i["x-attribsNamespace"]={...r["x-attribsNamespace"]}),r["x-attribsPrefix"]&&(i["x-attribsPrefix"]={...r["x-attribsPrefix"]}),t=i}else if(PU(r)){const n=e?Wy(r.children):[],i=new k0(n);for(const o of n)o.parent=i;t=i}else if(NU(r)){const n=e?Wy(r.children):[],i=new Cv(n);for(const o of n)o.parent=i;r["x-mode"]&&(i["x-mode"]=r["x-mode"]),t=i}else if(DU(r)){const n=new C0(r.name,r.data);r["x-name"]!=null&&(n["x-name"]=r["x-name"],n["x-publicId"]=r["x-publicId"],n["x-systemId"]=r["x-systemId"]),t=n}else throw new Error(`Not implemented yet: ${r.type}`);return t.startIndex=r.startIndex,t.endIndex=r.endIndex,r.sourceCodeLocation!=null&&(t.sourceCodeLocation=r.sourceCodeLocation),t}function Wy(r){const e=r.map(t=>x0(t,!0));for(let t=1;t<e.length;t++)e[t].prev=e[t-1],e[t-1].next=e[t];return e}const bx={withStartIndices:!1,withEndIndices:!1,xmlMode:!1};class _x{constructor(e,t,n){Ne(this,"dom",[]);Ne(this,"root",new Cv(this.dom));Ne(this,"callback");Ne(this,"options");Ne(this,"elementCB");Ne(this,"done",!1);Ne(this,"tagStack",[this.root]);Ne(this,"lastNode",null);Ne(this,"parser",null);typeof t=="function"&&(n=t,t=bx),typeof e=="object"&&(t=e,e=void 0),this.callback=e??null,this.options=t??bx,this.elementCB=n??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new Cv(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;const e=this.tagStack.pop();this.options.withEndIndices&&this.parser&&(e.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(e)}onopentag(e,t){const n=this.options.xmlMode?ut.Tag:void 0,i=new I0(e,t,void 0,n);this.addNode(i),this.tagStack.push(i)}ontext(e){const{lastNode:t}=this;if(t&&t.type===ut.Text)t.data+=e,this.options.withEndIndices&&this.parser&&(t.endIndex=this.parser.endIndex);else{const n=new Rv(e);this.addNode(n),this.lastNode=n}}oncomment(e){if(this.lastNode&&this.lastNode.type===ut.Comment){this.lastNode.data+=e;return}const t=new R0(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){const e=new Rv(""),t=new k0([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){const n=new C0(e,t);this.addNode(n)}handleCallback(e){if(typeof this.callback=="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){const t=this.tagStack[this.tagStack.length-1],n=t.children[t.children.length-1];this.options.withStartIndices&&this.parser&&(e.startIndex=this.parser.startIndex),this.options.withEndIndices&&this.parser&&(e.endIndex=this.parser.endIndex),t.children.push(e),n&&(e.prev=n,n.next=e),e.parent=t,this.lastNode=null}}const Lte=Object.freeze(Object.defineProperty({__proto__:null,CDATA:k0,Comment:R0,DataNode:Qm,Document:Cv,DomHandler:_x,Element:I0,Node:T0,NodeWithChildren:Zm,ProcessingInstruction:C0,Text:Rv,cloneNode:x0,default:_x,hasChildren:Nte,isCDATA:PU,isComment:AU,isDirective:DU,isDocument:NU,isTag:OU,isText:MU},Symbol.toStringTag,{value:"Module"})),LU=GU(Lte);var Ute=wi&&wi.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(w0,"__esModule",{value:!0});w0.default=UU;const jte=LU,qy=_,Fte=Ute(Hm),cd=_0,Bte={cloneElement:qy.cloneElement,createElement:qy.createElement,isValidElement:qy.isValidElement};function UU(r,e={}){var t,n,i,o,s;const a=[],l=typeof e.replace=="function",c=(t=e.transform)!==null&&t!==void 0?t:cd.returnFirstArg,{cloneElement:u,createElement:d,isValidElement:f}=(n=e.library)!==null&&n!==void 0?n:Bte,p=r.length;jU(r);for(let h=0;h<p;h++){const m=r[h];if(l){let R=(i=e.replace)===null||i===void 0?void 0:i.call(e,m,h);if(f(R)){p>1&&(R=u(R,{key:(o=R.key)!==null&&o!==void 0?o:h})),a.push(c(R,m,h));continue}}if(m.type==="text"){const R=!m.data.trim().length;if(R&&m.parent&&!(0,cd.canTextBeChildOfNode)(m.parent)||e.trim&&R)continue;a.push(c(m.data,m,h));continue}const E=m;let y={};Kte(E)?((0,cd.setStyleProp)(E.attribs.style,E.attribs),y=E.attribs):E.attribs&&(y=(0,Fte.default)(E.attribs,E.name));let S;switch(m.type){case"script":case"style":m.children[0]&&(y.dangerouslySetInnerHTML={__html:m.children[0].data});break;case"tag":m.name==="textarea"&&m.children[0]?y.defaultValue=m.children[0].data:!((s=m.children)===null||s===void 0)&&s.length&&(S=UU(m.children,e));break;default:continue}p>1&&(y.key=h),a.push(c(d(m.name,y,S),m,h))}return a.length===1?a[0]:a}function jU(r){for(const e of r)(e.type==="tag"||e.type==="script"||e.type==="style")&&(Object.setPrototypeOf(e,jte.Element.prototype),jU(e.children))}function Kte(r){return cd.PRESERVE_CUSTOM_ATTRIBUTES&&r.type==="tag"&&(0,cd.isCustomComponent)(r.name,r.attribs)}(function(r){var e=wi&&wi.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(r,"__esModule",{value:!0}),r.htmlToDOM=r.domToReact=r.attributesToProps=r.Text=r.ProcessingInstruction=r.Element=r.Comment=void 0,r.default=a;const t=e(v0);r.htmlToDOM=t.default;const n=e(Hm);r.attributesToProps=n.default;const i=e(w0);r.domToReact=i.default;var o=LU;Object.defineProperty(r,"Comment",{enumerable:!0,get:function(){return o.Comment}}),Object.defineProperty(r,"Element",{enumerable:!0,get:function(){return o.Element}}),Object.defineProperty(r,"ProcessingInstruction",{enumerable:!0,get:function(){return o.ProcessingInstruction}}),Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return o.Text}});const s={lowerCaseAttributeNames:!1};function a(l,c){var u;if(typeof l!="string")throw new TypeError("First argument must be a string");if(!l)return[];const d=Object.assign(Object.assign({},(u=c==null?void 0:c.htmlparser2)!==null&&u!==void 0?u:s),{trustedTypePolicy:c==null?void 0:c.trustedTypePolicy});return(0,i.default)((0,t.default)(l,d),c)}})(p0);const Ex=qa(p0),Vte=Ex.default||Ex,$te=["del","h1","h2","h3","h4","h5","h6","blockquote","p","a","ul","ol","sup","sub","li","b","i","u","strong","em","s","code","hr","br","div","table","thead","tbody","tr","th","td","caption","pre","span","img","details","summary"],Wte=["href","name","target","width","height","alt","title","src","start","class","data-mx-color","data-mx-bg-color","data-mx-spoiler"];function qte({userId:r,roomId:e}){const t=$o(r,e);return g.jsxs("span",{className:"rounded-sm bg-primary/15 px-1 font-medium",style:{color:$a(r)},title:r,children:["@",t]})}function Gte(r,e){return DL(r).map((t,n)=>t.userId?g.jsx(qte,{userId:t.userId,roomId:e},n):g.jsx(_.Fragment,{children:t.text},n))}function FU({html:r,roomId:e}){const t=_ee.sanitize(r,{ALLOWED_TAGS:$te,ALLOWED_ATTR:Wte,ALLOWED_URI_REGEXP:/^(?:(?:https?|ftp|mailto|magnet|matrix):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i}),n={replace:i=>{var o;if(i.type==="tag"&&i.name==="a"){const s=((o=i.attribs)==null?void 0:o.href)??"",a=i.children??[];return g.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer ugc",className:"text-primary underline",children:p0.domToReact(a,n)})}if(i.type==="text"){const s=i.data;return s.includes(":")?g.jsx(_.Fragment,{children:Gte(s,e)}):void 0}}};return g.jsx("div",{className:["prose prose-sm dark:prose-invert max-w-none min-w-0 break-words","prose-p:my-1 prose-headings:mt-3 prose-headings:mb-1","prose-pre:my-2 prose-pre:bg-muted prose-pre:text-foreground prose-pre:border prose-pre:border-border","prose-code:bg-muted prose-code:text-foreground prose-code:rounded-sm prose-code:px-1 prose-code:py-px prose-code:font-normal","prose-code:before:content-none prose-code:after:content-none","prose-a:text-primary prose-a:underline prose-a:underline-offset-2","prose-blockquote:border-muted-foreground/40 prose-blockquote:text-muted-foreground prose-blockquote:not-italic","prose-hr:border-border","prose-strong:text-foreground prose-headings:text-foreground"].join(" "),children:Vte(t,n)})}function Hte({...r}){return g.jsx(G$,{"data-slot":"popover",...r})}function zte({...r}){return g.jsx(H$,{"data-slot":"popover-trigger",...r})}function Yte({className:r,align:e="center",sideOffset:t=4,...n}){return g.jsx(z$,{children:g.jsx(Y$,{"data-slot":"popover-content",align:e,sideOffset:t,className:Le("z-50 w-72 rounded-md border border-border bg-popover p-3 text-popover-foreground shadow-md outline-none","data-[state=open]:animate-in data-[state=closed]:animate-out","data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",r),...n})})}const Jte=_.lazy(()=>FD(()=>import("./reaction-picker-emoji-xD2HkULN.js"),[]));function BU({roomId:r,eventId:e}){const[t,n]=_.useState(!1),i=de.safeGet(),o=async s=>{n(!1),i&&await i.sendEvent(r,"m.reaction",{"m.relates_to":{rel_type:"m.annotation",event_id:e,key:s}})};return g.jsxs(Hte,{open:t,onOpenChange:n,children:[g.jsx(zte,{asChild:!0,children:g.jsx("button",{type:"button","aria-label":"add reaction",className:"inline-flex items-center rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:g.jsx(VK,{className:"size-4"})})}),g.jsx(Yte,{align:"start",className:"w-auto p-0",children:g.jsx(_.Suspense,{fallback:g.jsx("div",{className:"p-3 text-xs",children:"Loading…"}),children:t&&g.jsx(Jte,{onPick:o})})})]})}function Xte({roomId:r,eventId:e,reactions:t}){const n=de.safeGet();if(t.size===0)return null;const i=async(o,s)=>{if(n){if(s.mine&&s.myEventId){await n.redactEvent(r,s.myEventId);return}await n.sendEvent(r,"m.reaction",{"m.relates_to":{rel_type:"m.annotation",event_id:e,key:o}})}};return g.jsxs("div",{"data-testid":"reactions-row",className:"mt-1 flex flex-wrap items-center gap-1",children:[Array.from(t.entries()).map(([o,s])=>g.jsxs("button",{type:"button","aria-label":`${o} ${s.count}`,onClick:()=>void i(o,s),className:`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs ${s.mine?"border-primary/60 bg-primary/10 text-primary":"border-border bg-muted/40 text-foreground hover:bg-muted"}`,children:[g.jsx("span",{children:o}),g.jsx("span",{className:"tabular-nums",children:s.count})]},o)),g.jsx("span",{className:"inline-flex items-center rounded-full border border-border bg-muted/40 px-1.5 py-0.5 hover:bg-muted",children:g.jsx(BU,{roomId:r,eventId:e})})]})}function Qte({userId:r}){const{presence:e}=iU(r);return g.jsx(l0,{userId:r,size:"sm",presence:e})}function Zte({userId:r,roomId:e}){const t=$o(r,e);return g.jsxs("span",{className:"rounded-sm bg-primary/15 px-1 font-medium",style:{color:$a(r)},title:r,children:["@",t]})}function ere({event:r}){const e=r.getContent(),t=r.getSender()??"?",n=r.getRoomId()??"",i=$o(t,n);if(r.getType()===Vi.Error){const s=typeof e.message=="string"?e.message:"Agent error";return g.jsxs("div",{className:"flex items-center gap-1.5 text-sm leading-5 text-muted-foreground",children:[g.jsx(zv,{className:"h-3.5 w-3.5 shrink-0"}),g.jsx("span",{className:"shrink-0 font-semibold",style:{color:$a(t)},children:i}),g.jsx("span",{className:"line-clamp-1 min-w-0 flex-1",children:s})]})}const o=e.format==="org.matrix.custom.html"&&typeof e.formatted_body=="string"&&e.formatted_body.length>0;return e.msgtype!=="m.text"&&e.msgtype!=="m.notice"?null:g.jsxs("div",{className:"flex items-baseline gap-1.5 text-sm leading-5",children:[g.jsx("span",{className:"shrink-0 font-semibold",style:{color:$a(t)},children:i}),o?g.jsx("div",{className:"line-clamp-2 min-w-0 flex-1 text-foreground/80",children:g.jsx(FU,{html:e.formatted_body,roomId:n})}):g.jsx("span",{className:"line-clamp-2 min-w-0 flex-1 text-foreground/80",children:e.body??""})]})}function tre({event:r,onReplyInThread:e,onViewThread:t,disableThreadAffordances:n}){const i=r.getContent(),o=r.getSender()??"?",s=i.body??"",a=r.getId()??"",l=r.getRoomId()??"",c=$o(o,l),u=i.format==="org.matrix.custom.html"&&typeof i.formatted_body=="string"&&i.formatted_body.length>0,{events:d,totalCount:f}=fU(l,n?"":a),p=WZ(l,a);return i.msgtype!=="m.text"&&i.msgtype!=="m.notice"?null:g.jsxs("div",{className:"group relative flex gap-2 py-1.5 hover:bg-muted/30",children:[g.jsx("div",{className:"mt-0.5 shrink-0",children:g.jsx(Qte,{userId:o})}),g.jsxs("div",{className:"min-w-0 flex-1",children:[g.jsx("span",{className:"font-semibold text-sm leading-6",style:{color:$a(o)},title:o,children:c}),u?g.jsx(FU,{html:i.formatted_body,roomId:l}):g.jsx("p",{className:"min-w-0 whitespace-pre-wrap break-words leading-6 text-foreground text-sm",children:DL(s).map((h,m)=>h.userId?g.jsx(Zte,{userId:h.userId,roomId:l},m):g.jsx("span",{children:h.text},m))}),g.jsx(Xte,{roomId:l,eventId:a,reactions:p}),!n&&f>0&&g.jsxs("div",{className:"mt-2 pl-3 border-l-2 border-muted-foreground/25 space-y-1",children:[f>3&&g.jsxs("button",{type:"button",onClick:()=>t==null?void 0:t(a),className:"text-xs text-primary hover:underline block",children:["View thread (",f," events)"]}),d.map(h=>g.jsx(ere,{event:h},h.getId()))]}),!n&&g.jsx("button",{type:"button","aria-label":"Reply in thread",onClick:()=>e==null?void 0:e(a),className:"mt-1 text-xs text-muted-foreground hover:text-foreground hover:underline",children:"Reply in thread"})]}),g.jsx("div",{className:"pointer-events-none absolute -top-3 right-2 z-10 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100",children:g.jsxs("div",{className:"flex items-center gap-1.5 rounded-md border border-border bg-background px-1.5 py-1 shadow-sm",children:[g.jsx(BU,{roomId:l,eventId:a}),!n&&g.jsx("button",{type:"button","aria-label":"Reply",onClick:()=>e==null?void 0:e(a),className:"inline-flex items-center rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:g.jsx(aM,{className:"size-4"})})]})})]})}function B_({event:r,onReplyInThread:e,onViewThread:t,disableThreadAffordances:n}){if(r.getType()==="m.room.message")return g.jsx(tre,{event:r,onReplyInThread:e,onViewThread:t,disableThreadAffordances:n});if(r.getType()===Oc.Request)return g.jsx(CZ,{event:r});if(r.getType()===Oc.Response)return null;if(r.getType()==="eco.zoon.session_reset")return g.jsxs("div",{className:"flex items-center gap-2 py-3 text-xs uppercase tracking-wider text-muted-foreground",children:[g.jsx("div",{className:"h-px flex-1 bg-border"}),g.jsx("span",{children:"new session"}),g.jsx("div",{className:"h-px flex-1 bg-border"})]});if(EZ(r)){const i=wZ(r);return i?i.kind==="error"?g.jsx(BZ,{decoded:i}):g.jsx(xZ,{decoded:i,sender:r.getSender()??"?",roomId:r.getRoomId()??"",ts:r.getTs()}):null}return null}function KU({loading:r,hasMore:e,onClick:t}){return!e&&!r?null:g.jsx("div",{className:"flex justify-center py-2",children:g.jsxs("button",{type:"button",onClick:t,disabled:r||!e,className:"flex items-center gap-1.5 rounded-md px-3 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[r&&g.jsx(Hv,{className:"h-3 w-3 animate-spin"}),r?"Loading…":"Load more"]})})}const wx=5;function rre(){return g.jsxs("div",{className:"flex gap-2 py-1.5","aria-busy":"true","aria-label":"Loading thread parent",children:[g.jsx("div",{className:"mt-0.5 h-7 w-7 shrink-0 rounded-full bg-muted animate-pulse"}),g.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[g.jsx("div",{className:"h-3 w-24 rounded bg-muted animate-pulse"}),g.jsx("div",{className:"h-3 w-3/4 rounded bg-muted animate-pulse"})]})]})}function nre({roomId:r,rootEventId:e,onBack:t}){const{root:n,rootPending:i,events:o,totalCount:s}=sZ(r,e),{loadMore:a,loading:l}=yZ(r,e),c=o.length<s,u=_.useRef(null),d=_.useRef(!0),f=_.useRef(null);function p(){const h=u.current;h&&(d.current=h.scrollHeight-h.scrollTop-h.clientHeight<50)}return _.useEffect(()=>{const h=u.current;!h||!d.current||(h.scrollTop=h.scrollHeight)},[o]),_.useEffect(()=>{const h=`${r}:${e}`;f.current!==h&&(o.length===0&&i||(c&&o.length<wx?(f.current=h,a()):(!c||o.length>=wx)&&(f.current=h)))},[r,e,c,o.length,i,a]),g.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[g.jsxs("header",{className:"flex items-center gap-2 border-b border-border px-3 py-2 shrink-0",children:[g.jsxs("button",{type:"button",onClick:t,"aria-label":"Back to room",className:"flex items-center gap-1 rounded px-2 py-1 text-sm text-muted-foreground hover:bg-muted hover:text-foreground",children:[g.jsx(cK,{className:"h-4 w-4"}),"Back"]}),g.jsxs("span",{className:"text-sm font-medium",children:["Thread ",s>0?`(${s} ${s===1?"event":"events"})`:""]})]}),g.jsxs("div",{ref:u,onScroll:p,className:"flex-1 min-h-0 overflow-y-auto",children:[o.length>0&&g.jsx(KU,{loading:l,hasMore:c,onClick:a}),g.jsxs("ol",{className:"flex flex-col gap-0.5 px-4 py-3",children:[g.jsx("li",{children:n?g.jsx(B_,{event:n,disableThreadAffordances:!0}):i?g.jsx(rre,{}):g.jsx("div",{className:"text-sm text-muted-foreground italic py-2",children:"Thread root unavailable."})}),o.map(h=>g.jsx("li",{children:g.jsx(B_,{event:h,disableThreadAffordances:!0})},h.getId()??`${h.getType()}-${h.getTs()}`))]})]})]})}function Gy(r){const e=de.safeGet(),t=e==null?void 0:e.getRoom(r);return t?t.getLiveTimeline().getPaginationToken(Ge.Backward)!==null:!1}function ire(r,e=50){const[t,n]=_.useState(()=>({loading:!1,hasMore:Gy(r)}));return _.useEffect(()=>{n(l=>({...l,hasMore:Gy(r)}));const o=de.safeGet(),s=o==null?void 0:o.getRoom(r);if(!o||!s)return;const a=()=>{n(l=>{const c=Gy(r);return c===l.hasMore?l:{...l,hasMore:c}})};return s.on(pe.Timeline,a),()=>{s.off(pe.Timeline,a)}},[r]),{loadMore:_.useCallback(async()=>{if(t.loading||!t.hasMore)return;const o=de.safeGet(),s=o==null?void 0:o.getRoom(r);if(!(!o||!s)){n(a=>({...a,loading:!0}));try{const a=s.getLiveTimeline(),l=await o.paginateEventTimeline(a,{backwards:!0,limit:e});n({loading:!1,hasMore:l})}catch(a){console.warn(`[useLoadMoreHistory] paginate(${r}) failed:`,a),n({loading:!1,hasMore:!1})}}},[r,e,t.loading,t.hasMore]),loading:t.loading,hasMore:t.hasMore}}function ore(){return g.jsxs("div",{className:"flex gap-2 py-1.5","aria-busy":"true","aria-label":"Loading thread parent",children:[g.jsx("div",{className:"mt-0.5 h-7 w-7 shrink-0 rounded-full bg-muted animate-pulse"}),g.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[g.jsx("div",{className:"h-3 w-24 rounded bg-muted animate-pulse"}),g.jsx("div",{className:"h-3 w-3/4 rounded bg-muted animate-pulse"})]})]})}function sre({events:r,pendingRootIds:e,onReplyInThread:t,onViewThread:n}){return g.jsxs("ol",{className:"flex flex-col gap-0.5 px-4 py-3",children:[e==null?void 0:e.map(i=>g.jsx("li",{children:g.jsx(ore,{})},`skeleton-${i}`)),r.map(i=>g.jsx("li",{children:g.jsx(B_,{event:i,onReplyInThread:t,onViewThread:n})},i.getId()??`${i.getType()}-${i.getTs()}`))]})}const Tx=5;function are({roomId:r,onReplyInThread:e,onViewThread:t}){const{events:n,pendingRootIds:i}=dU(r),{loadMore:o,loading:s,hasMore:a}=ire(r),l=_.useRef(null),c=_.useRef(!0),u=_.useRef(null);function d(){const f=l.current;f&&(c.current=f.scrollHeight-f.scrollTop-f.clientHeight<50)}return _.useEffect(()=>{const f=l.current;!f||!c.current||(f.scrollTop=f.scrollHeight)},[n]),_.useEffect(()=>{u.current!==r&&(a&&n.length<Tx?(u.current=r,o()):(!a||n.length>=Tx)&&(u.current=r))},[r,a,n.length,o]),g.jsxs("div",{ref:l,onScroll:d,className:"h-full overflow-y-auto",children:[n.length>0&&g.jsx(KU,{loading:s,hasMore:a,onClick:o}),g.jsx(sre,{events:n,pendingRootIds:i,onReplyInThread:e,onViewThread:t})]})}function lre(r){const t=r.getLiveTimeline().getEvents();for(let n=t.length-1;n>=0;n--){const i=t[n];if(i.getType()==="m.room.message")return i}return t[t.length-1]??null}function cre(r){_.useEffect(()=>{const e=de.safeGet(),t=e==null?void 0:e.getRoom(r);if(!e||!t)return;let n=null;const i=()=>{const s=lre(t);if(!s)return;const a=s.getId()??null;a!==null&&a===n||(n=a,e.sendReadReceipt(s).catch(()=>{}))};i();const o=()=>i();return t.on(pe.Timeline,o),()=>{t.off(pe.Timeline,o)}},[r])}const Hy=[];function Rx(r){const e=de.safeGet();if(!e)return Hy;const t=e.getUserId()??"",n=e.getRoom(r);if(!n)return Hy;const i=n.currentState.getMembers().filter(o=>o.typing&&o.userId!==t).map(o=>o.userId);return i.length===0?Hy:i}function ure(r){const[e,t]=_.useState(()=>Rx(r));return _.useEffect(()=>{const n=de.safeGet();if(!n)return;const i=()=>t(Rx(r));return n.on(Ar.Typing,i),()=>{n.off(Ar.Typing,i)}},[r]),e}function dre(){const{roomId:r}=YF(),[e,t]=nM(),n=e.get("thread"),i=ure(r??"");cre(r??"");function o(a){t({thread:a})}function s(){t({})}return r?g.jsxs("article",{className:"flex h-full min-h-0 flex-col",children:[g.jsx("div",{className:"min-h-0 flex-1",children:n?g.jsx(nre,{roomId:r,rootEventId:n,onBack:s}):g.jsx(are,{roomId:r,onReplyInThread:o,onViewThread:o})}),g.jsx(gZ,{typingUserIds:i,roomId:r}),g.jsx(vZ,{roomId:r,threadRootEventId:n,onExitThread:s})]}):g.jsx("div",{children:"No room selected"})}function fre(){return _.useSyncExternalStore(r=>de.subscribe(r),()=>de.safeGet()?"logged-in":"logged-out",()=>"logged-out")}function hre({config:r,initialRoute:e}){const[t,n]=_.useState(!1);return _.useEffect(()=>{if(!de.restoreFromStorage()){n(!0);return}let o=!1;return(async()=>{var s;try{await de.get().whoami()}catch(a){const l=a,c=l.errcode??((s=l.data)==null?void 0:s.errcode);(c==="M_UNKNOWN_TOKEN"||c==="M_MISSING_TOKEN"||c==="M_FORBIDDEN"||l.httpStatus===401)&&de.reset()}o||n(!0)})(),()=>{o=!0}},[]),t?e?g.jsxs(eb,{children:[g.jsx(uB,{initialEntries:[e],children:g.jsx(Cx,{config:r})}),g.jsx(uR,{})]}):g.jsxs(eb,{children:[g.jsx(bB,{children:g.jsx(Cx,{config:r})}),g.jsx(uR,{})]}):g.jsx("div",{role:"status",children:"Loading…"})}function Cx({config:r}){const e=fre(),t=Vs();return _.useEffect(()=>{e==="logged-out"&&window.location.pathname!=="/auth/callback"&&t("/login",{replace:!0})},[e,t]),g.jsxs(fB,{children:[g.jsxs(ca,{path:"/",element:e==="logged-in"?g.jsx(XQ,{}):g.jsx(Vp,{to:"/login",replace:!0}),children:[g.jsx(ca,{index:!0,element:g.jsx(ZJ,{})}),g.jsx(ca,{path:"room/:roomId",element:g.jsx(dre,{})}),g.jsx(ca,{path:"browse",element:g.jsx(OJ,{})})]}),g.jsx(ca,{path:"/login",element:e==="logged-in"?g.jsx(Vp,{to:"/",replace:!0}):g.jsx(IJ,{homeserverUrl:r.homeserverUrl,defaultIdpLabel:r.defaultIdpLabel??null})}),g.jsx(ca,{path:"/auth/callback",element:g.jsx(TJ,{homeserverUrl:r.homeserverUrl})})]})}const pre=_.createContext({theme:"system",setTheme:()=>null}),kx="zoon-ui-theme";function vre({children:r,defaultTheme:e="system"}){const[t,n]=_.useState(()=>localStorage.getItem(kx)??e);_.useEffect(()=>{const o=window.document.documentElement;if(o.classList.remove("light","dark"),t==="system"){const s=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";o.classList.add(s)}else o.classList.add(t)},[t]);const i=o=>{localStorage.setItem(kx,o),n(o)};return g.jsx(pre.Provider,{value:{theme:t,setTheme:i},children:r})}async function mre(r){var e;if((e=r.runtimeConfig)!=null&&e.homeserver_url)return r.runtimeConfig.homeserver_url;if(r.buildtimeUrl)return r.buildtimeUrl;throw new Error("No homeserver URL could be resolved")}async function gre(){try{const r=await fetch("/config.json",{cache:"no-store"});if(!r.ok)return null;const e=await r.json(),t={};return typeof e.homeserver_url=="string"&&(t.homeserver_url=e.homeserver_url),typeof e.default_idp_label=="string"&&(t.default_idp_label=e.default_idp_label),t}catch{return null}}const yre=null;async function Sre(){const r=await gre(),t={homeserverUrl:await mre({runtimeConfig:r,buildtimeUrl:yre}),defaultIdpLabel:(r==null?void 0:r.default_idp_label)??null};KP(document.getElementById("root")).render(g.jsx(_.StrictMode,{children:g.jsx(vre,{defaultTheme:"system",children:g.jsx(hre,{config:t})})}))}Sre().catch(r=>{console.error("Bootstrap failed:",r),document.body.innerHTML=`<pre>Bootstrap failed: ${String((r==null?void 0:r.message)??r)}</pre>`});export{ve as $,F8 as A,hv as B,Yt as C,Ww as D,V as E,Io as F,Tk as G,Jw as H,ot as I,Gt as J,Be as K,wre as L,Z as M,cr as N,Lt as O,ns as P,wl as Q,_e as R,$i as S,tn as T,sd as U,pa as V,Sc as W,Cf as X,_ as Y,g as Z,v as _,w as a,Cre as b,wi as c,Dr as d,Rm as e,Se as f,lN as g,To as h,_N as i,Tt as j,Vc as k,b as l,zs as m,Hw as n,xi as o,Om as p,Hs as q,hr as r,As as s,Pt as t,N8 as u,Zr as v,MN as w,qw as x,Ei as y,$w as z};