@whereby.com/browser-sdk 3.12.19 → 3.12.21

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,3 +1,3 @@
1
- this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function i(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}function n(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if("default"!==r&&!(r in e)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(e)}var s=i(t),o=i(r),a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d,l={exports:{}},u={};l.exports=(d||(d=1,function(){"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=t,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},i=e.useSyncExternalStore,n=e.useRef,s=e.useEffect,o=e.useMemo,a=e.useDebugValue;u.useSyncExternalStoreWithSelector=function(e,t,c,d,l){var u=n(null);if(null===u.current){var p={hasValue:!1,value:null};u.current=p}else p=u.current;u=o(function(){function e(e){if(!s){if(s=!0,i=e,e=d(e),void 0!==l&&p.hasValue){var t=p.value;if(l(t,e))return n=t}return n=e}if(t=n,r(i,e))return t;var o=d(e);return void 0!==l&&l(t,o)?(i=e,t):(i=e,n=o)}var i,n,s=!1,o=void 0===c?null:c;return[function(){return e(t())},null===o?void 0:function(){return e(o())}]},[t,c,d,l]);var h=i(e,u[0],u[1]);return s(function(){p.hasValue=!0,p.value=h},[h]),a(h),h},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),u);var p=l.exports;var h={notify(){},get:()=>[]};var f=(()=>!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement))(),m=(()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product)(),g=(()=>f||m?s.useLayoutEffect:s.useEffect)(),v=Symbol.for("react-redux-context"),b="undefined"!=typeof globalThis?globalThis:{};function y(){if(!s.createContext)return{};const e=b[v]??=new Map;let t=e.get(s.createContext);return t||(t=s.createContext(null),t.displayName="ReactRedux",e.set(s.createContext,t)),t}var w=y();var _=function(e){const{children:t,context:r,serverState:i,store:n}=e,o=s.useMemo(()=>{const t=function(e){let t,r=h,i=0,n=!1;function s(){c.onStateChange&&c.onStateChange()}function o(){i++,t||(t=e.subscribe(s),r=function(){let e=null,t=null;return{clear(){e=null,t=null},notify(){var t;t=()=>{let t=e;for(;t;)t.callback(),t=t.next},t()},get(){const t=[];let r=e;for(;r;)t.push(r),r=r.next;return t},subscribe(r){let i=!0;const n=t={callback:r,next:null,prev:t};return n.prev?n.prev.next=n:e=n,function(){i&&null!==e&&(i=!1,n.next?n.next.prev=n.prev:t=n.prev,n.prev?n.prev.next=n.next:e=n.next)}}}}())}function a(){i--,t&&0===i&&(t(),t=void 0,r.clear(),r=h)}const c={addNestedSub:function(e){o();const t=r.subscribe(e);let i=!1;return()=>{i||(i=!0,t(),a())}},notifyNestedSubs:function(){r.notify()},handleChangeWrapper:s,isSubscribed:function(){return n},trySubscribe:function(){n||(n=!0,o())},tryUnsubscribe:function(){n&&(n=!1,a())},getListeners:()=>r};return c}(n),r={store:n,subscription:t,getServerState:i?()=>i:void 0};{const{identityFunctionCheck:t="once",stabilityCheck:i="once"}=e;return Object.assign(r,{stabilityCheck:i,identityFunctionCheck:t})}},[n,i]),a=s.useMemo(()=>n.getState(),[n]);g(()=>{const{subscription:e}=o;return e.onStateChange=e.notifyNestedSubs,e.trySubscribe(),a!==n.getState()&&e.notifyNestedSubs(),()=>{e.tryUnsubscribe(),e.onStateChange=void 0}},[o,a]);const c=r||w;return s.createElement(c.Provider,{value:o},t)};function S(e=w){return function(){const t=s.useContext(e);if(!t)throw new Error("could not find react-redux context value; please ensure the component is wrapped in a <Provider>");return t}}var C=S();function R(e=w){const t=e===w?C:S(e),r=()=>{const{store:e}=t();return e};return Object.assign(r,{withTypes:()=>r}),r}var k=R();var T=(e,t)=>e===t;var P=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),O=()=>Math.random().toString(36).substring(7).split("").join("."),E={INIT:`@@redux/INIT${O()}`,REPLACE:`@@redux/REPLACE${O()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${O()}`};function D(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function x(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const r=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(r){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return r}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function I(e){let t=typeof e;return t=x(e),t}function M(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${I(e)}'`);if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(`Expected the enhancer to be a function. Instead, received: '${I(r)}'`);return r(M)(e,t)}let i=e,n=t,s=new Map,o=s,a=0,c=!1;function d(){o===s&&(o=new Map,s.forEach((e,t)=>{o.set(t,e)}))}function l(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return n}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${I(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;d();const r=a++;return o.set(r,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,d(),o.delete(r),s=null}}}function p(e){if(!D(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${I(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${I(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,n=i(n,e)}finally{c=!1}return(s=o).forEach(e=>{e()}),e}p({type:E.INIT});return{dispatch:p,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${I(e)}`);i=e,p({type:E.REPLACE})},[P]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${I(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[P](){return this}}}}}function j(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function L(e){const t=Object.keys(e),r={};for(let i=0;i<t.length;i++){const n=t[i];void 0===e[n]&&j(`No reducer provided for key "${n}"`),"function"==typeof e[n]&&(r[n]=e[n])}const i=Object.keys(r);let n,s;n={};try{!function(e){Object.keys(e).forEach(t=>{const r=e[t];if(void 0===r(void 0,{type:E.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===r(void 0,{type:E.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${E.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)})}(r)}catch(e){s=e}return function(e={},t){if(s)throw s;{const i=function(e,t,r,i){const n=Object.keys(t),s=r&&r.type===E.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===n.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!D(e))return`The ${s} has unexpected type of "${I(e)}". Expected argument to be an object with the following keys: "${n.join('", "')}"`;const o=Object.keys(e).filter(e=>!t.hasOwnProperty(e)&&!i[e]);return o.forEach(e=>{i[e]=!0}),r&&r.type===E.REPLACE?void 0:o.length>0?`Unexpected ${o.length>1?"keys":"key"} "${o.join('", "')}" found in ${s}. Expected to find one of the known reducer keys instead: "${n.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,n);i&&j(i)}let o=!1;const a={};for(let n=0;n<i.length;n++){const s=i[n],c=r[s],d=e[s],l=c(d,t);if(void 0===l){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${s}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[s]=l,o=o||l!==d}return o=o||i.length!==Object.keys(e).length,o?a:e}}function A(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...r)=>e(t(...r)))}function N(e){return D(e)&&"type"in e&&"string"==typeof e.type}var B=Symbol.for("immer-nothing"),F=Symbol.for("immer-draftable"),z=Symbol.for("immer-state"),V=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function U(e,...t){{const r=V[e],i="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}}var $=Object.getPrototypeOf;function G(e){return!!e&&!!e[z]}function q(e){return!!e&&(W(e)||Array.isArray(e)||!!e[F]||!!e.constructor?.[F]||X(e)||Z(e))}var H=Object.prototype.constructor.toString();function W(e){if(!e||"object"!=typeof e)return!1;const t=$(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===H}function K(e,t){0===J(e)?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,i)=>t(i,r,e))}function J(e){const t=e[z];return t?t.type_:Array.isArray(e)?1:X(e)?2:Z(e)?3:0}function Q(e,t){return 2===J(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Y(e,t,r){const i=J(e);2===i?e.set(t,r):3===i?e.add(r):e[t]=r}function X(e){return e instanceof Map}function Z(e){return e instanceof Set}function ee(e){return e.copy_||e.base_}function te(e,t){if(X(e))return new Map(e);if(Z(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=W(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[z];let r=Reflect.ownKeys(t);for(let i=0;i<r.length;i++){const n=r[i],s=t[n];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(t[n]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[n]})}return Object.create($(e),t)}{const t=$(e);if(null!==t&&r)return{...e};const i=Object.create(t);return Object.assign(i,e)}}function re(e,t=!1){return ne(e)||G(e)||!q(e)||(J(e)>1&&(e.set=e.add=e.clear=e.delete=ie),Object.freeze(e),t&&Object.entries(e).forEach(([e,t])=>re(t,!0))),e}function ie(){U(2)}function ne(e){return Object.isFrozen(e)}var se,oe={};function ae(e){const t=oe[e];return t||U(0,e),t}function ce(){return se}function de(e,t){t&&(ae("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function le(e){ue(e),e.drafts_.forEach(he),e.drafts_=null}function ue(e){e===se&&(se=e.parent_)}function pe(e){return se={drafts_:[],parent_:se,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function he(e){const t=e[z];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function fe(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[z].modified_&&(le(t),U(4)),q(e)&&(e=me(t,e),t.parent_||ve(t,e)),t.patches_&&ae("Patches").generateReplacementPatches_(r[z].base_,e,t.patches_,t.inversePatches_)):e=me(t,r,[]),le(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==B?e:void 0}function me(e,t,r){if(ne(t))return t;const i=t[z];if(!i)return K(t,(n,s)=>ge(e,i,t,n,s,r)),t;if(i.scope_!==e)return t;if(!i.modified_)return ve(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const t=i.copy_;let n=t,s=!1;3===i.type_&&(n=new Set(t),t.clear(),s=!0),K(n,(n,o)=>ge(e,i,t,n,o,r,s)),ve(e,t,!1),r&&e.patches_&&ae("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function ge(e,t,r,i,n,s,o){if(n===r&&U(5),G(n)){const o=me(e,n,s&&t&&3!==t.type_&&!Q(t.assigned_,i)?s.concat(i):void 0);if(Y(r,i,o),!G(o))return;e.canAutoFreeze_=!1}else o&&r.add(n);if(q(n)&&!ne(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;me(e,n),t&&t.scope_.parent_||"symbol"==typeof i||!Object.prototype.propertyIsEnumerable.call(r,i)||ve(e,n)}}function ve(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&re(t,r)}var be={get(e,t){if(t===z)return e;const r=ee(e);if(!Q(r,t))return function(e,t,r){const i=_e(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}(e,r,t);const i=r[t];return e.finalized_||!q(i)?i:i===we(e.base_,t)?(Ce(e),e.copy_[t]=Re(i,e)):i},has:(e,t)=>t in ee(e),ownKeys:e=>Reflect.ownKeys(ee(e)),set(e,t,r){const i=_e(ee(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){const i=we(ee(e),t),o=i?.[z];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((n=r)===(s=i)?0!==n||1/n==1/s:n!=n&&s!=s)&&(void 0!==r||Q(e.base_,t)))return!0;Ce(e),Se(e)}var n,s;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==we(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,Ce(e),Se(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=ee(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:i.enumerable,value:r[t]}:i},defineProperty(){U(11)},getPrototypeOf:e=>$(e.base_),setPrototypeOf(){U(12)}},ye={};function we(e,t){const r=e[z];return(r?ee(r):e)[t]}function _e(e,t){if(!(t in e))return;let r=$(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=$(r)}}function Se(e){e.modified_||(e.modified_=!0,e.parent_&&Se(e.parent_))}function Ce(e){e.copy_||(e.copy_=te(e.base_,e.scope_.immer_.useStrictShallowCopy_))}K(be,(e,t)=>{ye[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),ye.deleteProperty=function(e,t){return isNaN(parseInt(t))&&U(13),ye.set.call(this,e,t,void 0)},ye.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&U(14),be.set.call(this,e[0],t,r,e[0])};function Re(e,t){const r=X(e)?ae("MapSet").proxyMap_(e,t):Z(e)?ae("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:ce(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let n=i,s=be;r&&(n=[i],s=ye);const{revoke:o,proxy:a}=Proxy.revocable(n,s);return i.draft_=a,i.revoke_=o,a}(e,t);return(t?t.scope_:ce()).drafts_.push(r),r}function ke(e){if(!q(e)||ne(e))return e;const t=e[z];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=te(e,t.scope_.immer_.useStrictShallowCopy_)}else r=te(e,!0);return K(r,(e,t)=>{Y(r,e,ke(t))}),t&&(t.finalized_=!1),r}var Te=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const i=this;return function(e=r,...n){return i.produce(e,e=>t.call(this,e,...n))}}let i;if("function"!=typeof t&&U(6),void 0!==r&&"function"!=typeof r&&U(7),q(e)){const n=pe(this),s=Re(e,void 0);let o=!0;try{i=t(s),o=!1}finally{o?le(n):ue(n)}return de(n,r),fe(i,n)}if(!e||"object"!=typeof e){if(i=t(e),void 0===i&&(i=e),i===B&&(i=void 0),this.autoFreeze_&&re(i,!0),r){const t=[],n=[];ae("Patches").generateReplacementPatches_(e,i,t,n),r(t,n)}return i}U(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,i;return[this.produce(e,t,(e,t)=>{r=e,i=t}),r,i]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){q(e)||U(8),G(e)&&(e=function(e){G(e)||U(10,e);return ke(e)}(e));const t=pe(this),r=Re(e,void 0);return r[z].isManual_=!0,ue(t),r}finishDraft(e,t){const r=e&&e[z];r&&r.isManual_||U(9);const{scope_:i}=r;return de(i,t),fe(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const i=t[r];if(0===i.path.length&&"replace"===i.op){e=i.value;break}}r>-1&&(t=t.slice(r+1));const i=ae("Patches").applyPatches_;return G(e)?i(e,t):this.produce(e,e=>i(e,t))}},Pe=Te.produce;Te.produceWithPatches.bind(Te),Te.setAutoFreeze.bind(Te),Te.setUseStrictShallowCopy.bind(Te),Te.applyPatches.bind(Te),Te.createDraft.bind(Te),Te.finishDraft.bind(Te);var Oe=(e,t,r)=>{if(1===t.length&&t[0]===r){let t=!1;try{const r={};e(r)===r&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},Ee=(e,t,r)=>{const{memoize:i,memoizeOptions:n}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=i(()=>({}),...n);if(!(a.apply(null,s)===a.apply(null,o))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:r,firstInputs:s,secondInputs:o,stack:e})}},De={inputStabilityCheck:"once",identityFunctionCheck:"once"};var xe=e=>Array.isArray(e)?e:[e];function Ie(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const r=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${r}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Me(e,t){const r=[],{length:i}=e;for(let n=0;n<i;n++)r.push(e[n].apply(null,t));return r}var je="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function Le(){return{s:0,v:void 0,o:null,p:null}}function Ae(e,t={}){let r={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:i}=t;let n,s=0;function o(){let t=r;const{length:o}=arguments;for(let e=0,r=o;e<r;e++){const r=arguments[e];if("function"==typeof r||"object"==typeof r&&null!==r){let e=t.o;null===e&&(t.o=e=new WeakMap);const i=e.get(r);void 0===i?(t=Le(),e.set(r,t)):t=i}else{let e=t.p;null===e&&(t.p=e=new Map);const i=e.get(r);void 0===i?(t=Le(),e.set(r,t)):t=i}}const a=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),s++,i){const e=n?.deref?.()??n;null!=e&&i(e,c)&&(c=e,0!==s&&s--);n="object"==typeof c&&null!==c||"function"==typeof c?new je(c):c}return a.s=1,a.v=c,c}return o.clearCache=()=>{r={s:0,v:void 0,o:null,p:null},o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function Ne(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,i=(...e)=>{let t,i=0,n=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const a={...r,...s},{memoize:c,memoizeOptions:d=[],argsMemoize:l=Ae,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=xe(d),f=xe(u),m=Ie(e),g=c(function(){return i++,o.apply(null,arguments)},...h);let v=!0;const b=l(function(){n++;const e=Me(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:i}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:i}={...De,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:Oe},inputStabilityCheck:{shouldRun:"always"===i||"once"===i&&e,run:Ee}}})(v,p);if(r.shouldRun&&r.run(o,e,t),i.shouldRun){const t=Me(m,arguments);i.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:h},arguments)}v&&(v=!1)}return t},...f);return Object.assign(b,{resultFunc:o,memoizedResultFunc:g,dependencies:m,dependencyRecomputations:()=>n,resetDependencyRecomputations:()=>{n=0},lastResult:()=>t,recomputations:()=>i,resetRecomputations:()=>{i=0},memoize:c,argsMemoize:l})};return Object.assign(i,{withTypes:()=>i}),i}var Be=Ne(Ae),Fe=Object.assign((e,t=Be)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const r=Object.keys(e),i=t(r.map(t=>e[t]),(...e)=>e.reduce((e,t,i)=>(e[r[i]]=t,e),{}));return i},{withTypes:()=>Fe});function ze(e){return({dispatch:t,getState:r})=>i=>n=>"function"==typeof n?n(t,r,e):i(n)}var Ve=ze(),Ue=ze,$e="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?A:A.apply(null,arguments)},Ge=e=>e&&"function"==typeof e.match;function qe(e,t){function r(...r){if(t){let i=t(...r);if(!i)throw new Error("prepareAction did not return an object");return{type:e,payload:i.payload,..."meta"in i&&{meta:i.meta},..."error"in i&&{error:i.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>N(t)&&t.type===e,r}function He(e){return"function"==typeof e&&"type"in e&&Ge(e)}function We(e,t){let r=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();r+=e-t}},warnIfExceeded(){r>e&&console.warn(`${t} took ${r}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}var Ke=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Je(e){return q(e)?Pe(e,()=>{}):e}function Qe(e,t,r){return e.has(t)?e.get(t):e.set(t,r(t)).get(t)}function Ye(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function Xe(e,t,r){const i=Ze(e,t,r);return{detectMutations:()=>et(e,t,i,r)}}function Ze(e,t=[],r,i="",n=new Set){const s={value:r};if(!e(r)&&!n.has(r)){n.add(r),s.children={};for(const n in r){const o=i?i+"."+n:n;t.length&&-1!==t.indexOf(o)||(s.children[n]=Ze(e,t,r[n],o))}}return s}function et(e,t=[],r,i,n=!1,s=""){const o=r?r.value:void 0,a=o===i;if(n&&!a&&!Number.isNaN(i))return{wasMutated:!0,path:s};if(e(o)||e(i))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in i)c[e]=!0;const d=t.length>0;for(let n in c){const o=s?s+"."+n:n;if(d){if(t.some(e=>e instanceof RegExp?e.test(o):o===e))continue}const c=et(e,t,r.children[n],i[n],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function tt(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||D(e)}function rt(e,t="",r=tt,i,n=[],s){let o;if(!r(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(s?.has(e))return!1;const a=null!=i?i(e):Object.entries(e),c=n.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(n.some(e=>e instanceof RegExp?e.test(a):a===e))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=rt(d,a,r,i,n,s),o))return o}return s&&it(e)&&s.add(e),!1}function it(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!it(t))return!1;return!0}function nt(e){return"boolean"==typeof e}var st=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:i=!0,actionCreatorCheck:n=!0}=e??{};let s=new Ke;if(t&&(nt(t)?s.push(Ve):s.push(Ue(t.extraArgument))),r){let e={};nt(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,i,n){return JSON.stringify(e,r(t,n),i)},r=function(e,t){let r=[],i=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+i.slice(0,r.indexOf(t)).join(".")+"]"}),function(n,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?i.splice(o,1/0,n):i.push(n),~r.indexOf(s)&&(s=t.call(this,n,s))}else r.push(s);return null==e?s:e.call(this,n,s)}},{isImmutable:i=Ye,ignoredPaths:n,warnAfter:s=32}=e;const o=Xe.bind(null,i,n);return({getState:e})=>{let r,i=e(),n=o(i);return a=>c=>{const d=We(s,"ImmutableStateInvariantMiddleware");d.measureTime(()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${r.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)});const l=a(c);return d.measureTime(()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${r.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}),d.warnIfExceeded(),l}}}}(e))}if(i){let e={};nt(i)||(e=i),s.push(function(e={}){{const{isSerializable:t=tt,getEntries:r,ignoredActions:i=[],ignoredActionPaths:n=["meta.arg","meta.baseQueryMeta"],ignoredPaths:s=[],warnAfter:o=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:d=!1}=e,l=!d&&WeakSet?new WeakSet:void 0;return e=>d=>u=>{if(!N(u))return d(u);const p=d(u),h=We(o,"SerializableStateInvariantMiddleware");return c||i.length&&-1!==i.indexOf(u.type)||h.measureTime(()=>{const e=rt(u,"",t,r,n,l);if(e){const{keyPath:t,value:r}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,r,"\nTake a look at the logic that dispatched this action: ",u,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}}),a||(h.measureTime(()=>{const i=rt(e.getState(),"",t,r,s,l);if(i){const{keyPath:e,value:t}=i;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${u.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}}),h.warnIfExceeded()),p}}}(e))}if(n){let e={};nt(n)||(e=n),s.unshift(function(e={}){const{isActionCreator:t=He}=e;return()=>e=>r=>(t(r)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}(r.type)),e(r))}(e))}return s},ot=e=>t=>{setTimeout(t,e)},at=e=>function(t){const{autoBatch:r=!0}=t??{};let i=new Ke(e);return r&&i.push(((e={type:"raf"})=>t=>(...r)=>{const i=t(...r);let n=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:ot(10):"callback"===e.type?e.queueNotification:ot(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach(e=>e()))};return Object.assign({},i,{subscribe(e){const t=i.subscribe(()=>n&&e());return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return n=!e?.meta?.RTK_autoBatch,s=!n,s&&(o||(o=!0,c(d))),i.dispatch(e)}finally{n=!0}}})})("object"==typeof r?r:void 0)),i};function ct(e){const t=st(),{reducer:r,middleware:i,devTools:n=!0,duplicateMiddlewareCheck:s=!0,preloadedState:o,enhancers:a}=e||{};let c,d;if("function"==typeof r)c=r;else{if(!D(r))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");c=L(r)}if(i&&"function"!=typeof i)throw new Error("`middleware` field must be a callback");if("function"==typeof i){if(d=i(t),!Array.isArray(d))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else d=t();if(d.some(e=>"function"!=typeof e))throw new Error("each middleware provided to configureStore must be a function");if(s){let e=new Set;d.forEach(t=>{if(e.has(t))throw new Error("Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");e.add(t)})}let l=A;n&&(l=$e({trace:!0,..."object"==typeof n&&n}));const u=function(...e){return t=>(r,i)=>{const n=t(r,i);let s=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const o={getState:n.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map(e=>e(o));return s=A(...a)(n.dispatch),{...n,dispatch:s}}}(...d),p=at(u);if(a&&"function"!=typeof a)throw new Error("`enhancers` field must be a callback");let h="function"==typeof a?a(p):p();if(!Array.isArray(h))throw new Error("`enhancers` callback must return an array");if(h.some(e=>"function"!=typeof e))throw new Error("each enhancer provided to configureStore must be a function");d.length&&!h.includes(u)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return M(c,o,l(...h))}function dt(e){const t={},r=[];let i;const n={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(i)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const o="string"==typeof e?e:e.type;if(!o)throw new Error("`builder.addCase` cannot be called with an empty action type");if(o in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${o}'`);return t[o]=s,n},addMatcher(e,t){if(i)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),n},addDefaultCase(e){if(i)throw new Error("`builder.addDefaultCase` can only be called once");return i=e,n}};return e(n),[t,r,i]}function lt(...e){return t=>e.some(e=>((e,t)=>Ge(e)?e.match(t):e(t))(e,t))}var ut=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t},pt=["name","message","stack","code"],ht=class{constructor(e,t){this.payload=e,this.meta=t}_type},ft=class{constructor(e,t){this.payload=e,this.meta=t}_type},mt=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of pt)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},gt="External signal was aborted",vt=(()=>{function e(e,t,r){const i=qe(e+"/fulfilled",(e,t,r,i)=>({payload:e,meta:{...i||{},arg:r,requestId:t,requestStatus:"fulfilled"}})),n=qe(e+"/pending",(e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}})),s=qe(e+"/rejected",(e,t,i,n,s)=>({payload:n,error:(r&&r.serializeError||mt)(e||"Rejected"),meta:{...s||{},arg:i,requestId:t,rejectedWithValue:!!n,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}}));return Object.assign(function(e,{signal:o}={}){return(a,c,d)=>{const l=r?.idGenerator?r.idGenerator(e):ut(),u=new AbortController;let p,h;function f(e){h=e,u.abort()}o&&(o.aborted?f(gt):o.addEventListener("abort",()=>f(gt),{once:!0}));const m=async function(){let o;try{let s=r?.condition?.(e,{getState:c,extra:d});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||u.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise((e,t)=>{p=()=>{t({name:"AbortError",message:h||"Aborted"})},u.signal.addEventListener("abort",p)});a(n(l,e,r?.getPendingMeta?.({requestId:l,arg:e},{getState:c,extra:d}))),o=await Promise.race([m,Promise.resolve(t(e,{dispatch:a,getState:c,extra:d,requestId:l,signal:u.signal,abort:f,rejectWithValue:(e,t)=>new ht(e,t),fulfillWithValue:(e,t)=>new ft(e,t)})).then(t=>{if(t instanceof ht)throw t;return t instanceof ft?i(t.payload,l,e,t.meta):i(t,l,e)})])}catch(t){o=t instanceof ht?s(null,l,e,t.payload,t.meta):s(t,l,e)}finally{p&&u.signal.removeEventListener("abort",p)}return r&&!r.dispatchConditionRejection&&s.match(o)&&o.meta.condition||a(o),o}();return Object.assign(m,{abort:f,requestId:l,arg:e,unwrap:()=>m.then(bt)})}},{pending:n,rejected:s,fulfilled:i,settled:lt(s,i),typePrefix:e})}return e.withTypes=()=>e,e})();function bt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var yt=Symbol.for("rtk-slice-createasyncthunk");function wt(e,t){return`${e}/${t}`}function _t({creators:e}={}){const t=e?.asyncThunk?.[yt];return function(e){const{name:r,reducerPath:i=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const n=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},s=Object.keys(n),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const r="string"==typeof e?e:e.type;if(!r)throw new Error("`context.addCase` cannot be called with an empty action type");if(r in o.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+r);return o.sliceCaseReducersByType[r]=t,a},addMatcher:(e,t)=>(o.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(o.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(o.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},r=[],i]="function"==typeof e.extraReducers?dt(e.extraReducers):[e.extraReducers],n={...t,...o.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let r,[i,n,s]=dt(t);if("function"==typeof e)r=()=>Je(e());else{const t=Je(e);r=()=>t}function o(e=r(),t){let o=[i[t.type],...n.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return 0===o.filter(e=>!!e).length&&(o=[s]),o.reduce((e,r)=>{if(r){if(G(e)){const i=r(e,t);return void 0===i?e:i}if(q(e))return Pe(e,e=>r(e,t));{const i=r(e,t);if(void 0===i){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return i}}return e},e)}return o.getInitialState=r,o}(e.initialState,e=>{for(let t in n)e.addCase(t,n[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);i&&e.addDefaultCase(i)})}s.forEach(i=>{const s=n[i],o={reducerName:i,type:wt(r,i),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},i,n){let s,o;if("reducer"in i){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(i))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=i.reducer,o=i.prepare}else s=i;n.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?qe(e,o):qe(e))}(o,s,a):function({type:e,reducerName:t},r,i,n){if(!n)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:s,fulfilled:o,pending:a,rejected:c,settled:d,options:l}=r,u=n(e,s,l);i.exposeAction(t,u),o&&i.addCase(u.fulfilled,o);a&&i.addCase(u.pending,a);c&&i.addCase(u.rejected,c);d&&i.addMatcher(u.settled,d);i.exposeCaseReducer(t,{fulfilled:o||Rt,pending:a||Rt,rejected:c||Rt,settled:d||Rt})}(o,s,a,t)});const d=e=>e,l=new Map,u=new WeakMap;let p;function h(e,t){return p||(p=c()),p(e,t)}function f(){return p||(p=c()),p.getInitialState()}function m(t,r=!1){function i(e){let n=e[t];if(void 0===n){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");n=Qe(u,i,f)}return n}function n(t=d){const i=Qe(l,r,()=>new WeakMap);return Qe(i,t,()=>{const i={};for(const[n,s]of Object.entries(e.selectors??{}))i[n]=St(s,t,()=>Qe(u,t,f),r);return i})}return{reducerPath:t,getSelectors:n,get selectors(){return n(i)},selectSlice:i}}const g={name:r,reducer:h,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:f,...m(i),injectInto(e,{reducerPath:t,...r}={}){const n=t??i;return e.inject({reducerPath:n,reducer:h},r),{...g,...m(n,!0)}}};return g}}function St(e,t,r,i){function n(n,...s){let o=t(n);if(void 0===o){if(!i)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return n.unwrapped=e,n}var Ct=_t();function Rt(){}var kt="listener",Tt="completed",Pt="cancelled",Ot=`task-${Pt}`,Et=`task-${Tt}`,Dt=`${kt}-${Pt}`,xt=`${kt}-${Tt}`,It=class{constructor(e){this.code=e,this.message=`task ${Pt} (reason: ${e})`}name="TaskAbortError";message},Mt=(e,t)=>{if("function"!=typeof e)throw new TypeError(`${t} is not a function`)},jt=()=>{},Lt=(e,t=jt)=>(e.catch(t),e),At=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Nt=(e,t)=>{const r=e.signal;r.aborted||("reason"in r||Object.defineProperty(r,"reason",{enumerable:!0,value:t,configurable:!0,writable:!0}),e.abort(t))},Bt=e=>{if(e.aborted){const{reason:t}=e;throw new It(t)}};function Ft(e,t){let r=jt;return new Promise((i,n)=>{const s=()=>n(new It(e.reason));e.aborted?s():(r=At(e,s),t.finally(()=>r()).then(i,n))}).finally(()=>{r=jt})}var zt=e=>t=>Lt(Ft(e,t).then(t=>(Bt(e),t))),Vt=e=>{const t=zt(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:Ut}=Object,$t={},Gt="listenerMiddleware",qt=(e,t)=>(r,i)=>{Mt(r,"taskExecutor");const n=new AbortController;var s;s=n,At(e,()=>Nt(s,e.reason));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof It?"cancelled":"rejected",error:e}}finally{t?.()}})(async()=>{Bt(e),Bt(n.signal);const t=await r({pause:zt(n.signal),delay:Vt(n.signal),signal:n.signal});return Bt(n.signal),t},()=>Nt(n,Et));return i?.autoJoin&&t.push(o.catch(jt)),{result:zt(e)(o),cancel(){Nt(n,Ot)}}},Ht=(e,t)=>(r,i)=>Lt((async(r,i)=>{Bt(t);let n=()=>{};const s=[new Promise((t,i)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});n=()=>{s(),i()}})];null!=i&&s.push(new Promise(e=>setTimeout(e,i,null)));try{const e=await Ft(t,Promise.race(s));return Bt(t),e}finally{n()}})(r,i)),Wt=e=>{let{type:t,actionCreator:r,matcher:i,predicate:n,effect:s}=e;if(t)n=qe(t).match;else if(r)t=r.type,n=r.match;else if(i)n=i;else if(!n)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return Mt(s,"options.listener"),{predicate:n,type:t,effect:s}},Kt=Ut(e=>{const{type:t,predicate:r,effect:i}=Wt(e);return{id:ut(),effect:i,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}},{withTypes:()=>Kt}),Jt=(e,t)=>{const{type:r,effect:i,predicate:n}=Wt(t);return Array.from(e.values()).find(e=>("string"==typeof r?e.type===r:e.predicate===n)&&e.effect===i)},Qt=e=>{e.pending.forEach(e=>{Nt(e,Dt)})},Yt=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout(()=>{throw e},0)}},Xt=Ut(qe(`${Gt}/add`),{withTypes:()=>Xt}),Zt=qe(`${Gt}/removeAll`),er=Ut(qe(`${Gt}/remove`),{withTypes:()=>er}),tr=(...e)=>{console.error(`${Gt}/error`,...e)};let rr=!0,ir=!0;function nr(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseFloat(i[r],10)}function sr(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function or(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(rr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ar(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ir=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function cr(){if("object"==typeof window){if(rr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function dr(e,t){ir&&console.warn(e+" is deprecated, please use "+t+" instead.")}function lr(e){return"[object Object]"===Object.prototype.toString.call(e)}function ur(e){return lr(e)?Object.keys(e).reduce(function(t,r){const i=lr(e[r]),n=i?ur(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})},{}):e}function pr(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?pr(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach(t=>{pr(e,e.get(t),r)})}))}function hr(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(r=>{r.type===i&&r.trackId===t.id&&pr(e,r,n)})}),n}const fr=cr;function mr(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach(e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then(r=>{let o=(r=r.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),fr("chrome: "+JSON.stringify(e)),n(e)})}e.video=i(e.video)}return fr("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,e=>{r.webkitGetUserMedia(e,t,e=>{i&&i(s(e))})})}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function gr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function vr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.track.id):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}),t.stream.getTracks().forEach(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.id):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else sr(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function br(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function yr(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>hr(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sr(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>hr(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach(r=>{r.track===e&&(t?i=!0:t=r)}),this.getReceivers().forEach(t=>(t.track===e&&(r?i=!0:r=t),t.track===e)),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function wr(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),n.apply(this,arguments)}}function _r(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return wr(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[r.id];if(n)n.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then(e=>s(this,e))}};e.RTCPeerConnection.prototype[t]=i[t]});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(r=>{this._streams[r].getTracks().find(t=>e.track===t)&&(t=this._streams[r])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Sr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]})}function Cr(e,t){sr(e,"negotiationneeded",e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})}var Rr=Object.freeze({__proto__:null,fixNegotiationNeeded:Cr,shimAddTrackRemoveTrack:_r,shimAddTrackRemoveTrackWithNative:wr,shimGetSendersWithDtmf:br,shimGetUserMedia:mr,shimMediaStream:gr,shimOnTrack:vr,shimPeerConnection:Sr,shimSenderReceiverGetStats:yr});function kr(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){dr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function Tr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Pr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]});const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then(e=>{if(t.version<53&&!n)try{e.forEach(e=>{e.type=r[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))})}return e}).then(n,s)}}function Or(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Er(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sr(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Dr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){dr("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function xr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ir(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const r=e.length>0;r&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return i})}function Mr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function jr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Lr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Ar=Object.freeze({__proto__:null,shimAddTransceiver:Ir,shimCreateAnswer:Lr,shimCreateOffer:jr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})},shimGetParameters:Mr,shimGetUserMedia:kr,shimOnTrack:Tr,shimPeerConnection:Pr,shimRTCDataChannel:xr,shimReceiverGetStats:Er,shimRemoveStream:Dr,shimSenderGetStats:Or});function Nr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(r=>t.call(this,r,e)),e.getVideoTracks().forEach(r=>t.call(this,r,e))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach(e=>{r.includes(e.track)&&this.removeTrack(e)})})}}function Br(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)})}),t.apply(e,arguments)}}}function Fr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function zr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Vr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Vr(e){return e&&void 0!==e.video?Object.assign({},e,{video:ur(e.video)}):e}function Ur(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];void 0===i.urls&&i.url?(dr("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function $r(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function qr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Hr=Object.freeze({__proto__:null,shimAudioContext:qr,shimCallbacksAPI:Fr,shimConstraints:Vr,shimCreateOfferLegacy:Gr,shimGetUserMedia:zr,shimLocalStreamsAPI:Nr,shimRTCIceServerUrls:Ur,shimRemoteStreamsAPI:Br,shimTrackEventTransceiver:$r}),Wr={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter(e=>0===e.indexOf(r))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)r=i[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)}),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let n=3;n<i.length;n++){const s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const i=t.parseRtpMap(o),n=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(i.parameters=n.length?t.parseFmtp(n[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{r.headerExtensions.push(t.parseExtmap(e))});const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach(e=>{n.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach(e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)});let n=0;return r.codecs.forEach(e=>{e.maxptime>n&&(n=e.maxptime)}),n>0&&(i+="a=maxptime:"+n+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach(e=>{i+=t.writeExtmap(e)}),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),n=-1!==i.fecMechanisms.indexOf("RED"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}}),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach(e=>{e.maxBitrate=l})),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return n.length>0?(r=n[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let n;i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let n;const s=void 0!==r?r:2;n=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+n+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(Wr);var Kr=Wr.exports,Jr=c(Kr),Qr=n({__proto__:null,default:Jr},[Kr]);function Yr(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const r=new t(e),i=Jr.parseCandidate(e.candidate);for(const e in i)e in r||Object.defineProperty(r,e,{value:i[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,sr(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Xr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||sr(e,"icecandidate",e=>{if(e.candidate){const t=Jr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Zr(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Jr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Jr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),i=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=Jr.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i}(arguments[0],e);let n;n=0===r&&0===i?Number.POSITIVE_INFINITY:0===r||0===i?Math.max(r,i):Math.min(r,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return r.apply(this,arguments)}}function ei(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},sr(e,"datachannel",e=>(t(e.channel,e.target),e))}function ti(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function ri(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function ii(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ni(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>r.apply(this,[e]))})}var si=Object.freeze({__proto__:null,removeExtmapAllowMixed:ri,shimAddIceCandidateNullOrEmpty:ii,shimConnectionState:ti,shimMaxMessageSize:Zr,shimParameterlessSetLocalDescription:ni,shimRTCIceCandidate:Yr,shimRTCIceCandidateRelayProtocol:Xr,shimSendThrowTypeError:ei});const oi=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=cr,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){const e=r.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=parseInt(nr(r.userAgent,/Firefox\/(\d+)\./,1));else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(nr(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(nr(r.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=nr(r.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),n={browserDetails:i,commonShim:si,extractVersion:nr,disableLog:or,disableWarnings:ar,sdp:Qr};switch(i.browser){case"chrome":if(!Rr||!Sr||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=Rr,ii(e,i),ni(e),mr(e,i),gr(e),Sr(e,i),vr(e),_r(e,i),br(e),yr(e),Cr(e,i),Yr(e),Xr(e),ti(e),Zr(e,i),ei(e),ri(e,i);break;case"firefox":if(!Ar||!Pr||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Ar,ii(e,i),ni(e),kr(e,i),Pr(e,i),Tr(e),Dr(e),Or(e),Er(e),xr(e),Ir(e),Mr(e),jr(e),Lr(e),Yr(e),ti(e),Zr(e,i),ei(e);break;case"safari":if(!Hr||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=Hr,ii(e,i),ni(e),Ur(e),Gr(e),Fr(e),Nr(e),Br(e),$r(e),zr(e),qr(e),Yr(e),Xr(e),Zr(e,i),ei(e),ri(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});function ai(e){return{id:e.id,tracks:e.getTracks().map(function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}})}}var ci=function(e,t,r){var i=0,n=!!window.mozRTCPeerConnection,s=!!window.RTCIceGatherer,o={};if(r.forEach(function(r){if(window[r+"RTCPeerConnection"]&&("webkit"!==r||!s)){var a=window[r+"RTCPeerConnection"],c=function(r,c){var d=new a(r,c),l="PC_"+i++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach(function(e){delete e.credential}),r.browserType=n?"moz":s?"edge":"webkit",e("create",l,r),c&&e("constraints",l,c),d.addEventListener("icecandidate",function(t){e("onicecandidate",l,t.candidate)}),d.addEventListener("addstream",function(t){e("onaddstream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("track",function(t){e("ontrack",l,t.track.kind+":"+t.track.id+" "+t.streams.map(function(e){return"stream:"+e.id}))}),d.addEventListener("removestream",function(t){e("onremovestream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("signalingstatechange",function(){e("onsignalingstatechange",l,d.signalingState)}),d.addEventListener("iceconnectionstatechange",function(){e("oniceconnectionstatechange",l,d.iceConnectionState)}),d.addEventListener("icegatheringstatechange",function(){e("onicegatheringstatechange",l,d.iceGatheringState)}),d.addEventListener("connectionstatechange",function(){e("onconnectionstatechange",l,d.connectionState)}),d.addEventListener("negotiationneeded",function(){e("onnegotiationneeded",l,void 0)}),d.addEventListener("datachannel",function(t){e("ondatachannel",l,[t.channel.id,t.channel.label])});var u=function(){d.getStats(null).then(function(t){var r=function(e){if(!e.entries)return e;var t={};return e.forEach(function(e,r){t[r]=e}),t}(t),i=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach(function(r){var i=t[r];delete i.id,e[r]&&Object.keys(i).forEach(function(n){i[n]===e[r][n]&&delete t[r][n],(0===Object.keys(i).length||1===Object.keys(i).length&&i.timestamp)&&delete t[r]})});var r=-1/0;return Object.keys(t).forEach(function(e){var i=t[e];i.timestamp>r&&(r=i.timestamp)}),Object.keys(t).forEach(function(e){var i=t[e];i.timestamp===r&&(i.timestamp=0)}),t.timestamp=r,t}(o[l]||{},r)),o[l]=i})};if(!s&&t)var p=window.setInterval(function(){"closed"!==d.signalingState?u():window.clearInterval(p)},t);return s||d.addEventListener("connectionstatechange",function(){"connected"!==d.connectionState&&"failed"!==d.connectionState||u()}),d};["createDataChannel","close"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){return e(t,this.__rtcStatsId,arguments),r.apply(this,arguments)})}),["addStream","removeStream"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=i.getTracks().map(function(e){return e.kind+":"+e.id}).join(",");return e(t,this.__rtcStatsId,i.id+" "+n),r.apply(this,arguments)})}),["addTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,i.kind+":"+i.id+" "+(n.map(function(e){return"stream:"+e.id}).join(";")||"-")),r.apply(this,arguments)})}),["removeTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0].track;return e(t,this.__rtcStatsId,i?i.kind+":"+i.id:"null"),r.apply(this,arguments)})}),["createOffer","createAnswer"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i,n=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?i=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(i=arguments[2]),e(t,this.__rtcStatsId,i),r.apply(this,i?[i]:void 0).then(function(r){if(e(t+"OnSuccess",n,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])},function(r){if(e(t+"OnFailure",n,r.toString()),!(s.length>1&&"function"==typeof s[1]))throw r;s[1].apply(null,[r])})})}),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=this.__rtcStatsId,n=arguments;return e(t,this.__rtcStatsId,n[0]),r.apply(this,[n[0]]).then(function(){e(t+"OnSuccess",i,void 0),n.length>=2&&"function"==typeof n[1]&&n[1].apply(null,[])},function(r){if(e(t+"OnFailure",i,r.toString()),!(n.length>=3&&"function"==typeof n[2]))throw r;n[2].apply(null,[r])})})}),a.generateCertificate&&Object.defineProperty(c,"generateCertificate",{get:function(){return arguments.length?a.generateCertificate.apply(null,arguments):a.generateCertificate}}),window[r+"RTCPeerConnection"]=c,window[r+"RTCPeerConnection"].prototype=a.prototype}}),r.forEach(function(t){var r=t+(t.length?"GetUserMedia":"getUserMedia");if(navigator[r]){var i=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];i(arguments[0],function(r){e("getUserMediaOnSuccess",null,ai(r)),t&&t(r)},function(t){e("getUserMediaOnFailure",null,t.name),r&&r(t)})}.bind(navigator)}}),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return e("navigator.mediaDevices.getUserMedia",null,arguments[0]),a.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getUserMediaOnSuccess",null,ai(t)),t},function(t){return e("navigator.mediaDevices.getUserMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var c=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return e("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),c.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getDisplayMediaOnSuccess",null,ai(t)),t},function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},di=c(ci);let li;const ui=new Uint8Array(16);function pi(){if(!li&&(li="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!li))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return li(ui)}const hi=[];for(let xD=0;xD<256;++xD)hi.push((xD+256).toString(16).slice(1));var fi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function mi(e,t,r){if(fi.randomUUID&&!e)return fi.randomUUID();const i=(e=e||{}).random||(e.rng||pi)();return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return hi[e[t+0]]+hi[e[t+1]]+hi[e[t+2]]+hi[e[t+3]]+"-"+hi[e[t+4]]+hi[e[t+5]]+"-"+hi[e[t+6]]+hi[e[t+7]]+"-"+hi[e[t+8]]+hi[e[t+9]]+"-"+hi[e[t+10]]+hi[e[t+11]]+hi[e[t+12]]+hi[e[t+13]]+hi[e[t+14]]+hi[e[t+15]]}(i)}var gi={},vi={},bi={exports:{}},yi=bi.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"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(e){return null!=e.subtype?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.maxMessageSize?"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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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(yi).forEach(function(e){yi[e].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})});var wi=bi.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(r[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},i=wi,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach(function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,o,n)}}),t.media=s,t};var s=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}})})}}(vi);var _i=wi,Si=/%[sdv%]/g,Ci=function(e){var t=1,r=arguments,i=r.length;return e.replace(Si,function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Ri=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?i.push(r[t.name][s]):i.push(r[t.names[n]])}else i.push(r[t.name]);return Ci.apply(null,i)},ki=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ti=["i","c","b","a"],Pi=vi,Oi=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=t.outerOrder||ki,i=t.innerOrder||Ti,n=[];return r.forEach(function(t){_i[t].forEach(function(r){r.name in e&&null!=e[r.name]?n.push(Ri(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){n.push(Ri(t,r,e))})})}),e.media.forEach(function(e){n.push(Ri("m",_i.m[0],e)),i.forEach(function(t){_i[t].forEach(function(r){r.name in e&&null!=e[r.name]?n.push(Ri(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){n.push(Ri(t,r,e))})})})}),n.join("\r\n")+"\r\n"},Ei=wi;gi.grammar=Ei;var Di=gi.write=Oi,xi=gi.parse=Pi.parse;gi.parseParams=Pi.parseParams,gi.parseFmtpConfig=Pi.parseFmtpConfig,gi.parsePayloads=Pi.parsePayloads,gi.parseRemoteCandidates=Pi.parseRemoteCandidates,gi.parseImageAttributes=Pi.parseImageAttributes,gi.parseSimulcastStreamList=Pi.parseSimulcastStreamList;var Ii={},Mi={},ji={};Object.defineProperty(ji,"__esModule",{value:!0}),ji.isCorrect=ji.isInSubnet=void 0,ji.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},ji.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var Li={};Object.defineProperty(Li,"__esModule",{value:!0}),Li.RE_SUBNET_STRING=Li.RE_ADDRESS=Li.GROUPS=Li.BITS=void 0,Li.BITS=32,Li.GROUPS=4,Li.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,Li.RE_SUBNET_STRING=/\/\d{1,2}$/;var Ai={};Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.AddressError=void 0;class Ni extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}Ai.AddressError=Ni;var Bi,Fi={exports:{}};Bi=Fi,function(){var e;function t(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function r(){return new t(null)}var i="undefined"!=typeof navigator;i&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],d=this[e++]>>15,l=a*c+d*o;n=((c=o*c+((32767&l)<<15)+r[i]+(1073741823&n))>>>30)+(l>>>15)+a*d+(n>>>30),r[i++]=1073741823&c}return n},e=30):i&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(;--s>=0;){var o=t*this[e++]+r[i]+n;n=Math.floor(o/67108864),r[i++]=67108863&o}return n},e=26):(t.prototype.am=function(e,t,r,i,n,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],d=this[e++]>>14,l=a*c+d*o;n=((c=o*c+((16383&l)<<14)+r[i]+n)>>28)+(l>>14)+a*d,r[i++]=268435455&c}return n},e=28),t.prototype.DB=e,t.prototype.DM=(1<<e)-1,t.prototype.DV=1<<e,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-e,t.prototype.F2=2*e-52;var n,s,o=new Array;for(n="0".charCodeAt(0),s=0;s<=9;++s)o[n++]=s;for(n="a".charCodeAt(0),s=10;s<36;++s)o[n++]=s;for(n="A".charCodeAt(0),s=10;s<36;++s)o[n++]=s;function a(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function c(e,t){var r=o[e.charCodeAt(t)];return null==r?-1:r}function d(e){var t=r();return t.fromInt(e),t}function l(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function u(e){this.m=e}function p(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function h(e,t){return e&t}function f(e,t){return e|t}function m(e,t){return e^t}function g(e,t){return e&~t}function v(e){if(0==e)return-1;var t=0;return 65535&e||(e>>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function b(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function y(){}function w(e){return e}function _(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}u.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},u.prototype.revert=function(e){return e},u.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},u.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},u.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},p.prototype.convert=function(e){var i=r();return e.abs().dlShiftTo(this.m.t,i),i.divRemTo(this.m,null,i),e.s<0&&i.compareTo(t.ZERO)>0&&this.m.subTo(i,i),i},p.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},p.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],i=r*this.mpl+((r*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,i,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},p.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,r){var i;if(16==r)i=4;else if(8==r)i=3;else if(256==r)i=8;else if(2==r)i=1;else if(32==r)i=5;else{if(4!=r)return void this.fromRadix(e,r);i=2}this.t=0,this.s=0;for(var n=e.length,s=!1,o=0;--n>=0;){var a=8==i?255&e[n]:c(e,n);a<0?"-"==e.charAt(n)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+i>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=i)>=this.DB&&(o-=this.DB))}8==i&&128&e[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){var r,i=e%this.DB,n=this.DB-i,s=(1<<n)-1,o=Math.floor(e/this.DB),a=this.s<<i&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>n|a,a=(this[r]&s)<<i;for(r=o-1;r>=0;--r)t[r]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var i=e%this.DB,n=this.DB-i,s=(1<<i)-1;t[0]=this[r]>>i;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<n,t[o-r]=this[o]>>i;i>0&&(t[this.t-r-1]|=(this.s&s)<<n),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]-e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i-=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i-=e[r],t[r++]=i&this.DM,i>>=this.DB;i-=e.s}t.s=i<0?-1:0,i<-1?t[r++]=this.DV+i:i>0&&(t[r++]=i),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var i=this.abs(),n=e.abs(),s=i.t;for(r.t=s+n.t;--s>=0;)r[s]=0;for(s=0;s<n.t;++s)r[s+i.t]=i.am(0,n[s],r,s,0,i.t);r.s=0,r.clamp(),this.s!=e.s&&t.ZERO.subTo(r,r)},t.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var i=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,i,t.t-r-1))>=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,i,n){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=i&&i.fromInt(0),void(null!=n&&this.copyTo(n));null==n&&(n=r());var a=r(),c=this.s,d=e.s,u=this.DB-l(s[s.t-1]);u>0?(s.lShiftTo(u,a),o.lShiftTo(u,n)):(s.copyTo(a),o.copyTo(n));var p=a.t,h=a[p-1];if(0!=h){var f=h*(1<<this.F1)+(p>1?a[p-2]>>this.F2:0),m=this.FV/f,g=(1<<this.F1)/f,v=1<<this.F2,b=n.t,y=b-p,w=null==i?r():i;for(a.dlShiftTo(y,w),n.compareTo(w)>=0&&(n[n.t++]=1,n.subTo(w,n)),t.ONE.dlShiftTo(p,w),w.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var _=n[--b]==h?this.DM:Math.floor(n[b]*m+(n[b-1]+v)*g);if((n[b]+=a.am(0,_,n,y,0,p))<_)for(a.dlShiftTo(y,w),n.subTo(w,n);n[b]<--_;)n.subTo(w,n)}null!=i&&(n.drShiftTo(p,i),c!=d&&t.ZERO.subTo(i,i)),n.t=p,n.clamp(),u>0&&n.rShiftTo(u,n),c<0&&t.ZERO.subTo(n,n)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},t.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},t.prototype.exp=function(e,i){if(e>4294967295||e<1)return t.ONE;var n=r(),s=r(),o=i.convert(this),a=l(e)-1;for(o.copyTo(n);--a>=0;)if(i.sqrTo(n,s),(e&1<<a)>0)i.mulTo(s,o,n);else{var c=n;n=s,s=c}return i.revert(n)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,i=(1<<t)-1,n=!1,s="",o=this.t,c=this.DB-o*this.DB%t;if(o-- >0)for(c<this.DB&&(r=this[o]>>c)>0&&(n=!0,s=a(r));o>=0;)c<t?(r=(this[o]&(1<<c)-1)<<t-c,r|=this[--o]>>(c+=this.DB-t)):(r=this[o]>>(c-=t)&i,c<=0&&(c+=this.DB,--o)),r>0&&(n=!0),n&&(s+=a(r));return n?s:"0"},t.prototype.negate=function(){var e=r();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+l(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var i=r();return this.abs().divRemTo(e,null,i),this.s<0&&i.compareTo(t.ZERO)>0&&e.subTo(i,i),i},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new u(t):new p(t),this.exp(e,r)},t.ZERO=d(0),t.ONE=d(1),y.prototype.convert=w,y.prototype.revert=w,y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},y.prototype.sqrTo=function(e,t){e.squareTo(t)},_.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=r();return e.copyTo(t),this.reduce(t),t},_.prototype.revert=function(e){return e},_.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},_.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var S,C,R,k=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],T=(1<<26)/k[k.length-1];function P(){var e;e=(new Date).getTime(),C[R++]^=255&e,C[R++]^=e>>8&255,C[R++]^=e>>16&255,C[R++]^=e>>24&255,R>=j&&(R-=j)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),i=Math.pow(e,t),n=d(i),s=r(),o=r(),a="";for(this.divRemTo(n,s,o);s.signum()>0;)a=(i+o.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var i=this.chunkSize(r),n=Math.pow(r,i),s=!1,o=0,a=0,d=0;d<e.length;++d){var l=c(e,d);l<0?"-"==e.charAt(d)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=i&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(r,o)),this.dAddOffset(a,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,r,i){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,i),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),f,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var n=new Array,s=7&e;n.length=1+(e>>3),r.nextBytes(n),s>0?n[0]&=(1<<s)-1:n[0]=0,this.fromString(n,256)}},t.prototype.bitwiseTo=function(e,t,r){var i,n,s=Math.min(e.t,this.t);for(i=0;i<s;++i)r[i]=t(this[i],e[i]);if(e.t<this.t){for(n=e.s&this.DM,i=s;i<this.t;++i)r[i]=t(this[i],n);r.t=this.t}else{for(n=this.s&this.DM,i=s;i<e.t;++i)r[i]=t(n,e[i]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var i=t.ONE.shiftLeft(e);return this.bitwiseTo(i,r,i),i},t.prototype.addTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]+e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i+=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i+=e[r],t[r++]=i&this.DM,i>>=this.DB;i+=e.s}t.s=i<0?-1:0,i>0?t[r++]=i:i<-1&&(t[r++]=this.DV+i),t.t=r,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,r){var i,n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r[--n]=0;for(i=r.t-this.t;n<i;++n)r[n+this.t]=this.am(0,e[n],r,n,0,this.t);for(i=Math.min(e.t,t);n<i;++n)this.am(0,e[n],r,n,0,t-n);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var i=r.t=this.t+e.t-t;for(r.s=0;--i>=0;)r[i]=0;for(i=Math.max(t-this.t,0);i<e.t;++i)r[this.t+i-t]=this.am(t-i,e[i],r,0,0,this.t+i-t);r.clamp(),r.drShiftTo(1,r)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var i=this.t-1;i>=0;--i)r=(t*r+this[i])%e;return r},t.prototype.millerRabin=function(e){var i=this.subtract(t.ONE),n=i.getLowestSetBit();if(n<=0)return!1;var s=i.shiftRight(n);(e=e+1>>1)>k.length&&(e=k.length);for(var o=r(),a=0;a<e;++a){o.fromInt(k[Math.floor(Math.random()*k.length)]);var c=o.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(i)){for(var d=1;d++<n&&0!=c.compareTo(i);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(i))return!1}}return!0},t.prototype.clone=function(){var e=r();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,i=this.DB-e*this.DB%8,n=0;if(e-- >0)for(i<this.DB&&(r=this[e]>>i)!=(this.s&this.DM)>>i&&(t[n++]=r|this.s<<this.DB-i);e>=0;)i<8?(r=(this[e]&(1<<i)-1)<<8-i,r|=this[--e]>>(i+=this.DB-8)):(r=this[e]>>(i-=8)&255,i<=0&&(i+=this.DB,--e)),128&r&&(r|=-256),0==n&&(128&this.s)!=(128&r)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return this.compareTo(e)>0?this:e},t.prototype.and=function(e){var t=r();return this.bitwiseTo(e,h,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,f,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.not=function(){for(var e=r(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=r();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=r();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+v(this[e]);return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=b(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,f)},t.prototype.clearBit=function(e){return this.changeBit(e,g)},t.prototype.flipBit=function(e){return this.changeBit(e,m)},t.prototype.add=function(e){var t=r();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=r();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=r();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=r();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=r();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=r(),i=r();return this.divRemTo(e,t,i),new Array(t,i)},t.prototype.modPow=function(e,t){var i,n,s=e.bitLength(),o=d(1);if(s<=0)return o;i=s<18?1:s<48?3:s<144?4:s<768?5:6,n=s<8?new u(t):t.isEven()?new _(t):new p(t);var a=new Array,c=3,h=i-1,f=(1<<i)-1;if(a[1]=n.convert(this),i>1){var m=r();for(n.sqrTo(a[1],m);c<=f;)a[c]=r(),n.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,w=r();for(s=l(e[b])-1;b>=0;){for(s>=h?g=e[b]>>s-h&f:(g=(e[b]&(1<<s+1)-1)<<h-s,b>0&&(g|=e[b-1]>>this.DB+s-h)),c=i;!(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)n.sqrTo(o,w),n.sqrTo(w,o),c-=2;c>0?n.sqrTo(o,w):(v=o,o=w,w=v),n.mulTo(w,a[g],o)}for(;b>=0&&!(e[b]&1<<s);)n.sqrTo(o,w),v=o,o=w,w=v,--s<0&&(s=this.DB-1,--b)}return n.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var i=e.clone(),n=this.clone(),s=d(1),o=d(0),a=d(0),c=d(1);0!=i.signum();){for(;i.isEven();)i.rShiftTo(1,i),r?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),r?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(e,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);i.compareTo(n)>=0?(i.subTo(n,i),r&&s.subTo(a,s),o.subTo(c,o)):(n.subTo(i,n),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=n.compareTo(t.ONE)?t.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},t.prototype.pow=function(e){return this.exp(e,new y)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var i=t;t=r,r=i}var n=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(n<s&&(s=n),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=r.getLowestSetBit())>0&&r.rShiftTo(n,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},t.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=k[k.length-1]){for(t=0;t<k.length;++t)if(r[0]==k[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<k.length;){for(var i=k[t],n=t+1;n<k.length&&i<T;)i*=k[n++];for(i=r.modInt(i);t<n;)if(i%k[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=_,null==C){var O;if(C=new Array,R=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var E=new Uint8Array(32);for(window.crypto.getRandomValues(E),O=0;O<32;++O)C[R++]=E[O]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var D=window.crypto.random(32);for(O=0;O<D.length;++O)C[R++]=255&D.charCodeAt(O)}for(;R<j;)O=Math.floor(65536*Math.random()),C[R++]=O>>>8,C[R++]=255&O;R=0,P()}function x(){if(null==S){for(P(),(S=new M).init(C),R=0;R<C.length;++R)C[R]=0;R=0}return S.next()}function I(){}function M(){this.i=0,this.j=0,this.S=new Array}I.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=x()},M.prototype.init=function(e){var t,r,i;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,i=this.S[t],this.S[t]=this.S[r],this.S[r]=i;this.i=0,this.j=0},M.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var j=256;Bi.exports={default:t,BigInteger:t,SecureRandom:I}}.call(a);var zi=Fi.exports,Vi={};!function(e){!function(){var t={not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function r(e){return function(e,i){var n,s,o,a,c,d,l,u,p,h=1,f=e.length,m="";for(s=0;s<f;s++)if("string"==typeof e[s])m+=e[s];else if("object"==typeof e[s]){if((a=e[s]).keys)for(n=i[h],o=0;o<a.keys.length;o++){if(null==n)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));n=n[a.keys[o]]}else n=a.param_no?i[a.param_no]:i[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&n instanceof Function&&(n=n()),t.numeric_arg.test(a.type)&&"number"!=typeof n&&isNaN(n))throw new TypeError(r("[sprintf] expecting number but found %T",n));switch(t.number.test(a.type)&&(u=n>=0),a.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=n:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",n=n.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+n).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+n+c:"0"===d?p+c+n:c+p+n)}return m}(function(e){if(n[e])return n[e];var r,i=e,s=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))s.push(r[0]);else if(null!==(r=t.modulo.exec(i)))s.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var a=[],c=r[2],d=[];if(null===(d=t.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(d[1]);""!==(c=c.substring(d[0].length));)if(null!==(d=t.key_access.exec(c)))a.push(d[1]);else{if(null===(d=t.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(d[1])}r[2]=a}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");s.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}i=i.substring(r[0].length)}return n[e]=s}(e),arguments)}function i(e,t){return r.apply(null,[e].concat(t||[]))}var n=Object.create(null);e.sprintf=r,e.vsprintf=i,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=i)}()}(Vi);var Ui=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),$i=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Gi=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Ui(t,e,r);return $i(t,e),t};Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.Address4=void 0;const qi=Gi(ji),Hi=Gi(Li),Wi=Ai,Ki=zi,Ji=Vi;class Qi{constructor(e){this.groups=Hi.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=qi.isCorrect(Hi.BITS),this.isInSubnet=qi.isInSubnet,this.address=e;const t=Hi.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>Hi.BITS)throw new Wi.AddressError("Invalid subnet mask.");e=e.replace(Hi.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new Qi(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Hi.RE_ADDRESS))throw new Wi.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let i;for(i=0;i<8;i+=2){const e=t.slice(i,i+2);r.push(parseInt(e,16))}return new Qi(r.join("."))}static fromInteger(e){return Qi.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new Qi(t)}toHex(){return this.parsedAddress.map(e=>(0,Ji.sprintf)("%02x",parseInt(e,10))).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){const e=[];let t;for(t=0;t<Hi.GROUPS;t+=2){const r=(0,Ji.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,Ji.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Ki.BigInteger(this.parsedAddress.map(e=>(0,Ji.sprintf)("%02x",parseInt(e,10))).join(""),16)}_startAddress(){return new Ki.BigInteger(this.mask()+"0".repeat(Hi.BITS-this.subnetMask),2)}startAddress(){return Qi.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Ki.BigInteger("1");return Qi.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Ki.BigInteger(this.mask()+"1".repeat(Hi.BITS-this.subnetMask),2)}endAddress(){return Qi.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Ki.BigInteger("1");return Qi.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return Qi.fromInteger(parseInt(e.toString(),10))}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:(0,Ji.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new Qi("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Hi.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Hi.RE_ADDRESS,(0,Ji.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>',e.slice(0,2).join("."),e.slice(2,4).join(".")))}}Mi.Address4=Qi;var Yi={},Xi={};Object.defineProperty(Xi,"__esModule",{value:!0}),Xi.RE_URL_WITH_PORT=Xi.RE_URL=Xi.RE_ZONE_STRING=Xi.RE_SUBNET_STRING=Xi.RE_BAD_ADDRESS=Xi.RE_BAD_CHARACTERS=Xi.TYPES=Xi.SCOPES=Xi.GROUPS=Xi.BITS=void 0,Xi.BITS=128,Xi.GROUPS=8,Xi.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},Xi.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},Xi.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,Xi.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,Xi.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,Xi.RE_ZONE_STRING=/%.*$/,Xi.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),Xi.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.simpleGroup=Zi.spanLeadingZeroes=Zi.spanAll=Zi.spanAllZeroes=void 0;const en=Vi;function tn(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function rn(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}Zi.spanAllZeroes=tn,Zi.spanAll=function(e,t=0){return e.split("").map((e,r)=>(0,en.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,tn(e))).join("")},Zi.spanLeadingZeroes=function(e){return e.split(":").map(e=>rn(e)).join(":")},Zi.simpleGroup=function(e,t=0){return e.split(":").map((e,r)=>/group-v4/.test(e)?e:(0,en.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,rn(e)))};var nn={},sn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),on=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),an=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&sn(t,e,r);return on(t,e),t};Object.defineProperty(nn,"__esModule",{value:!0}),nn.possibleElisions=nn.simpleRegularExpression=nn.ADDRESS_BOUNDARY=nn.padGroup=nn.groupPossibilities=void 0;const cn=an(Xi),dn=Vi;function ln(e){return(0,dn.sprintf)("(%s)",e.join("|"))}function un(e){return e.length<4?(0,dn.sprintf)("0{0,%d}%s",4-e.length,e):e}nn.groupPossibilities=ln,nn.padGroup=un,nn.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",nn.simpleRegularExpression=function(e){const t=[];e.forEach((e,r)=>{0===parseInt(e,16)&&t.push(r)});const r=t.map(t=>e.map((e,r)=>{if(r===t){const t=0===r||r===cn.GROUPS-1?":":"";return ln([un(e),t])}return un(e)}).join(":"));return r.push(e.map(un).join(":")),ln(r)},nn.possibleElisions=function(e,t,r){const i=t?"":":",n=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,dn.sprintf)("%s(:0{1,4}){1,%d}",i,e-1)),s.push((0,dn.sprintf)("(0{1,4}:){1,%d}%s",e-1,n)),s.push((0,dn.sprintf)("(0{1,4}:){%d}0{1,4}",e-1));for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)s.push((0,dn.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return ln(s)};var pn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),hn=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fn=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&pn(t,e,r);return hn(t,e),t};Object.defineProperty(Yi,"__esModule",{value:!0}),Yi.Address6=void 0;const mn=fn(ji),gn=fn(Li),vn=fn(Xi),bn=fn(Zi),yn=Mi,wn=nn,_n=Ai,Sn=zi,Cn=Vi;function Rn(e){if(!e)throw new Error("Assertion failed.")}function kn(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function Tn(e){return(0,Cn.sprintf)("%04x",parseInt(e,16))}function Pn(e){return 255&e}class On{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=mn.isInSubnet,this.isCorrect=mn.isCorrect(vn.BITS),this.groups=void 0===t?vn.GROUPS:t,this.address=e;const r=vn.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>vn.BITS)throw new _n.AddressError("Invalid subnet mask.");e=e.replace(vn.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new _n.AddressError("Invalid subnet mask.");const i=vn.RE_ZONE_STRING.exec(e);i&&(this.zone=i[0],e=e.replace(vn.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new On(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let i;for(i=0;i<vn.GROUPS;i++)r.push(t.slice(4*i,4*(i+1)));return new On(r.join(":"))}static fromURL(e){let t,r,i=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=vn.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],i=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=vn.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return i?(i=parseInt(i,10),(i<0||i>65536)&&(i=null)):i=null,{address:new On(t),port:i}}static fromAddress4(e){const t=new yn.Address4(e),r=vn.BITS-(gn.BITS-t.subnetMask);return new On(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new _n.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new On(t)}microsoftTranscription(){return(0,Cn.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=vn.BITS-this.subnetMask-Math.abs(e-vn.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}(new Sn.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new Sn.BigInteger(this.mask()+"0".repeat(vn.BITS-this.subnetMask),2)}startAddress(){return On.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Sn.BigInteger("1");return On.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Sn.BigInteger(this.mask()+"1".repeat(vn.BITS-this.subnetMask),2)}endAddress(){return On.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Sn.BigInteger("1");return On.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=vn.SCOPES[this.getBits(12,16).intValue()];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(vn.TYPES))if(this.isInSubnet(new On(e)))return vn.TYPES[e];return"Global unicast"}getBits(e,t){return new Sn.BigInteger(this.getBitsBase2(e,t),2)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,vn.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:(0,Cn.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const i=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&i.push([e-r,e-1]),r=0)}r>1&&i.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const n=i.map(e=>e[1]-e[0]+1);if(i.length>0){const e=n.indexOf(Math.max(...n));t=function(e,t){const r=[],i=[];let n;for(n=0;n<e.length;n++)n<t[0]?r.push(e[n]):n>t[1]&&i.push(e[n]);return r.concat(["compact"]).concat(i)}(this.parsedAddress,i[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let s=t.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/^compact|compact$/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInteger().toString(2).padStart(vn.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(gn.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new yn.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new _n.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(gn.RE_ADDRESS,this.address4.parsedAddress.map(kn).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(vn.RE_BAD_CHARACTERS);if(t)throw new _n.AddressError((0,Cn.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(vn.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(vn.RE_BAD_ADDRESS);if(r)throw new _n.AddressError((0,Cn.sprintf)("Address failed regex: %s",r.join("")),e.replace(vn.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let i=[];const n=e.split("::");if(2===n.length){let e=n[0].split(":"),t=n[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new _n.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,i=i.concat(e);for(let e=0;e<r;e++)i.push("0");i=i.concat(t)}else{if(1!==n.length)throw new _n.AddressError("Too many :: groups found");i=e.split(":"),this.elidedGroups=0}if(i=i.map(e=>(0,Cn.sprintf)("%x",parseInt(e,16))),i.length!==this.groups)throw new _n.AddressError("Incorrect number of groups found");return i}canonicalForm(){return this.parsedAddress.map(Tn).join(":")}decimal(){return this.parsedAddress.map(e=>(0,Cn.sprintf)("%05d",parseInt(e,16))).join(":")}bigInteger(){return new Sn.BigInteger(this.parsedAddress.map(Tn).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return yn.Address4.fromHex(new Sn.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new On(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=this.getBits(80,96).xor(new Sn.BigInteger("ffff",16)).toString(),r=yn.Address4.fromHex(this.getBitsBase16(32,64)),i=yn.Address4.fromHex(this.getBits(96,128).xor(new Sn.BigInteger("ffffffff",16)).toString(16)),n=this.getBits(64,80),s=this.getBitsBase2(64,80),o=n.testBit(15),a=n.testBit(14),c=n.testBit(8),d=n.testBit(9),l=new Sn.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Cn.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:i.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=yn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Cn.sprintf)("%s",e.slice(0,4)),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new On(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(Pn)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(Pn))}static fromUnsignedByteArray(e){const t=new Sn.BigInteger("256",10);let r=new Sn.BigInteger("0",10),i=new Sn.BigInteger("1",10);for(let n=e.length-1;n>=0;n--)r=r.add(i.multiply(new Sn.BigInteger(e[n].toString(10),10))),i=i.multiply(t);return On.fromBigInteger(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new On("2001::/32"))}is6to4(){return this.isInSubnet(new On("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Cn.sprintf)(":%s",e),(0,Cn.sprintf)("http://[%s]%s/",this.correctForm(),e)}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;return e.v4&&(t=this.to4in6),e.className?(0,Cn.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Cn.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return bn.simpleGroup(this.address).join(":");Rn("number"==typeof this.elidedGroups),Rn("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...bn.simpleGroup(t)):e.push("");const i=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)i.push((0,Cn.sprintf)("group-%d",e));return e.push((0,Cn.sprintf)('<span class="%s"></span>',i.join(" "))),r.length?e.push(...bn.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Rn(this.address4 instanceof yn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new On(this.correctForm());if(0===r.elidedGroups)t.push((0,wn.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===vn.GROUPS)t.push((0,wn.possibleElisions)(vn.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,wn.simpleRegularExpression)(e[0].split(":"))),Rn("number"==typeof r.elidedGroups),t.push((0,wn.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,wn.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",wn.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",wn.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}Yi.Address6=On,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var i={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(i,e,n);return r(i,e),i};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const n=Mi;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return n.Address4}});const s=Yi;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=Ai;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=i(Zi);e.v6={helpers:c}}(Ii);var En={exports:{}};!function(e){(function(){var t,r,i,n,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,i){var n,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(n=0;i>0;){if((s=r-i)<0&&(s=0),e[n]>>s!==t[n]>>s)return!1;i-=r,n+=1}return!0},r.subnetMatch=function(e,t,r){var i,n,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),i=0,n=o.length;i<n;i++)if(a=o[i],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,i;if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,r=e.length;t<r;t++)if(!(0<=(i=e[t])&&i<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.kind=function(){return"ipv4"},e.prototype.toString=function(){return this.octets.join(".")},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,e.octets,8,t)},e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.toIPv4MappedAddress=function(){return r.IPv6.parse("::ffff:"+this.toString())},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,n=!1,t=r=3;r>=0;t=r+=-1){if(!((i=this.octets[t])in o))return null;if(s=o[i],n&&0!==s)return null;8!==s&&(n=!0),e+=s}return 32-e},e}(),i="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^"+i+"\\."+i+"\\."+i+"\\."+i+"$","i"),longValue:new RegExp("^"+i+"$","i")},r.IPv4.parser=function(e){var t,r,i,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(n.fourOctet))return function(){var e,n,s,o;for(o=[],e=0,n=(s=t.slice(1,6)).length;e<n;e++)i=s[e],o.push(r(i));return o}();if(t=e.match(n.longValue)){if((o=r(t[1]))>4294967295||o<0)throw new Error("ipaddr: address outside defined range");return function(){var e,t;for(t=[],s=e=0;e<=24;s=e+=8)t.push(o>>s&255);return t}().reverse()}return null},r.IPv6=function(){function e(e,t){var r,i,n,s,o,a;if(16===e.length)for(this.parts=[],r=i=0;i<=14;r=i+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(n=0,s=(a=this.parts).length;n<s;n++)if(!(0<=(o=a[n])&&o<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.kind=function(){return"ipv6"},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e.prototype.toRFC5952String=function(){var e,t,r,i,n;for(i=/((^|:)(0(:|$)){2,})/g,n=this.toNormalizedString(),e=0,t=-1;r=i.exec(n);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?n:n.substring(0,e)+"::"+n.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,i,n;for(e=[],t=0,r=(n=this.parts).length;t<r;t++)i=n[t],e.push(i>>8),e.push(255&i);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.toFixedLengthString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16).padStart(4,"0"));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,e.parts,16,t)},e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],reserved:[[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.toIPv4Address=function(){var e,t,i;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(i=this.parts.slice(-2))[0],t=i[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},e=0,n=!1,t=r=7;r>=0;t=r+=-1){if(!((i=this.parts[t])in o))return null;if(s=o[i],n&&0!==s)return null;16!==s&&(n=!0),e+=s}return 128-e},e}(),s="(?:[0-9a-f]+::?)+",c="%[0-9a-z]{1,}",o={zoneIndex:new RegExp(c,"i"),native:new RegExp("^(::)?("+s+")?([0-9a-f]+)?(::)?("+c+")?$","i"),transitional:new RegExp("^((?:"+s+")|(?:::)(?:"+s+")?)"+i+"\\."+i+"\\."+i+"\\."+i+"("+c+")?$","i")},t=function(e,t){var r,i,n,s,a,c;if(e.indexOf("::")!==e.lastIndexOf("::"))return null;for((c=(e.match(o.zoneIndex)||[])[0])&&(c=c.substring(1),e=e.replace(/%.+$/,"")),r=0,i=-1;(i=e.indexOf(":",i+1))>=0;)r++;if("::"===e.substr(0,2)&&r--,"::"===e.substr(-2,2)&&r--,r>t)return null;for(a=t-r,s=":";a--;)s+="0:";return":"===(e=e.replace("::",s))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){var t,r,i,s;for(s=[],t=0,r=(i=e.split(":")).length;t<r;t++)n=i[t],s.push(parseInt(n,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,i,n,s,a,c,d;if(o.native.test(e))return t(e,8);if((s=e.match(o.transitional))&&(d=s[6]||"",(r=t(s[1].slice(0,-1)+d,6)).parts)){for(i=0,n=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;i<n;i++)if(!(0<=(a=c[i])&&a<=255))return null;return r.parts.push(c[0]<<8|c[1]),r.parts.push(c[2]<<8|c[3]),{parts:r.parts,zoneId:r.zoneId}}return null},r.IPv4.isIPv4=r.IPv6.isIPv6=function(e){return null!==this.parser(e)},r.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},r.IPv4.isValidFourPartDecimal=function(e){return!(!r.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},r.IPv6.isValid=function(e){var t;if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return new this((t=this.parser(e)).parts,t.zoneId),!0}catch(e){return!1}},r.IPv4.parse=function(e){var t;if(null===(t=this.parser(e)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},r.IPv6.parse=function(e){var t;if(null===(t=this.parser(e)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},r.IPv4.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,i;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(i=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)i[r]=255,r++;return t<4&&(i[t]=Math.pow(2,e%8)-1<<8-e%8),new this(i)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)|255^parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)&parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},r.isValid=function(e){return r.IPv6.isValid(e)||r.IPv4.isValid(e)},r.parse=function(e){if(r.IPv6.isValid(e))return r.IPv6.parse(e);if(r.IPv4.isValid(e))return r.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},r.parseCIDR=function(e){try{return r.IPv6.parseCIDR(e)}catch(t){try{return r.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},r.fromByteArray=function(e){var t;if(4===(t=e.length))return new r.IPv4(e);if(16===t)return new r.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},r.process=function(e){var t;return"ipv6"===(t=this.parse(e)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(a)}(En);var Dn=En.exports,xn=function(e,t){if("string"==typeof t)return In(e,t);if("object"==typeof t){for(var r=!1,i=0;i<t.length;i++)if(In(e,t[i])){r=!0;break}return r}};function In(e,t){try{var r=Dn.process(e);if(-1===t.indexOf("/")){var i=Dn.process(t);return"ipv6"===r.kind()&&"ipv6"===i.kind()?r.toNormalizedString()===i.toNormalizedString():r.toString()==i.toString()}var n=Dn.parseCIDR(t);return r.match(n)}catch(e){return!1}}var Mn=xn,jn=/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,Ln=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/3"],An=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var Nn=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(jn.test(e)){r.isValid=!0;for(var i=e.split("."),n=0;n<4;n++)t.push(parseInt(i[n],10));r.boiledIp=t.join("."),Mn(r.boiledIp,Ln)&&(r.isBogon=!0),Mn(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),Mn(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),Mn(r.boiledIp,An)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},Bn=c(Nn),Fn={exports:{}},zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vn=[],Un=0;Un<256;Un++)Vn[Un]=(Un+256).toString(16).substr(1);Fn.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e){var t=0,r=Vn;return r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!zn.test(r))return!1;if(void 0===t)t=qn(r);else if(qn(r)!==t)return!1;switch(t){case 1:case 2:return!0;case 3:case 4:case 5:return-1!==["8","9","a","b"].indexOf(r.charAt(19));default:throw new Error("Invalid version provided.")}};var $n,Gn,qn=Fn.exports.version=function(e){return 0|e.charAt(14)},Hn=c(Fn.exports),Wn={},Kn={exports:{}};function Jn(){if(Gn)return $n;Gn=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,s=365.25*i;function o(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return $n=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(n){var s=Math.abs(n);if(s>=i)return o(n,s,i,"day");if(s>=r)return o(n,s,r,"hour");if(s>=t)return o(n,s,t,"minute");if(s>=e)return o(n,s,e,"second");return n+" ms"}(a):function(n){var s=Math.abs(n);if(s>=i)return Math.round(n/i)+"d";if(s>=r)return Math.round(n/r)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},$n}var Qn=function(e){function t(e){let i,n,s,o=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),s=n-(i||n);r.diff=s,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,n)=>{if("%%"===i)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];i=s.call(r,t),e.splice(o,1),o--}return i}),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e,t){let r=0,i=0,n=-1,s=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(n=i,s=r,i++):(r++,i++);else{if(-1===n)return!1;i=n+1,s++,r=s}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=Jn(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))}),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Qn(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Kn,Kn.exports);var Yn=Kn.exports,Xn={},Zn={exports:{}};!function(e,t){!function(r,i){var n,s="user-agent",o="",a="function",c="undefined",d="object",l="string",u="browser",p="cpu",h="device",f="engine",m="os",g="result",v="name",b="type",y="vendor",w="version",_="architecture",S="major",C="model",R="console",k="mobile",T="tablet",P="smarttv",O="wearable",E="xr",D="embedded",x="inapp",I="brands",M="formFactors",j="fullVersionList",L="platform",A="platformVersion",N="bitness",B="sec-ch-ua",F=B+"-full-version-list",z=B+"-arch",V=B+"-"+N,U=B+"-form-factors",$=B+"-"+k,G=B+"-"+C,q=B+"-"+L,H=q+"-version",W=[I,j,k,C,L,A,_,M,N],K="Amazon",J="Apple",Q="ASUS",Y="BlackBerry",X="Google",Z="Huawei",ee="Lenovo",te="Honor",re="LG",ie="Microsoft",ne="Motorola",se="Nvidia",oe="OnePlus",ae="OPPO",ce="Samsung",de="Sharp",le="Sony",ue="Xiaomi",pe="Zebra",he="Chrome",fe="Chromium",me="Chromecast",ge="Edge",ve="Firefox",be="Opera",ye="Facebook",we="Sogou",_e="Mobile ",Se=" Browser",Ce="Windows",Re=typeof r!==c,ke=Re&&r.navigator?r.navigator:i,Te=ke&&ke.userAgentData?ke.userAgentData:i,Pe=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},Oe=function(e,t){if(typeof e===d&&e.length>0){for(var r in e)if(Ie(t)==Ie(e[r]))return!0;return!1}return!!De(e)&&Ie(t)==Ie(e)},Ee=function(e,t){for(var r in e)return/^(browser|cpu|device|engine|os)$/.test(r)||!!t&&Ee(e[r])},De=function(e){return typeof e===l},xe=function(e){if(!e)return i;for(var t=[],r=Le(/\\?\"/g,e).split(","),n=0;n<r.length;n++)if(r[n].indexOf(";")>-1){var s=Ne(r[n]).split(";v=");t[n]={brand:s[0],version:s[1]}}else t[n]=Ne(r[n]);return t},Ie=function(e){return De(e)?e.toLowerCase():e},Me=function(e){return De(e)?Le(/[^\d\.]/g,e).split(".")[0]:i},je=function(e){for(var t in e){var r=e[t];typeof r==d&&2==r.length?this[r[0]]=r[1]:this[r]=i}return this},Le=function(e,t){return De(t)?t.replace(e,o):t},Ae=function(e){return Le(/\\?\"/g,e)},Ne=function(e,t){if(De(e))return e=Le(/^\s\s*/,e),typeof t===c?e:e.substring(0,500)},Be=function(e,t){if(e&&t)for(var r,n,s,o,c,l,u=0;u<t.length&&!c;){var p=t[u],h=t[u+1];for(r=n=0;r<p.length&&!c&&p[r];)if(c=p[r++].exec(e))for(s=0;s<h.length;s++)l=c[++n],typeof(o=h[s])===d&&o.length>0?2===o.length?typeof o[1]==a?this[o[0]]=o[1].call(this,l):this[o[0]]=o[1]:o.length>=3&&(typeof o[1]!==a||o[1].exec&&o[1].test?3==o.length?this[o[0]]=l?l.replace(o[1],o[2]):i:4==o.length?this[o[0]]=l?o[3].call(this,l.replace(o[1],o[2])):i:o.length>4&&(this[o[0]]=l?o[3].apply(this,[l.replace(o[1],o[2])].concat(o.slice(4))):i):o.length>3?this[o[0]]=l?o[1].apply(this,o.slice(2)):i:this[o[0]]=l?o[1].call(this,l,o[2]):i):this[o]=l||i;u+=2}},Fe=function(e,t){for(var r in t)if(typeof t[r]===d&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(Oe(t[r][n],e))return"?"===r?i:r}else if(Oe(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},ze={ME:"4.90","NT 3.51":"3.51","NT 4.0":"4.0",2e3:["5.0","5.01"],XP:["5.1","5.2"],Vista:"6.0",7:"6.1",8:"6.2",8.1:"6.3",10:["6.4","10.0"],NT:""},Ve={embedded:"Automotive",mobile:"Mobile",tablet:["Tablet","EInk"],smarttv:"TV",wearable:"Watch",xr:["VR","XR"],"?":["Desktop","Unknown"],"*":i},Ue={Chrome:"Google Chrome",Edge:"Microsoft Edge","Edge WebView2":"Microsoft Edge WebView2","Chrome WebView":"Android WebView","Chrome Headless":"HeadlessChrome","Huawei Browser":"HuaweiBrowser","MIUI Browser":"Miui Browser","Opera Mobi":"OperaMobile",Yandex:"YaBrowser"},$e={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[w,[v,_e+"Chrome"]],[/webview.+edge\/([\w\.]+)/i],[w,[v,ge+" WebView"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[w,[v,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[v,w],[/opios[\/ ]+([\w\.]+)/i],[w,[v,be+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[w,[v,be+" GX"]],[/\bopr\/([\w\.]+)/i],[w,[v,be]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[w,[v,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[w,[v,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon|otter|dooble|(?:lg |qute)browser)\/([-\w\.]+)/i,/(heytap|ovi|115|surf)browser\/([\d\.]+)/i,/(ecosia|weibo)(?:__| \w+@)([\d\.]+)/i],[v,w],[/quark(?:pc)?\/([-\w\.]+)/i],[w,[v,"Quark"]],[/\bddg\/([\w\.]+)/i],[w,[v,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[w,[v,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[w,[v,"WeChat"]],[/konqueror\/([\w\.]+)/i],[w,[v,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[w,[v,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[w,[v,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[w,[v,"Smart "+ee+Se]],[/(avast|avg)\/([\w\.]+)/i],[[v,/(.+)/,"$1 Secure"+Se],w],[/\bfocus\/([\w\.]+)/i],[w,[v,ve+" Focus"]],[/\bopt\/([\w\.]+)/i],[w,[v,be+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[w,[v,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[w,[v,"Dolphin"]],[/coast\/([\w\.]+)/i],[w,[v,be+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[w,[v,"MIUI"+Se]],[/fxios\/([\w\.-]+)/i],[w,[v,_e+ve]],[/\bqihoobrowser\/?([\w\.]*)/i],[w,[v,"360"]],[/\b(qq)\/([\w\.]+)/i],[[v,/(.+)/,"$1Browser"],w],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[v,/(.+)/,"$1"+Se],w],[/samsungbrowser\/([\w\.]+)/i],[w,[v,ce+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[w,[v,we+" Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[v,we+" Mobile"],w],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[v,w],[/(lbbrowser|rekonq)/i],[v],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[w,v],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[v,ye],w,[b,x]],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(instagram|snapchat|klarna)[\/ ]([-\w\.]+)/i],[v,w,[b,x]],[/\bgsa\/([\w\.]+) .*safari\//i],[w,[v,"GSA"],[b,x]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[w,[v,"TikTok"],[b,x]],[/\[(linkedin)app\]/i],[v,[b,x]],[/(chromium)[\/ ]([-\w\.]+)/i],[v,w],[/headlesschrome(?:\/([\w\.]+)| )/i],[w,[v,he+" Headless"]],[/wv\).+chrome\/([\w\.]+).+edgw\//i],[w,[v,ge+" WebView2"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[v,he+" WebView"],w],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[w,[v,"Android"+Se]],[/chrome\/([\w\.]+) mobile/i],[w,[v,_e+"Chrome"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[v,w],[/version\/([\w\.\,]+) .*mobile(?:\/\w+ | ?)safari/i],[w,[v,_e+"Safari"]],[/iphone .*mobile(?:\/\w+ | ?)safari/i],[[v,_e+"Safari"]],[/version\/([\w\.\,]+) .*(safari)/i],[w,v],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[v,[w,"1"]],[/(webkit|khtml)\/([\w\.]+)/i],[v,w],[/(?:mobile|tablet);.*(firefox)\/([\w\.-]+)/i],[[v,_e+ve],w],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[v,"Netscape"],w],[/(wolvic|librewolf)\/([\w\.]+)/i],[v,w],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[w,[v,ve+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[v,[w,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[v,[w,/[^\d\.]+./,o]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[_,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[_,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[_,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[_,/ower/,o,Ie]],[/ sun4\w[;\)]/i],[[_,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[_,Ie]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[C,[y,ce],[b,T]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,/sec-(sgh\w+)/i],[C,[y,ce],[b,k]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[C,[y,J],[b,k]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[C,[y,J],[b,T]],[/(macintosh);/i],[C,[y,J]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[C,[y,de],[b,k]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[C,[y,te],[b,T]],[/honor([-\w ]+)[;\)]/i],[C,[y,te],[b,k]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[C,[y,Z],[b,T]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[C,[y,Z],[b,k]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[C,/_/g," "],[y,ue],[b,T]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[C,/_/g," "],[y,ue],[b,k]],[/droid.+; (cph2[3-6]\d[13579]|((gm|hd)19|(ac|be|in|kb)20|(d[en]|eb|le|mt)21|ne22)[0-2]\d|p[g-k]\w[1m]10)\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[C,[y,oe],[b,k]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[C,[y,ae],[b,k]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[C,[y,Fe,{OnePlus:["203","304","403","404","413","415"],"*":ae}],[b,T]],[/(vivo (5r?|6|8l?|go|one|s|x[il]?[2-4]?)[\w\+ ]*)(?: bui|\))/i],[C,[y,"BLU"],[b,k]],[/; vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[C,[y,"Vivo"],[b,k]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[C,[y,"Realme"],[b,k]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[C,[y,ee],[b,T]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i],[C,[y,ee],[b,k]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,/((?:moto(?! 360)[-\w\(\) ]+|xt\d{3,4}[cgkosw\+]?[-\d]*|nexus 6)(?= bui|\)))/i],[C,[y,ne],[b,k]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[C,[y,ne],[b,T]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[C,[y,re],[b,T]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,/\blg-?([\d\w]+) bui/i],[C,[y,re],[b,k]],[/(nokia) (t[12][01])/i],[y,C,[b,T]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[C,/_/g," "],[b,k],[y,"Nokia"]],[/(pixel (c|tablet))\b/i],[C,[y,X],[b,T]],[/droid.+;(?: google)? (g(01[13]a|020[aem]|025[jn]|1b60|1f8f|2ybb|4s1m|576d|5nz6|8hhn|8vou|a02099|c15s|d1yq|e2ae|ec77|gh2x|kv4x|p4bc|pj41|r83y|tt9q|ur25|wvk6)|pixel[\d ]*a?( pro)?( xl)?( fold)?( \(5g\))?)( bui|\))/i],[C,[y,X],[b,k]],[/(google) (pixelbook( go)?)/i],[y,C],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-\w\w\d\d)(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[C,[y,le],[b,k]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[C,"Xperia Tablet"],[y,le],[b,T]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[C,[y,K],[b,T]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[C,/(.+)/g,"Fire Phone $1"],[y,K],[b,k]],[/(playbook);[-\w\),; ]+(rim)/i],[C,y,[b,T]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[C,[y,Y],[b,k]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[C,[y,Q],[b,T]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[C,[y,Q],[b,k]],[/(nexus 9)/i],[C,[y,"HTC"],[b,T]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[y,[C,/_/g," "],[b,k]],[/tcl (xess p17aa)/i,/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])(_\w(\w|\w\w))?(\)| bui)/i],[C,[y,"TCL"],[b,T]],[/droid [\w\.]+; (418(?:7d|8v)|5087z|5102l|61(?:02[dh]|25[adfh]|27[ai]|56[dh]|59k|65[ah])|a509dl|t(?:43(?:0w|1[adepqu])|50(?:6d|7[adju])|6(?:09dl|10k|12b|71[efho]|76[hjk])|7(?:66[ahju]|67[hw]|7[045][bh]|71[hk]|73o|76[ho]|79w|81[hks]?|82h|90[bhsy]|99b)|810[hs]))(_\w(\w|\w\w))?(\)| bui)/i],[C,[y,"TCL"],[b,k]],[/(itel) ((\w+))/i],[[y,Ie],C,[b,Fe,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[C,[y,"Acer"],[b,T]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[C,[y,"Meizu"],[b,k]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[C,[y,"Ulefone"],[b,k]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[C,[y,"Energizer"],[b,k]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[C,[y,"Cat"],[b,k]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[C,[y,"Smartfren"],[b,k]],[/droid.+; (a(in)?(0(15|59|6[35])|142)p?)/i],[C,[y,"Nothing"],[b,k]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[C,[y,"Archos"],[b,T]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[C,[y,"Archos"],[b,k]],[/; (n159v)/i],[C,[y,"HMD"],[b,k]],[/(imo) (tab \w+)/i,/(infinix|tecno) (x1101b?|p904|dp(7c|8d|10a)( pro)?|p70[1-3]a?|p904|t1101)/i],[y,C,[b,T]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (blu|hmd|imo|infinix|lava|oneplus|tcl)[_ ]([\w\+ ]+?)(?: bui|\)|; r)/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(oppo) ?([\w ]+) bui/i],[y,C,[b,k]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i],[y,C,[b,T]],[/(surface duo)/i],[C,[y,ie],[b,T]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[C,[y,"Fairphone"],[b,k]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[C,[y,se],[b,T]],[/(sprint) (\w+)/i],[y,C,[b,k]],[/(kin\.[onetw]{3})/i],[[C,/\./g," "],[y,ie],[b,k]],[/droid.+; ([c6]+|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[C,[y,pe],[b,T]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[C,[y,pe],[b,k]],[/smart-tv.+(samsung)/i],[y,[b,P]],[/hbbtv.+maple;(\d+)/i],[[C,/^/,"SmartTV"],[y,ce],[b,P]],[/(vizio)(?: |.+model\/)(\w+-\w+)/i,/tcast.+(lg)e?. ([-\w]+)/i],[y,C,[b,P]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[y,re],[b,P]],[/(apple) ?tv/i],[y,[C,J+" TV"],[b,P]],[/crkey.*devicetype\/chromecast/i],[[C,me+" Third Generation"],[y,X],[b,P]],[/crkey.*devicetype\/([^/]*)/i],[[C,/^/,"Chromecast "],[y,X],[b,P]],[/fuchsia.*crkey/i],[[C,me+" Nest Hub"],[y,X],[b,P]],[/crkey/i],[[C,me],[y,X],[b,P]],[/(portaltv)/i],[C,[y,ye],[b,P]],[/droid.+aft(\w+)( bui|\))/i],[C,[y,K],[b,P]],[/(shield \w+ tv)/i],[C,[y,se],[b,P]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[C,[y,de],[b,P]],[/(bravia[\w ]+)( bui|\))/i],[C,[y,le],[b,P]],[/(mi(tv|box)-?\w+) bui/i],[C,[y,ue],[b,P]],[/Hbbtv.*(technisat) (.*);/i],[y,C,[b,P]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[y,/.+\/(\w+)/,"$1",Fe,{LG:"lge"}],[C,Ne],[b,P]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[C,[b,P]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:|large screen[\w ]+safari)\b/i],[[b,P]],[/(playstation \w+)/i],[C,[y,le],[b,R]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[C,[y,ie],[b,R]],[/(ouya)/i,/(nintendo) (\w+)/i,/(retroid) (pocket ([^\)]+))/i],[y,C,[b,R]],[/droid.+; (shield)( bui|\))/i],[C,[y,se],[b,R]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[C,[y,ce],[b,O]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[y,C,[b,O]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[C,[y,ae],[b,O]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[C,[y,J],[b,O]],[/(opwwe\d{3})/i],[C,[y,oe],[b,O]],[/(moto 360)/i],[C,[y,ne],[b,O]],[/(smartwatch 3)/i],[C,[y,le],[b,O]],[/(g watch r)/i],[C,[y,re],[b,O]],[/droid.+; (wt63?0{2,3})\)/i],[C,[y,pe],[b,O]],[/droid.+; (glass) \d/i],[C,[y,X],[b,E]],[/(pico) (4|neo3(?: link|pro)?)/i],[y,C,[b,E]],[/(quest( \d| pro)?s?).+vr/i],[C,[y,ye],[b,E]],[/mobile vr; rv.+firefox/i],[[b,E]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[y,[b,D]],[/(aeobc)\b/i],[C,[y,K],[b,D]],[/(homepod).+mac os/i],[C,[y,J],[b,D]],[/windows iot/i],[[b,D]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+?(mobile|vr|\d) safari/i],[C,[b,Fe,{mobile:"Mobile",xr:"VR","*":T}]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[b,T]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[b,k]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[C,[y,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[w,[v,ge+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[v,w],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[w,[v,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[v,w],[/ladybird\//i],[[v,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[w,v]],os:[[/(windows nt) (6\.[23]); arm/i],[[v,/N/,"R"],[w,Fe,ze]],[/(windows (?:phone|mobile|iot))(?: os)?[\/ ]?([\d\.]*( se)?)/i,/(windows)[\/ ](1[01]|2000|3\.1|7|8(\.1)?|9[58]|me|server 20\d\d( r2)?|vista|xp)/i],[v,w],[/windows nt ?([\d\.\)]*)(?!.+xbox)/i,/\bwin(?=3| ?9|n)(?:nt| 9x )?([\d\.;]*)/i],[[w,/(;|\))/g,"",Fe,ze],[v,Ce]],[/(windows ce)\/?([\d\.]*)/i],[v,w],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[w,/_/g,"."],[v,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+(haiku|morphos))/i],[[v,"macOS"],[w,/_/g,"."]],[/android ([\d\.]+).*crkey/i],[w,[v,me+" Android"]],[/fuchsia.*crkey\/([\d\.]+)/i],[w,[v,me+" Fuchsia"]],[/crkey\/([\d\.]+).*devicetype\/smartspeaker/i],[w,[v,me+" SmartSpeaker"]],[/linux.*crkey\/([\d\.]+)/i],[w,[v,me+" Linux"]],[/crkey\/([\d\.]+)/i],[w,[v,me]],[/droid ([\w\.]+)\b.+(android[- ]x86)/i],[w,v],[/(ubuntu) ([\w\.]+) like android/i],[[v,/(.+)/,"$1 Touch"],w],[/(harmonyos)[\/ ]?([\d\.]*)/i,/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen)\w*[-\/\.; ]?([\d\.]*)/i],[v,w],[/\(bb(10);/i],[w,[v,Y]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[w,[v,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[w,[v,ve+" OS"]],[/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i,/webos(?:[ \/]?|\.tv-20(?=2[2-9]))(\d[\d\.]*)/i],[w,[v,"webOS"]],[/web0s;.+?(?:chr[o0]me|safari)\/(\d+)/i],[[w,Fe,{25:"120",24:"108",23:"94",22:"87",6:"79",5:"68",4:"53",3:"38",2:"538",1:"537","*":"TV"}],[v,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[w,[v,"watchOS"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[v,"Chrome OS"],w],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) (\w+)/i,/(xbox); +xbox ([^\);]+)/i,/(pico) .+os([\w\.]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/linux.+(mint)[\/\(\) ]?([\w\.]*)/i,/(mageia|vectorlinux|fuchsia|arcaos|arch(?= ?linux))[;l ]([\d\.]*)/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire|knoppix)(?: gnu[\/ ]linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/\b(aix)[; ]([1-9\.]{0,4})/i,/(hurd|linux|morphos)(?: (?:arm|x86|ppc)\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) ?(r\d)?/i],[v,w],[/(sunos) ?([\d\.]*)/i],[[v,"Solaris"],w],[/\b(beos|os\/2|amigaos|openvms|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[v,w]]},Ge=(je.call((n={init:{},isIgnore:{},isIgnoreRgx:{},toString:{}}).init,[[u,[v,w,S,b]],[p,[_]],[h,[b,C,y]],[f,[v,w]],[m,[v,w]]]),je.call(n.isIgnore,[[u,[w,S]],[f,[w]],[m,[w]]]),je.call(n.isIgnoreRgx,[[u,/ ?browser$/i],[m,/ ?os$/i]]),je.call(n.toString,[[u,[v,w]],[p,[_]],[h,[y,C]],[f,[v,w]],[m,[v,w]]]),n),qe=function(e,t){var r=Ge.init[t],i=Ge.isIgnore[t]||0,n=Ge.isIgnoreRgx[t]||0,s=Ge.toString[t]||0;function a(){je.call(this,r)}return a.prototype.getItem=function(){return e},a.prototype.withClientHints=function(){return Te?Te.getHighEntropyValues(W).then(function(t){return e.setCH(new He(t,!1)).parseCH().get()}):e.parseCH().get()},a.prototype.withFeatureCheck=function(){return e.detectFeature().get()},t!=g&&(a.prototype.is=function(e){var t=!1;for(var r in this)if(this.hasOwnProperty(r)&&!Oe(i,r)&&Ie(n?Le(n,this[r]):this[r])==Ie(n?Le(n,e):e)){if(t=!0,e!=c)break}else if(e==c&&t){t=!t;break}return t},a.prototype.toString=function(){var e=o;for(var t in s)typeof this[s[t]]!==c&&(e+=(e?" ":o)+this[s[t]]);return e||c}),Te||(a.prototype.then=function(e){var t=this,r=function(){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e])};r.prototype={is:a.prototype.is,toString:a.prototype.toString};var i=new r;return e(i),i}),new a};function He(e,t){if(e=e||{},je.call(this,W),t)je.call(this,[[I,xe(e[B])],[j,xe(e[F])],[k,/\?1/.test(e[$])],[C,Ae(e[G])],[L,Ae(e[q])],[A,Ae(e[H])],[_,Ae(e[z])],[M,xe(e[U])],[N,Ae(e[V])]]);else for(var r in e)this.hasOwnProperty(r)&&typeof e[r]!==c&&(this[r]=e[r])}function We(e,t,r,n){return this.get=function(e){return e?this.data.hasOwnProperty(e)?this.data[e]:i:this.data},this.set=function(e,t){return this.data[e]=t,this},this.setCH=function(e){return this.uaCH=e,this},this.detectFeature=function(){if(ke&&ke.userAgent==this.ua)switch(this.itemType){case u:ke.brave&&typeof ke.brave.isBrave==a&&this.set(v,"Brave");break;case h:!this.get(b)&&Te&&Te[k]&&this.set(b,k),"Macintosh"==this.get(C)&&ke&&typeof ke.standalone!==c&&ke.maxTouchPoints&&ke.maxTouchPoints>2&&this.set(C,"iPad").set(b,T);break;case m:!this.get(v)&&Te&&Te[L]&&this.set(v,Te[L]);break;case g:var e=this.data,t=function(t){return e[t].getItem().detectFeature().get()};this.set(u,t(u)).set(p,t(p)).set(h,t(h)).set(f,t(f)).set(m,t(m))}return this},this.parseUA=function(){return this.itemType!=g&&Be.call(this.data,this.ua,this.rgxMap),this.itemType==u&&this.set(S,Me(this.get(w))),this},this.parseCH=function(){var e=this.uaCH,t=this.rgxMap;switch(this.itemType){case u:case f:var r,n=e[j]||e[I];if(n)for(var s in n){var o=n[s].brand||n[s],a=n[s].version;this.itemType==u&&!/not.a.brand/i.test(o)&&(!r||/Chrom/.test(r)&&o!=fe||r==ge&&/WebView2/.test(o))&&(o=Fe(o,Ue),(r=this.get(v))&&!/Chrom/.test(r)&&/Chrom/.test(o)||this.set(v,o).set(w,a).set(S,Me(a)),r=o),this.itemType==f&&o==fe&&this.set(w,a)}break;case p:var c=e[_];c&&(c&&"64"==e[N]&&(c+="64"),Be.call(this.data,c+";",t));break;case h:if(e[k]&&this.set(b,k),e[C]&&(this.set(C,e[C]),!this.get(b)||!this.get(y))){var d={};Be.call(d,"droid 9; "+e[C]+")",t),!this.get(b)&&d.type&&this.set(b,d.type),!this.get(y)&&d.vendor&&this.set(y,d.vendor)}if(e[M]){var l;if("string"!=typeof e[M])for(var R=0;!l&&R<e[M].length;)l=Fe(e[M][R++],Ve);else l=Fe(e[M],Ve);this.set(b,l)}break;case m:var T=e[L];if(T){var P=e[A];T==Ce&&(P=parseInt(Me(P),10)>=13?"11":"10"),this.set(v,T).set(w,P)}this.get(v)==Ce&&"Xbox"==e[C]&&this.set(v,"Xbox").set(w,i);break;case g:var O=this.data,E=function(t){return O[t].getItem().setCH(e).parseCH().get()};this.set(u,E(u)).set(p,E(p)).set(h,E(h)).set(f,E(f)).set(m,E(m))}return this},je.call(this,[["itemType",e],["ua",t],["uaCH",n],["rgxMap",r],["data",qe(this,e)]]),this}function Ke(e,t,r){if(typeof e===d?(Ee(e,!0)?(typeof t===d&&(r=t),t=e):(r=e,t=i),e=i):typeof e!==l||Ee(t,!0)||(r=t,t=i),r&&typeof r.append===a){var n={};r.forEach(function(e,t){n[t]=e}),r=n}if(!(this instanceof Ke))return new Ke(e,t,r).getResult();var c=typeof e===l?e:r&&r[s]?r[s]:ke&&ke.userAgent?ke.userAgent:o,v=new He(r,!0),b=t?function(e,t){var r={},i=t;if(!Ee(t))for(var n in i={},t)for(var s in t[n])i[s]=t[n][s].concat(i[s]?i[s]:[]);for(var o in e)r[o]=i[o]&&i[o].length%2==0?i[o].concat(e[o]):e[o];return r}($e,t):$e,y=function(e){return e==g?function(){return new We(e,c,b,v).set("ua",c).set(u,this.getBrowser()).set(p,this.getCPU()).set(h,this.getDevice()).set(f,this.getEngine()).set(m,this.getOS()).get()}:function(){return new We(e,c,b[e],v).parseUA().get()}};return je.call(this,[["getBrowser",y(u)],["getCPU",y(p)],["getDevice",y(h)],["getEngine",y(f)],["getOS",y(m)],["getResult",y(g)],["getUA",function(){return c}],["setUA",function(e){return De(e)&&(c=e.length>500?Ne(e,500):e),this}]]).setUA(c),this}Ke.VERSION="2.0.4",Ke.BROWSER=Pe([v,w,S,b]),Ke.CPU=Pe([_]),Ke.DEVICE=Pe([C,y,b,R,k,P,T,O,D]),Ke.ENGINE=Ke.OS=Pe([v,w]),e.exports&&(t=e.exports=Ke),t.UAParser=Ke;var Je=Re&&(r.jQuery||r.Zepto);if(Je&&!Je.ua){var Qe=new Ke;Je.ua=Qe.getResult(),Je.ua.get=function(){return Qe.getUA()},Je.ua.set=function(e){Qe.setUA(e);var t=Qe.getResult();for(var r in t)Je.ua[r]=t[r]}}}("object"==typeof window?window:a)}(Zn,Zn.exports);var es=Zn.exports,ts={},rs=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ts,"__esModule",{value:!0});var is=ts.Logger=void 0;const ns=rs(Yn),ss="mediasoup-client";is=ts.Logger=class{constructor(e){e?(this._debug=(0,ns.default)(`${ss}:${e}`),this._warn=(0,ns.default)(`${ss}:WARN:${e}`),this._error=(0,ns.default)(`${ss}:ERROR:${e}`)):(this._debug=(0,ns.default)(ss),this._warn=(0,ns.default)(`${ss}:WARN`),this._error=(0,ns.default)(`${ss}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var os,as={},cs={exports:{}},ds="object"==typeof Reflect?Reflect:null,ls=ds&&"function"==typeof ds.apply?ds.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};os=ds&&"function"==typeof ds.ownKeys?ds.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var us=Number.isNaN||function(e){return e!=e};function ps(){ps.init.call(this)}cs.exports=ps,cs.exports.once=function(e,t){return new Promise(function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}Ss(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Ss(e,"error",t,r)}(e,n,{once:!0})})},ps.EventEmitter=ps,ps.prototype._events=void 0,ps.prototype._eventsCount=0,ps.prototype._maxListeners=void 0;var hs=10;function fs(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function ms(e){return void 0===e._maxListeners?ps.defaultMaxListeners:e._maxListeners}function gs(e,t,r,i){var n,s,o;if(fs(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=ms(e))>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function vs(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function bs(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=vs.bind(i);return n.listener=r,i.wrapFn=n,n}function ys(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(n):_s(n,n.length)}function ws(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function _s(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function Ss(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function n(s){i.once&&e.removeEventListener(t,n),r(s)})}}Object.defineProperty(ps,"defaultMaxListeners",{enumerable:!0,get:function(){return hs},set:function(e){if("number"!=typeof e||e<0||us(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");hs=e}}),ps.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ps.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||us(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},ps.prototype.getMaxListeners=function(){return ms(this)},ps.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)ls(a,this,t);else{var c=a.length,d=_s(a,c);for(r=0;r<c;++r)ls(d[r],this,t)}return!0},ps.prototype.addListener=function(e,t){return gs(this,e,t,!1)},ps.prototype.on=ps.prototype.addListener,ps.prototype.prependListener=function(e,t){return gs(this,e,t,!0)},ps.prototype.once=function(e,t){return fs(t),this.on(e,bs(this,e,t)),this},ps.prototype.prependOnceListener=function(e,t){return fs(t),this.prependListener(e,bs(this,e,t)),this},ps.prototype.removeListener=function(e,t){var r,i,n,s,o;if(fs(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,n),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},ps.prototype.off=ps.prototype.removeListener,ps.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var n,s=Object.keys(r);for(i=0;i<s.length;++i)"removeListener"!==(n=s[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},ps.prototype.listeners=function(e){return ys(this,e,!0)},ps.prototype.rawListeners=function(e){return ys(this,e,!1)},ps.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):ws.call(e,t)},ps.prototype.listenerCount=ws,ps.prototype.eventNames=function(){return this._eventsCount>0?os(this._events):[]};var Cs=cs.exports;Object.defineProperty(as,"__esModule",{value:!0}),as.EnhancedEventEmitter=void 0;const Rs=Cs,ks=new ts.Logger("EnhancedEventEmitter");class Ts extends Rs.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){ks.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(super.listenerCount(e))}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}}as.EnhancedEventEmitter=Ts;var Ps={};Object.defineProperty(Ps,"__esModule",{value:!0});var Os=Ps.InvalidStateError=Ps.UnsupportedError=void 0;class Es extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Es):this.stack=new Error(e).stack}}Ps.UnsupportedError=Es;class Ds extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ds):this.stack=new Error(e).stack}}Os=Ps.InvalidStateError=Ds;var xs={};Object.defineProperty(xs,"__esModule",{value:!0});var Is=xs.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))};xs.generateRandomNumber=function(){return Math.round(1e7*Math.random())},xs.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const i of r){const r=t[i];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var Ms={},js={},Ls={},As=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.Logger=void 0;const Ns=As(Yn),Bs="h264-profile-level-id";Ls.Logger=class{constructor(e){e?(this._debug=(0,Ns.default)(`${Bs}:${e}`),this._warn=(0,Ns.default)(`${Bs}:WARN:${e}`),this._error=(0,Ns.default)(`${Bs}:ERROR:${e}`)):(this._debug=(0,Ns.default)(Bs),this._warn=(0,Ns.default)(`${Bs}:WARN`),this._error=(0,Ns.default)(`${Bs}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(js,"__esModule",{value:!0}),js.ProfileLevelId=js.Level=js.Profile=void 0,js.parseProfileLevelId=Ks,js.profileLevelIdToString=Js,js.profileToString=function(e){switch(e){case zs.ConstrainedBaseline:return"ConstrainedBaseline";case zs.Baseline:return"Baseline";case zs.Main:return"Main";case zs.ConstrainedHigh:return"ConstrainedHigh";case zs.High:return"High";case zs.PredictiveHigh444:return"PredictiveHigh444";default:return void Fs.warn(`profileToString() | unrecognized profile ${e}`)}},js.levelToString=function(e){switch(e){case Vs.L1_b:return"1b";case Vs.L1:return"1";case Vs.L1_1:return"1.1";case Vs.L1_2:return"1.2";case Vs.L1_3:return"1.3";case Vs.L2:return"2";case Vs.L2_1:return"2.1";case Vs.L2_2:return"2.2";case Vs.L3:return"3";case Vs.L3_1:return"3.1";case Vs.L3_2:return"3.2";case Vs.L4:return"4";case Vs.L4_1:return"4.1";case Vs.L4_2:return"4.2";case Vs.L5:return"5";case Vs.L5_1:return"5.1";case Vs.L5_2:return"5.2";default:return void Fs.warn(`levelToString() | unrecognized level ${e}`)}},js.parseSdpProfileLevelId=Qs,js.isSameProfile=function(e={},t={}){const r=Qs(e),i=Qs(t);return Boolean(r&&i&&r.profile===i.profile)},js.isSameProfileAndLevel=function(e={},t={}){const r=Qs(e),i=Qs(t);return Boolean(r&&i&&r.profile===i.profile&&r.level==i.level)},js.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Fs.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=Qs(e),i=Qs(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!i)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==i.profile)throw new TypeError("H264 Profile mismatch");const n=Xs(e)&&Xs(t),s=r.level,o=i.level,a=(d=s,l=o,function(e,t){return e===Vs.L1_b?t!==Vs.L1&&t!==Vs.L1_b:t===Vs.L1_b?e!==Vs.L1:e<t}(d,l)?d:l),c=n?s:a;var d,l;return Fs.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),Js(new Us(r.profile,c))},js.supportedLevel=function(e,t){for(let r=Ws.length-1;r>=0;--r){const i=Ws[r];if(256*i.max_macroblock_frame_size<=e&&i.max_macroblocks_per_second<=t*i.max_macroblock_frame_size)return Fs.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${i.level}]`),i.level}return void Fs.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const Fs=new Ls.Logger;var zs,Vs;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(zs||(js.Profile=zs={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(Vs||(js.Level=Vs={}));class Us{constructor(e,t){this.profile=e,this.level=t}}js.ProfileLevelId=Us;const $s=new Us(zs.ConstrainedBaseline,Vs.L3_1);class Gs{constructor(e){this.mask=~Ys("x",e),this.masked_value=Ys("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class qs{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const Hs=[new qs(66,new Gs("x1xx0000"),zs.ConstrainedBaseline),new qs(77,new Gs("1xxx0000"),zs.ConstrainedBaseline),new qs(88,new Gs("11xx0000"),zs.ConstrainedBaseline),new qs(66,new Gs("x0xx0000"),zs.Baseline),new qs(88,new Gs("10xx0000"),zs.Baseline),new qs(77,new Gs("0x0x0000"),zs.Main),new qs(100,new Gs("00000000"),zs.High),new qs(100,new Gs("00001100"),zs.ConstrainedHigh),new qs(244,new Gs("00000000"),zs.PredictiveHigh444)],Ws=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Vs.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Vs.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:Vs.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:Vs.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Vs.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Vs.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:Vs.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:Vs.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:Vs.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:Vs.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:Vs.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Vs.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Vs.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:Vs.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:Vs.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:Vs.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:Vs.L5_2}];function Ks(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,i=t>>8&255,n=t>>16&255;let s;switch(r){case Vs.L1_1:s=16&i?Vs.L1_b:Vs.L1_1;break;case Vs.L1:case Vs.L1_2:case Vs.L1_3:case Vs.L2:case Vs.L2_1:case Vs.L2_2:case Vs.L3:case Vs.L3_1:case Vs.L3_2:case Vs.L4:case Vs.L4_1:case Vs.L4_2:case Vs.L5:case Vs.L5_1:case Vs.L5_2:s=r;break;default:return void Fs.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of Hs)if(n===t.profile_idc&&t.profile_iop.isMatch(i))return Fs.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new Us(t.profile,s);Fs.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${n}, profile_iop:${i}]`)}function Js(e){if(e.level==Vs.L1_b)switch(e.profile){case zs.ConstrainedBaseline:return"42f00b";case zs.Baseline:return"42100b";case zs.Main:return"4d100b";default:return void Fs.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case zs.ConstrainedBaseline:t="42e0";break;case zs.Baseline:t="4200";break;case zs.Main:t="4d00";break;case zs.ConstrainedHigh:t="640c";break;case zs.High:t="6400";break;case zs.PredictiveHigh444:t="f400";break;default:return void Fs.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function Qs(e={}){const t=e["profile-level-id"];return t?Ks(t):$s}function Ys(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)}function Xs(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}var Zs,eo=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),to=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ro=a&&a.__importStar||(Zs=function(e){return Zs=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},Zs(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=Zs(e),i=0;i<r.length;i++)"default"!==r[i]&&eo(t,e,r[i]);return to(t,e),t});Object.defineProperty(Ms,"__esModule",{value:!0}),Ms.validateRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)ho(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)mo(t)},Ms.validateRtpParameters=po,Ms.validateSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},Ms.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},Ms.getExtendedRtpCapabilities=function(e,t){const r={codecs:[],headerExtensions:[]};for(const i of t.codecs??[]){if(yo(i))continue;const t=(e.codecs??[]).find(e=>wo(e,i,{strict:!0,modify:!0}));if(!t)continue;const n={mimeType:t.mimeType,kind:t.kind,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters,remoteParameters:i.parameters,rtcpFeedback:So(t,i)};r.codecs.push(n)}for(const i of r.codecs){const r=e.codecs.find(e=>yo(e)&&e.parameters.apt===i.localPayloadType),n=t.codecs.find(e=>yo(e)&&e.parameters.apt===i.remotePayloadType);r&&n&&(i.localRtxPayloadType=r.preferredPayloadType,i.remoteRtxPayloadType=n.preferredPayloadType)}for(const i of t.headerExtensions){const t=e.headerExtensions.find(e=>_o(e,i));if(!t)continue;const n={kind:i.kind,uri:i.uri,sendId:t.preferredId,recvId:i.preferredId,encrypt:t.preferredEncrypt,direction:"sendrecv"};switch(i.direction){case"sendrecv":n.direction="sendrecv";break;case"recvonly":n.direction="sendonly";break;case"sendonly":n.direction="recvonly";break;case"inactive":n.direction="inactive"}r.headerExtensions.push(n)}return r},Ms.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={mimeType:r.mimeType,kind:r.kind,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(e),!r.remoteRtxPayloadType)continue;const i={mimeType:`${r.kind}/rtx`,kind:r.kind,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt,direction:r.direction};t.headerExtensions.push(e)}return t};var io=Ms.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.localParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},no=Ms.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.remoteParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"goog-remb"!==e.type);else if(r.headerExtensions.some(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type);else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type&&"goog-remb"!==e.type);return r},so=Ms.reduceCodecs=function(e,t){const r=[];if(t){for(let i=0;i<e.length;++i)if(wo(e[i],t,{strict:!0})){r.push(e[i]),yo(e[i+1])&&r.push(e[i+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),yo(e[1])&&r.push(e[1]);return r};Ms.generateProbatorRtpParameters=function(e){po(e=ao.clone(e));const t={mid:co,codecs:[],headerExtensions:[],encodings:[{ssrc:lo}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=uo,t.headerExtensions=e.headerExtensions,t},Ms.canSend=function(e,t){return t.codecs.some(t=>t.kind===e)},Ms.canReceive=function(e,t){if(po(e),0===e.codecs.length)return!1;const r=e.codecs[0];return t.codecs.some(e=>e.remotePayloadType===r.payloadType)};const oo=ro(js),ao=ro(xs),co="probator",lo=1234,uo=127;function po(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)go(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)vo(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)bo(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function ho(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),e.preferredPayloadType&&"number"!=typeof e.preferredPayloadType)throw new TypeError("invalid codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)fo(t)}function fo(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function mo(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function go(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)fo(t)}function vo(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function bo(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function yo(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function wo(e,t,{strict:r=!1,modify:i=!1}={}){const n=e.mimeType.toLowerCase();if(n!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(n){case"video/h264":if(r){if((e.parameters["packetization-mode"]||0)!==(t.parameters["packetization-mode"]||0))return!1;if(!oo.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=oo.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}i&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]||0)!==(t.parameters["profile-id"]||0))return!1}}return!0}function _o(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function So(e,t){const r=[];for(const i of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find(e=>e.type===i.type&&(e.parameter===i.parameter||!e.parameter&&!i.parameter));e&&r.push(e)}return r}var Co={},Ro={},ko={},To={};Object.defineProperty(To,"__esModule",{value:!0}),To.Logger=void 0;const Po=Yn,Oo="awaitqueue";To.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=Po(`${Oo}:${e}`),this._warn=Po(`${Oo}:WARN:${e}`),this._error=Po(`${Oo}:ERROR:${e}`)):(this._debug=Po(Oo),this._warn=Po(`${Oo}:WARN`),this._error=Po(`${Oo}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var Eo={};Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.AwaitQueueRemovedTaskError=Eo.AwaitQueueStoppedError=void 0;class Do extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Do)}}Eo.AwaitQueueStoppedError=Do;class xo extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,xo)}}Eo.AwaitQueueRemovedTaskError=xo,Object.defineProperty(ko,"__esModule",{value:!0}),ko.AwaitQueue=void 0;const Io=Eo,Mo=new To.Logger("AwaitQueue");
1
+ this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function i(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}function n(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if("default"!==r&&!(r in e)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(e)}var s=i(t),o=i(r),a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d,l={exports:{}},u={};l.exports=(d||(d=1,function(){"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=t,r="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},i=e.useSyncExternalStore,n=e.useRef,s=e.useEffect,o=e.useMemo,a=e.useDebugValue;u.useSyncExternalStoreWithSelector=function(e,t,c,d,l){var u=n(null);if(null===u.current){var p={hasValue:!1,value:null};u.current=p}else p=u.current;u=o(function(){function e(e){if(!s){if(s=!0,i=e,e=d(e),void 0!==l&&p.hasValue){var t=p.value;if(l(t,e))return n=t}return n=e}if(t=n,r(i,e))return t;var o=d(e);return void 0!==l&&l(t,o)?(i=e,t):(i=e,n=o)}var i,n,s=!1,o=void 0===c?null:c;return[function(){return e(t())},null===o?void 0:function(){return e(o())}]},[t,c,d,l]);var h=i(e,u[0],u[1]);return s(function(){p.hasValue=!0,p.value=h},[h]),a(h),h},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),u);var p=l.exports;var h={notify(){},get:()=>[]};var f=(()=>!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement))(),m=(()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product)(),g=(()=>f||m?s.useLayoutEffect:s.useEffect)(),v=Symbol.for("react-redux-context"),b="undefined"!=typeof globalThis?globalThis:{};function y(){if(!s.createContext)return{};const e=b[v]??=new Map;let t=e.get(s.createContext);return t||(t=s.createContext(null),t.displayName="ReactRedux",e.set(s.createContext,t)),t}var w=y();var _=function(e){const{children:t,context:r,serverState:i,store:n}=e,o=s.useMemo(()=>{const t=function(e){let t,r=h,i=0,n=!1;function s(){c.onStateChange&&c.onStateChange()}function o(){i++,t||(t=e.subscribe(s),r=function(){let e=null,t=null;return{clear(){e=null,t=null},notify(){var t;t=()=>{let t=e;for(;t;)t.callback(),t=t.next},t()},get(){const t=[];let r=e;for(;r;)t.push(r),r=r.next;return t},subscribe(r){let i=!0;const n=t={callback:r,next:null,prev:t};return n.prev?n.prev.next=n:e=n,function(){i&&null!==e&&(i=!1,n.next?n.next.prev=n.prev:t=n.prev,n.prev?n.prev.next=n.next:e=n.next)}}}}())}function a(){i--,t&&0===i&&(t(),t=void 0,r.clear(),r=h)}const c={addNestedSub:function(e){o();const t=r.subscribe(e);let i=!1;return()=>{i||(i=!0,t(),a())}},notifyNestedSubs:function(){r.notify()},handleChangeWrapper:s,isSubscribed:function(){return n},trySubscribe:function(){n||(n=!0,o())},tryUnsubscribe:function(){n&&(n=!1,a())},getListeners:()=>r};return c}(n),r={store:n,subscription:t,getServerState:i?()=>i:void 0};{const{identityFunctionCheck:t="once",stabilityCheck:i="once"}=e;return Object.assign(r,{stabilityCheck:i,identityFunctionCheck:t})}},[n,i]),a=s.useMemo(()=>n.getState(),[n]);g(()=>{const{subscription:e}=o;return e.onStateChange=e.notifyNestedSubs,e.trySubscribe(),a!==n.getState()&&e.notifyNestedSubs(),()=>{e.tryUnsubscribe(),e.onStateChange=void 0}},[o,a]);const c=r||w;return s.createElement(c.Provider,{value:o},t)};function S(e=w){return function(){const t=s.useContext(e);if(!t)throw new Error("could not find react-redux context value; please ensure the component is wrapped in a <Provider>");return t}}var C=S();function R(e=w){const t=e===w?C:S(e),r=()=>{const{store:e}=t();return e};return Object.assign(r,{withTypes:()=>r}),r}var k=R();var T=(e,t)=>e===t;var P=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),O=()=>Math.random().toString(36).substring(7).split("").join("."),E={INIT:`@@redux/INIT${O()}`,REPLACE:`@@redux/REPLACE${O()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${O()}`};function D(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function x(e){if(void 0===e)return"undefined";if(null===e)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(function(e){return e instanceof Date||"function"==typeof e.toDateString&&"function"==typeof e.getDate&&"function"==typeof e.setDate}(e))return"date";if(function(e){return e instanceof Error||"string"==typeof e.message&&e.constructor&&"number"==typeof e.constructor.stackTraceLimit}(e))return"error";const r=function(e){return"function"==typeof e.constructor?e.constructor.name:null}(e);switch(r){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return r}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function I(e){let t=typeof e;return t=x(e),t}function M(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${I(e)}'`);if("function"==typeof t&&"function"==typeof r||"function"==typeof r&&"function"==typeof arguments[3])throw new Error("It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if("function"==typeof t&&void 0===r&&(r=t,t=void 0),void 0!==r){if("function"!=typeof r)throw new Error(`Expected the enhancer to be a function. Instead, received: '${I(r)}'`);return r(M)(e,t)}let i=e,n=t,s=new Map,o=s,a=0,c=!1;function d(){o===s&&(o=new Map,s.forEach((e,t)=>{o.set(t,e)}))}function l(){if(c)throw new Error("You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return n}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${I(e)}'`);if(c)throw new Error("You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let t=!0;d();const r=a++;return o.set(r,e),function(){if(t){if(c)throw new Error("You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");t=!1,d(),o.delete(r),s=null}}}function p(e){if(!D(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${I(e)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if("string"!=typeof e.type)throw new Error(`Action "type" property must be a string. Instead, the actual type was: '${I(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,n=i(n,e)}finally{c=!1}return(s=o).forEach(e=>{e()}),e}p({type:E.INIT});return{dispatch:p,subscribe:u,getState:l,replaceReducer:function(e){if("function"!=typeof e)throw new Error(`Expected the nextReducer to be a function. Instead, received: '${I(e)}`);i=e,p({type:E.REPLACE})},[P]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(`Expected the observer to be an object. Instead, received: '${I(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[P](){return this}}}}}function j(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function L(e){const t=Object.keys(e),r={};for(let i=0;i<t.length;i++){const n=t[i];void 0===e[n]&&j(`No reducer provided for key "${n}"`),"function"==typeof e[n]&&(r[n]=e[n])}const i=Object.keys(r);let n,s;n={};try{!function(e){Object.keys(e).forEach(t=>{const r=e[t];if(void 0===r(void 0,{type:E.INIT}))throw new Error(`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(void 0===r(void 0,{type:E.PROBE_UNKNOWN_ACTION()}))throw new Error(`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${E.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)})}(r)}catch(e){s=e}return function(e={},t){if(s)throw s;{const i=function(e,t,r,i){const n=Object.keys(t),s=r&&r.type===E.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===n.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!D(e))return`The ${s} has unexpected type of "${I(e)}". Expected argument to be an object with the following keys: "${n.join('", "')}"`;const o=Object.keys(e).filter(e=>!t.hasOwnProperty(e)&&!i[e]);return o.forEach(e=>{i[e]=!0}),r&&r.type===E.REPLACE?void 0:o.length>0?`Unexpected ${o.length>1?"keys":"key"} "${o.join('", "')}" found in ${s}. Expected to find one of the known reducer keys instead: "${n.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,n);i&&j(i)}let o=!1;const a={};for(let n=0;n<i.length;n++){const s=i[n],c=r[s],d=e[s],l=c(d,t);if(void 0===l){const e=t&&t.type;throw new Error(`When called with an action of type ${e?`"${String(e)}"`:"(unknown type)"}, the slice reducer for key "${s}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}a[s]=l,o=o||l!==d}return o=o||i.length!==Object.keys(e).length,o?a:e}}function A(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...r)=>e(t(...r)))}function N(e){return D(e)&&"type"in e&&"string"==typeof e.type}var B=Symbol.for("immer-nothing"),F=Symbol.for("immer-draftable"),z=Symbol.for("immer-state"),V=[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}];function U(e,...t){{const r=V[e],i="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${i}`)}}var $=Object.getPrototypeOf;function G(e){return!!e&&!!e[z]}function q(e){return!!e&&(W(e)||Array.isArray(e)||!!e[F]||!!e.constructor?.[F]||Y(e)||Z(e))}var H=Object.prototype.constructor.toString();function W(e){if(!e||"object"!=typeof e)return!1;const t=$(e);if(null===t)return!0;const r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object||"function"==typeof r&&Function.toString.call(r)===H}function K(e,t){0===J(e)?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,i)=>t(i,r,e))}function J(e){const t=e[z];return t?t.type_:Array.isArray(e)?1:Y(e)?2:Z(e)?3:0}function Q(e,t){return 2===J(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function X(e,t,r){const i=J(e);2===i?e.set(t,r):3===i?e.add(r):e[t]=r}function Y(e){return e instanceof Map}function Z(e){return e instanceof Set}function ee(e){return e.copy_||e.base_}function te(e,t){if(Y(e))return new Map(e);if(Z(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);const r=W(e);if(!0===t||"class_only"===t&&!r){const t=Object.getOwnPropertyDescriptors(e);delete t[z];let r=Reflect.ownKeys(t);for(let i=0;i<r.length;i++){const n=r[i],s=t[n];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(t[n]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[n]})}return Object.create($(e),t)}{const t=$(e);if(null!==t&&r)return{...e};const i=Object.create(t);return Object.assign(i,e)}}function re(e,t=!1){return ne(e)||G(e)||!q(e)||(J(e)>1&&(e.set=e.add=e.clear=e.delete=ie),Object.freeze(e),t&&Object.entries(e).forEach(([e,t])=>re(t,!0))),e}function ie(){U(2)}function ne(e){return Object.isFrozen(e)}var se,oe={};function ae(e){const t=oe[e];return t||U(0,e),t}function ce(){return se}function de(e,t){t&&(ae("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function le(e){ue(e),e.drafts_.forEach(he),e.drafts_=null}function ue(e){e===se&&(se=e.parent_)}function pe(e){return se={drafts_:[],parent_:se,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function he(e){const t=e[z];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function fe(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[z].modified_&&(le(t),U(4)),q(e)&&(e=me(t,e),t.parent_||ve(t,e)),t.patches_&&ae("Patches").generateReplacementPatches_(r[z].base_,e,t.patches_,t.inversePatches_)):e=me(t,r,[]),le(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==B?e:void 0}function me(e,t,r){if(ne(t))return t;const i=t[z];if(!i)return K(t,(n,s)=>ge(e,i,t,n,s,r)),t;if(i.scope_!==e)return t;if(!i.modified_)return ve(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;const t=i.copy_;let n=t,s=!1;3===i.type_&&(n=new Set(t),t.clear(),s=!0),K(n,(n,o)=>ge(e,i,t,n,o,r,s)),ve(e,t,!1),r&&e.patches_&&ae("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function ge(e,t,r,i,n,s,o){if(n===r&&U(5),G(n)){const o=me(e,n,s&&t&&3!==t.type_&&!Q(t.assigned_,i)?s.concat(i):void 0);if(X(r,i,o),!G(o))return;e.canAutoFreeze_=!1}else o&&r.add(n);if(q(n)&&!ne(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;me(e,n),t&&t.scope_.parent_||"symbol"==typeof i||!Object.prototype.propertyIsEnumerable.call(r,i)||ve(e,n)}}function ve(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&re(t,r)}var be={get(e,t){if(t===z)return e;const r=ee(e);if(!Q(r,t))return function(e,t,r){const i=_e(t,r);return i?"value"in i?i.value:i.get?.call(e.draft_):void 0}(e,r,t);const i=r[t];return e.finalized_||!q(i)?i:i===we(e.base_,t)?(Ce(e),e.copy_[t]=Re(i,e)):i},has:(e,t)=>t in ee(e),ownKeys:e=>Reflect.ownKeys(ee(e)),set(e,t,r){const i=_e(ee(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){const i=we(ee(e),t),o=i?.[z];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((n=r)===(s=i)?0!==n||1/n==1/s:n!=n&&s!=s)&&(void 0!==r||Q(e.base_,t)))return!0;Ce(e),Se(e)}var n,s;return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==we(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,Ce(e),Se(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=ee(e),i=Reflect.getOwnPropertyDescriptor(r,t);return i?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:i.enumerable,value:r[t]}:i},defineProperty(){U(11)},getPrototypeOf:e=>$(e.base_),setPrototypeOf(){U(12)}},ye={};function we(e,t){const r=e[z];return(r?ee(r):e)[t]}function _e(e,t){if(!(t in e))return;let r=$(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=$(r)}}function Se(e){e.modified_||(e.modified_=!0,e.parent_&&Se(e.parent_))}function Ce(e){e.copy_||(e.copy_=te(e.base_,e.scope_.immer_.useStrictShallowCopy_))}K(be,(e,t)=>{ye[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),ye.deleteProperty=function(e,t){return isNaN(parseInt(t))&&U(13),ye.set.call(this,e,t,void 0)},ye.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&U(14),be.set.call(this,e[0],t,r,e[0])};function Re(e,t){const r=Y(e)?ae("MapSet").proxyMap_(e,t):Z(e)?ae("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),i={type_:r?1:0,scope_:t?t.scope_:ce(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let n=i,s=be;r&&(n=[i],s=ye);const{revoke:o,proxy:a}=Proxy.revocable(n,s);return i.draft_=a,i.revoke_=o,a}(e,t);return(t?t.scope_:ce()).drafts_.push(r),r}function ke(e){if(!q(e)||ne(e))return e;const t=e[z];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=te(e,t.scope_.immer_.useStrictShallowCopy_)}else r=te(e,!0);return K(r,(e,t)=>{X(r,e,ke(t))}),t&&(t.finalized_=!1),r}var Te=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,r)=>{if("function"==typeof e&&"function"!=typeof t){const r=t;t=e;const i=this;return function(e=r,...n){return i.produce(e,e=>t.call(this,e,...n))}}let i;if("function"!=typeof t&&U(6),void 0!==r&&"function"!=typeof r&&U(7),q(e)){const n=pe(this),s=Re(e,void 0);let o=!0;try{i=t(s),o=!1}finally{o?le(n):ue(n)}return de(n,r),fe(i,n)}if(!e||"object"!=typeof e){if(i=t(e),void 0===i&&(i=e),i===B&&(i=void 0),this.autoFreeze_&&re(i,!0),r){const t=[],n=[];ae("Patches").generateReplacementPatches_(e,i,t,n),r(t,n)}return i}U(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,i;return[this.produce(e,t,(e,t)=>{r=e,i=t}),r,i]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){q(e)||U(8),G(e)&&(e=function(e){G(e)||U(10,e);return ke(e)}(e));const t=pe(this),r=Re(e,void 0);return r[z].isManual_=!0,ue(t),r}finishDraft(e,t){const r=e&&e[z];r&&r.isManual_||U(9);const{scope_:i}=r;return de(i,t),fe(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const i=t[r];if(0===i.path.length&&"replace"===i.op){e=i.value;break}}r>-1&&(t=t.slice(r+1));const i=ae("Patches").applyPatches_;return G(e)?i(e,t):this.produce(e,e=>i(e,t))}},Pe=Te.produce;Te.produceWithPatches.bind(Te),Te.setAutoFreeze.bind(Te),Te.setUseStrictShallowCopy.bind(Te),Te.applyPatches.bind(Te),Te.createDraft.bind(Te),Te.finishDraft.bind(Te);var Oe=(e,t,r)=>{if(1===t.length&&t[0]===r){let t=!1;try{const r={};e(r)===r&&(t=!0)}catch{}if(t){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("The result function returned its own inputs without modification. e.g\n`createSelector([state => state.todos], todos => todos)`\nThis could lead to inefficient memoization and unnecessary re-renders.\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.",{stack:e})}}},Ee=(e,t,r)=>{const{memoize:i,memoizeOptions:n}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=i(()=>({}),...n);if(!(a.apply(null,s)===a.apply(null,o))){let e;try{throw new Error}catch(t){({stack:e}=t)}console.warn("An input selector returned a different result when passed same arguments.\nThis means your output selector will likely run more frequently than intended.\nAvoid returning a new reference inside your input selector, e.g.\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`",{arguments:r,firstInputs:s,secondInputs:o,stack:e})}},De={inputStabilityCheck:"once",identityFunctionCheck:"once"};var xe=e=>Array.isArray(e)?e:[e];function Ie(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const r=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${r}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Me(e,t){const r=[],{length:i}=e;for(let n=0;n<i;n++)r.push(e[n].apply(null,t));return r}var je="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function Le(){return{s:0,v:void 0,o:null,p:null}}function Ae(e,t={}){let r={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:i}=t;let n,s=0;function o(){let t=r;const{length:o}=arguments;for(let e=0,r=o;e<r;e++){const r=arguments[e];if("function"==typeof r||"object"==typeof r&&null!==r){let e=t.o;null===e&&(t.o=e=new WeakMap);const i=e.get(r);void 0===i?(t=Le(),e.set(r,t)):t=i}else{let e=t.p;null===e&&(t.p=e=new Map);const i=e.get(r);void 0===i?(t=Le(),e.set(r,t)):t=i}}const a=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),s++,i){const e=n?.deref?.()??n;null!=e&&i(e,c)&&(c=e,0!==s&&s--);n="object"==typeof c&&null!==c||"function"==typeof c?new je(c):c}return a.s=1,a.v=c,c}return o.clearCache=()=>{r={s:0,v:void 0,o:null,p:null},o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function Ne(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,i=(...e)=>{let t,i=0,n=0,s={},o=e.pop();"object"==typeof o&&(s=o,o=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);const a={...r,...s},{memoize:c,memoizeOptions:d=[],argsMemoize:l=Ae,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=xe(d),f=xe(u),m=Ie(e),g=c(function(){return i++,o.apply(null,arguments)},...h);let v=!0;const b=l(function(){n++;const e=Me(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:i}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:i}={...De,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:Oe},inputStabilityCheck:{shouldRun:"always"===i||"once"===i&&e,run:Ee}}})(v,p);if(r.shouldRun&&r.run(o,e,t),i.shouldRun){const t=Me(m,arguments);i.run({inputSelectorResults:e,inputSelectorResultsCopy:t},{memoize:c,memoizeOptions:h},arguments)}v&&(v=!1)}return t},...f);return Object.assign(b,{resultFunc:o,memoizedResultFunc:g,dependencies:m,dependencyRecomputations:()=>n,resetDependencyRecomputations:()=>{n=0},lastResult:()=>t,recomputations:()=>i,resetRecomputations:()=>{i=0},memoize:c,argsMemoize:l})};return Object.assign(i,{withTypes:()=>i}),i}var Be=Ne(Ae),Fe=Object.assign((e,t=Be)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const r=Object.keys(e),i=t(r.map(t=>e[t]),(...e)=>e.reduce((e,t,i)=>(e[r[i]]=t,e),{}));return i},{withTypes:()=>Fe});function ze(e){return({dispatch:t,getState:r})=>i=>n=>"function"==typeof n?n(t,r,e):i(n)}var Ve=ze(),Ue=ze,$e="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?A:A.apply(null,arguments)},Ge=e=>e&&"function"==typeof e.match;function qe(e,t){function r(...r){if(t){let i=t(...r);if(!i)throw new Error("prepareAction did not return an object");return{type:e,payload:i.payload,..."meta"in i&&{meta:i.meta},..."error"in i&&{error:i.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>N(t)&&t.type===e,r}function He(e){return"function"==typeof e&&"type"in e&&Ge(e)}function We(e,t){let r=0;return{measureTime(e){const t=Date.now();try{return e()}finally{const e=Date.now();r+=e-t}},warnIfExceeded(){r>e&&console.warn(`${t} took ${r}ms, which is more than the warning threshold of ${e}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)}}}var Ke=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Je(e){return q(e)?Pe(e,()=>{}):e}function Qe(e,t,r){return e.has(t)?e.get(t):e.set(t,r(t)).get(t)}function Xe(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function Ye(e,t,r){const i=Ze(e,t,r);return{detectMutations:()=>et(e,t,i,r)}}function Ze(e,t=[],r,i="",n=new Set){const s={value:r};if(!e(r)&&!n.has(r)){n.add(r),s.children={};for(const n in r){const o=i?i+"."+n:n;t.length&&-1!==t.indexOf(o)||(s.children[n]=Ze(e,t,r[n],o))}}return s}function et(e,t=[],r,i,n=!1,s=""){const o=r?r.value:void 0,a=o===i;if(n&&!a&&!Number.isNaN(i))return{wasMutated:!0,path:s};if(e(o)||e(i))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in i)c[e]=!0;const d=t.length>0;for(let n in c){const o=s?s+"."+n:n;if(d){if(t.some(e=>e instanceof RegExp?e.test(o):o===e))continue}const c=et(e,t,r.children[n],i[n],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function tt(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||D(e)}function rt(e,t="",r=tt,i,n=[],s){let o;if(!r(e))return{keyPath:t||"<root>",value:e};if("object"!=typeof e||null===e)return!1;if(s?.has(e))return!1;const a=null!=i?i(e):Object.entries(e),c=n.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(n.some(e=>e instanceof RegExp?e.test(a):a===e))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=rt(d,a,r,i,n,s),o))return o}return s&&it(e)&&s.add(e),!1}function it(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!it(t))return!1;return!0}function nt(e){return"boolean"==typeof e}var st=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:i=!0,actionCreatorCheck:n=!0}=e??{};let s=new Ke;if(t&&(nt(t)?s.push(Ve):s.push(Ue(t.extraArgument))),r){let e={};nt(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,i,n){return JSON.stringify(e,r(t,n),i)},r=function(e,t){let r=[],i=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+i.slice(0,r.indexOf(t)).join(".")+"]"}),function(n,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?i.splice(o,1/0,n):i.push(n),~r.indexOf(s)&&(s=t.call(this,n,s))}else r.push(s);return null==e?s:e.call(this,n,s)}},{isImmutable:i=Xe,ignoredPaths:n,warnAfter:s=32}=e;const o=Ye.bind(null,i,n);return({getState:e})=>{let r,i=e(),n=o(i);return a=>c=>{const d=We(s,"ImmutableStateInvariantMiddleware");d.measureTime(()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected between dispatches, in the path '${r.path||""}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)});const l=a(c);return d.measureTime(()=>{if(i=e(),r=n.detectMutations(),n=o(i),r.wasMutated)throw new Error(`A state mutation was detected inside a dispatch, in the path: ${r.path||""}. Take a look at the reducer(s) handling the action ${t(c)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}),d.warnIfExceeded(),l}}}}(e))}if(i){let e={};nt(i)||(e=i),s.push(function(e={}){{const{isSerializable:t=tt,getEntries:r,ignoredActions:i=[],ignoredActionPaths:n=["meta.arg","meta.baseQueryMeta"],ignoredPaths:s=[],warnAfter:o=32,ignoreState:a=!1,ignoreActions:c=!1,disableCache:d=!1}=e,l=!d&&WeakSet?new WeakSet:void 0;return e=>d=>u=>{if(!N(u))return d(u);const p=d(u),h=We(o,"SerializableStateInvariantMiddleware");return c||i.length&&-1!==i.indexOf(u.type)||h.measureTime(()=>{const e=rt(u,"",t,r,n,l);if(e){const{keyPath:t,value:r}=e;console.error(`A non-serializable value was detected in an action, in the path: \`${t}\`. Value:`,r,"\nTake a look at the logic that dispatched this action: ",u,"\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)","\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)")}}),a||(h.measureTime(()=>{const i=rt(e.getState(),"",t,r,s,l);if(i){const{keyPath:e,value:t}=i;console.error(`A non-serializable value was detected in the state, in the path: \`${e}\`. Value:`,t,`\nTake a look at the reducer(s) handling this action type: ${u.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}}),h.warnIfExceeded()),p}}}(e))}if(n){let e={};nt(n)||(e=n),s.unshift(function(e={}){const{isActionCreator:t=He}=e;return()=>e=>r=>(t(r)&&console.warn(function(e){const t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}(r.type)),e(r))}(e))}return s},ot=e=>t=>{setTimeout(t,e)},at=e=>function(t){const{autoBatch:r=!0}=t??{};let i=new Ke(e);return r&&i.push(((e={type:"raf"})=>t=>(...r)=>{const i=t(...r);let n=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:ot(10):"callback"===e.type?e.queueNotification:ot(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach(e=>e()))};return Object.assign({},i,{subscribe(e){const t=i.subscribe(()=>n&&e());return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return n=!e?.meta?.RTK_autoBatch,s=!n,s&&(o||(o=!0,c(d))),i.dispatch(e)}finally{n=!0}}})})("object"==typeof r?r:void 0)),i};function ct(e){const t=st(),{reducer:r,middleware:i,devTools:n=!0,duplicateMiddlewareCheck:s=!0,preloadedState:o,enhancers:a}=e||{};let c,d;if("function"==typeof r)c=r;else{if(!D(r))throw new Error("`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");c=L(r)}if(i&&"function"!=typeof i)throw new Error("`middleware` field must be a callback");if("function"==typeof i){if(d=i(t),!Array.isArray(d))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else d=t();if(d.some(e=>"function"!=typeof e))throw new Error("each middleware provided to configureStore must be a function");if(s){let e=new Set;d.forEach(t=>{if(e.has(t))throw new Error("Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");e.add(t)})}let l=A;n&&(l=$e({trace:!0,..."object"==typeof n&&n}));const u=function(...e){return t=>(r,i)=>{const n=t(r,i);let s=()=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const o={getState:n.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map(e=>e(o));return s=A(...a)(n.dispatch),{...n,dispatch:s}}}(...d),p=at(u);if(a&&"function"!=typeof a)throw new Error("`enhancers` field must be a callback");let h="function"==typeof a?a(p):p();if(!Array.isArray(h))throw new Error("`enhancers` callback must return an array");if(h.some(e=>"function"!=typeof e))throw new Error("each enhancer provided to configureStore must be a function");d.length&&!h.includes(u)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return M(c,o,l(...h))}function dt(e){const t={},r=[];let i;const n={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(i)throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");const o="string"==typeof e?e:e.type;if(!o)throw new Error("`builder.addCase` cannot be called with an empty action type");if(o in t)throw new Error(`\`builder.addCase\` cannot be called with two reducers for the same action type '${o}'`);return t[o]=s,n},addMatcher(e,t){if(i)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),n},addDefaultCase(e){if(i)throw new Error("`builder.addDefaultCase` can only be called once");return i=e,n}};return e(n),[t,r,i]}function lt(...e){return t=>e.some(e=>((e,t)=>Ge(e)?e.match(t):e(t))(e,t))}var ut=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t},pt=["name","message","stack","code"],ht=class{constructor(e,t){this.payload=e,this.meta=t}_type},ft=class{constructor(e,t){this.payload=e,this.meta=t}_type},mt=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of pt)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},gt="External signal was aborted",vt=(()=>{function e(e,t,r){const i=qe(e+"/fulfilled",(e,t,r,i)=>({payload:e,meta:{...i||{},arg:r,requestId:t,requestStatus:"fulfilled"}})),n=qe(e+"/pending",(e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}})),s=qe(e+"/rejected",(e,t,i,n,s)=>({payload:n,error:(r&&r.serializeError||mt)(e||"Rejected"),meta:{...s||{},arg:i,requestId:t,rejectedWithValue:!!n,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}}));return Object.assign(function(e,{signal:o}={}){return(a,c,d)=>{const l=r?.idGenerator?r.idGenerator(e):ut(),u=new AbortController;let p,h;function f(e){h=e,u.abort()}o&&(o.aborted?f(gt):o.addEventListener("abort",()=>f(gt),{once:!0}));const m=async function(){let o;try{let s=r?.condition?.(e,{getState:c,extra:d});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||u.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise((e,t)=>{p=()=>{t({name:"AbortError",message:h||"Aborted"})},u.signal.addEventListener("abort",p)});a(n(l,e,r?.getPendingMeta?.({requestId:l,arg:e},{getState:c,extra:d}))),o=await Promise.race([m,Promise.resolve(t(e,{dispatch:a,getState:c,extra:d,requestId:l,signal:u.signal,abort:f,rejectWithValue:(e,t)=>new ht(e,t),fulfillWithValue:(e,t)=>new ft(e,t)})).then(t=>{if(t instanceof ht)throw t;return t instanceof ft?i(t.payload,l,e,t.meta):i(t,l,e)})])}catch(t){o=t instanceof ht?s(null,l,e,t.payload,t.meta):s(t,l,e)}finally{p&&u.signal.removeEventListener("abort",p)}return r&&!r.dispatchConditionRejection&&s.match(o)&&o.meta.condition||a(o),o}();return Object.assign(m,{abort:f,requestId:l,arg:e,unwrap:()=>m.then(bt)})}},{pending:n,rejected:s,fulfilled:i,settled:lt(s,i),typePrefix:e})}return e.withTypes=()=>e,e})();function bt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var yt=Symbol.for("rtk-slice-createasyncthunk");function wt(e,t){return`${e}/${t}`}function _t({creators:e}={}){const t=e?.asyncThunk?.[yt];return function(e){const{name:r,reducerPath:i=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const n=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},s=Object.keys(n),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},a={addCase(e,t){const r="string"==typeof e?e:e.type;if(!r)throw new Error("`context.addCase` cannot be called with an empty action type");if(r in o.sliceCaseReducersByType)throw new Error("`context.addCase` cannot be called with two reducers for the same action type: "+r);return o.sliceCaseReducersByType[r]=t,a},addMatcher:(e,t)=>(o.sliceMatchers.push({matcher:e,reducer:t}),a),exposeAction:(e,t)=>(o.actionCreators[e]=t,a),exposeCaseReducer:(e,t)=>(o.sliceCaseReducersByName[e]=t,a)};function c(){if("object"==typeof e.extraReducers)throw new Error("The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[t={},r=[],i]="function"==typeof e.extraReducers?dt(e.extraReducers):[e.extraReducers],n={...t,...o.sliceCaseReducersByType};return function(e,t){if("object"==typeof t)throw new Error("The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let r,[i,n,s]=dt(t);if("function"==typeof e)r=()=>Je(e());else{const t=Je(e);r=()=>t}function o(e=r(),t){let o=[i[t.type],...n.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return 0===o.filter(e=>!!e).length&&(o=[s]),o.reduce((e,r)=>{if(r){if(G(e)){const i=r(e,t);return void 0===i?e:i}if(q(e))return Pe(e,e=>r(e,t));{const i=r(e,t);if(void 0===i){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return i}}return e},e)}return o.getInitialState=r,o}(e.initialState,e=>{for(let t in n)e.addCase(t,n[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);i&&e.addDefaultCase(i)})}s.forEach(i=>{const s=n[i],o={reducerName:i,type:wt(r,i),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},i,n){let s,o;if("reducer"in i){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(i))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=i.reducer,o=i.prepare}else s=i;n.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?qe(e,o):qe(e))}(o,s,a):function({type:e,reducerName:t},r,i,n){if(!n)throw new Error("Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:s,fulfilled:o,pending:a,rejected:c,settled:d,options:l}=r,u=n(e,s,l);i.exposeAction(t,u),o&&i.addCase(u.fulfilled,o);a&&i.addCase(u.pending,a);c&&i.addCase(u.rejected,c);d&&i.addMatcher(u.settled,d);i.exposeCaseReducer(t,{fulfilled:o||Rt,pending:a||Rt,rejected:c||Rt,settled:d||Rt})}(o,s,a,t)});const d=e=>e,l=new Map,u=new WeakMap;let p;function h(e,t){return p||(p=c()),p(e,t)}function f(){return p||(p=c()),p.getInitialState()}function m(t,r=!1){function i(e){let n=e[t];if(void 0===n){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");n=Qe(u,i,f)}return n}function n(t=d){const i=Qe(l,r,()=>new WeakMap);return Qe(i,t,()=>{const i={};for(const[n,s]of Object.entries(e.selectors??{}))i[n]=St(s,t,()=>Qe(u,t,f),r);return i})}return{reducerPath:t,getSelectors:n,get selectors(){return n(i)},selectSlice:i}}const g={name:r,reducer:h,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:f,...m(i),injectInto(e,{reducerPath:t,...r}={}){const n=t??i;return e.inject({reducerPath:n,reducer:h},r),{...g,...m(n,!0)}}};return g}}function St(e,t,r,i){function n(n,...s){let o=t(n);if(void 0===o){if(!i)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return n.unwrapped=e,n}var Ct=_t();function Rt(){}var kt="listener",Tt="completed",Pt="cancelled",Ot=`task-${Pt}`,Et=`task-${Tt}`,Dt=`${kt}-${Pt}`,xt=`${kt}-${Tt}`,It=class{constructor(e){this.code=e,this.message=`task ${Pt} (reason: ${e})`}name="TaskAbortError";message},Mt=(e,t)=>{if("function"!=typeof e)throw new TypeError(`${t} is not a function`)},jt=()=>{},Lt=(e,t=jt)=>(e.catch(t),e),At=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Nt=(e,t)=>{const r=e.signal;r.aborted||("reason"in r||Object.defineProperty(r,"reason",{enumerable:!0,value:t,configurable:!0,writable:!0}),e.abort(t))},Bt=e=>{if(e.aborted){const{reason:t}=e;throw new It(t)}};function Ft(e,t){let r=jt;return new Promise((i,n)=>{const s=()=>n(new It(e.reason));e.aborted?s():(r=At(e,s),t.finally(()=>r()).then(i,n))}).finally(()=>{r=jt})}var zt=e=>t=>Lt(Ft(e,t).then(t=>(Bt(e),t))),Vt=e=>{const t=zt(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:Ut}=Object,$t={},Gt="listenerMiddleware",qt=(e,t)=>(r,i)=>{Mt(r,"taskExecutor");const n=new AbortController;var s;s=n,At(e,()=>Nt(s,e.reason));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof It?"cancelled":"rejected",error:e}}finally{t?.()}})(async()=>{Bt(e),Bt(n.signal);const t=await r({pause:zt(n.signal),delay:Vt(n.signal),signal:n.signal});return Bt(n.signal),t},()=>Nt(n,Et));return i?.autoJoin&&t.push(o.catch(jt)),{result:zt(e)(o),cancel(){Nt(n,Ot)}}},Ht=(e,t)=>(r,i)=>Lt((async(r,i)=>{Bt(t);let n=()=>{};const s=[new Promise((t,i)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});n=()=>{s(),i()}})];null!=i&&s.push(new Promise(e=>setTimeout(e,i,null)));try{const e=await Ft(t,Promise.race(s));return Bt(t),e}finally{n()}})(r,i)),Wt=e=>{let{type:t,actionCreator:r,matcher:i,predicate:n,effect:s}=e;if(t)n=qe(t).match;else if(r)t=r.type,n=r.match;else if(i)n=i;else if(!n)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return Mt(s,"options.listener"),{predicate:n,type:t,effect:s}},Kt=Ut(e=>{const{type:t,predicate:r,effect:i}=Wt(e);return{id:ut(),effect:i,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}},{withTypes:()=>Kt}),Jt=(e,t)=>{const{type:r,effect:i,predicate:n}=Wt(t);return Array.from(e.values()).find(e=>("string"==typeof r?e.type===r:e.predicate===n)&&e.effect===i)},Qt=e=>{e.pending.forEach(e=>{Nt(e,Dt)})},Xt=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout(()=>{throw e},0)}},Yt=Ut(qe(`${Gt}/add`),{withTypes:()=>Yt}),Zt=qe(`${Gt}/removeAll`),er=Ut(qe(`${Gt}/remove`),{withTypes:()=>er}),tr=(...e)=>{console.error(`${Gt}/error`,...e)};let rr=!0,ir=!0;function nr(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseFloat(i[r],10)}function sr(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function or(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(rr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function ar(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(ir=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function cr(){if("object"==typeof window){if(rr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function dr(e,t){ir&&console.warn(e+" is deprecated, please use "+t+" instead.")}function lr(e){return"[object Object]"===Object.prototype.toString.call(e)}function ur(e){return lr(e)?Object.keys(e).reduce(function(t,r){const i=lr(e[r]),n=i?ur(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})},{}):e}function pr(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?pr(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach(t=>{pr(e,e.get(t),r)})}))}function hr(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(r=>{r.type===i&&r.trackId===t.id&&pr(e,r,n)})}),n}const fr=cr;function mr(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach(e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then(r=>{let o=(r=r.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),fr("chrome: "+JSON.stringify(e)),n(e)})}e.video=i(e.video)}return fr("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,e=>{r.webkitGetUserMedia(e,t,e=>{i&&i(s(e))})})}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function gr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function vr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.track.id):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}),t.stream.getTracks().forEach(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===r.id):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else sr(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function br(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function yr(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>hr(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sr(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>hr(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach(r=>{r.track===e&&(t?i=!0:t=r)}),this.getReceivers().forEach(t=>(t.track===e&&(r?i=!0:r=t),t.track===e)),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function wr(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),n.apply(this,arguments)}}function _r(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return wr(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)}),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const n=this._streams[r.id];if(n)n.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then(e=>s(this,e))}};e.RTCPeerConnection.prototype[t]=i[t]});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:r})}(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(r=>{this._streams[r].getTracks().find(t=>e.track===t)&&(t=this._streams[r])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Sr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]})}function Cr(e,t){sr(e,"negotiationneeded",e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e})}var Rr=Object.freeze({__proto__:null,fixNegotiationNeeded:Cr,shimAddTrackRemoveTrack:_r,shimAddTrackRemoveTrackWithNative:wr,shimGetSendersWithDtmf:br,shimGetUserMedia:mr,shimMediaStream:gr,shimOnTrack:vr,shimPeerConnection:Sr,shimSenderReceiverGetStats:yr});function kr(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){dr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function Tr(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Pr(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]});const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then(e=>{if(t.version<53&&!n)try{e.forEach(e=>{e.type=r[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))})}return e}).then(n,s)}}function Or(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Er(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),sr(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Dr(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){dr("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function xr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Ir(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const r=e.length>0;r&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(r).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return i})}function Mr(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function jr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Lr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Ar=Object.freeze({__proto__:null,shimAddTransceiver:Ir,shimCreateAnswer:Lr,shimCreateOffer:jr,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})},shimGetParameters:Mr,shimGetUserMedia:kr,shimOnTrack:Tr,shimPeerConnection:Pr,shimRTCDataChannel:xr,shimReceiverGetStats:Er,shimRemoveStream:Dr,shimSenderGetStats:Or});function Nr(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(r=>t.call(this,r,e)),e.getVideoTracks().forEach(r=>t.call(this,r,e))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach(e=>{r.includes(e.track)&&this.removeTrack(e)})})}}function Br(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)})}),t.apply(e,arguments)}}}function Fr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function zr(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(Vr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Vr(e){return e&&void 0!==e.video?Object.assign({},e,{video:ur(e.video)}):e}function Ur(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];void 0===i.urls&&i.url?(dr("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function $r(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gr(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function qr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Hr=Object.freeze({__proto__:null,shimAudioContext:qr,shimCallbacksAPI:Fr,shimConstraints:Vr,shimCreateOfferLegacy:Gr,shimGetUserMedia:zr,shimLocalStreamsAPI:Nr,shimRTCIceServerUrls:Ur,shimRemoteStreamsAPI:Br,shimTrackEventTransceiver:$r}),Wr={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){const r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){const r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter(e=>0===e.indexOf(r))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const r={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":r.relatedAddress=t[e+1];break;case"rport":r.relatedPort=parseInt(t[e+1],10);break;case"tcptype":r.tcpType=t[e+1];break;case"ufrag":r.ufrag=t[e+1],r.usernameFragment=t[e+1];break;default:void 0===r[t[e]]&&(r[t[e]]=t[e+1])}return r},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const r=e.component;"rtp"===r?t.push(1):"rtcp"===r?t.push(2):t.push(r),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let r;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)r=i[e].trim().split("="),t[r[0].trim()]=r[1];return t},t.writeFmtp=function(e){let t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)}),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),r={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substring(t+1,i),r.value=e.substring(i+1)):r.attribute=e.substring(t+1),r},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let r="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),r},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){const i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substring(12),password:n.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");r.profile=i[2];for(let n=3;n<i.length;n++){const s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const i=t.parseRtpMap(o),n=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(i.parameters=n.length?t.parseFmtp(n[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{r.headerExtensions.push(t.parseExtmap(e))});const n=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach(e=>{n.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),r},t.writeRtpDescription=function(e,r){let i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=r.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach(e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)});let n=0;return r.codecs.forEach(e=>{e.maxptime>n&&(n=e.maxptime)}),n>0&&(i+="a=maxptime:"+n+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach(e=>{i+=t.writeExtmap(e)}),i},t.parseRtpEncodingParameters=function(e){const r=[],i=t.parseRtpParameters(e),n=-1!==i.fecMechanisms.indexOf("RED"),s=-1!==i.fecMechanisms.indexOf("ULPFEC"),o=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),r.push(t),n&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},r.push(t))}}),0===r.length&&a&&r.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach(e=>{e.maxBitrate=l})),r},t.parseRtcpParameters=function(e){const r={},i=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);const n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;const s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let r;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return r=i[0].substring(7).split(" "),{stream:r[0],track:r[1]};const n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return n.length>0?(r=n[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let n;i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);const s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};const o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){const e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){let r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,r,i){let n;const s=void 0!==r?r:2;n=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+n+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const r=t.splitLines(e)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){const r=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const r=t.splitLines(e);for(let e=0;e<r.length;e++)if(r[e].length<2||"="!==r[e].charAt(1))return!1;return!0},e.exports=t}(Wr);var Kr=Wr.exports,Jr=c(Kr),Qr=n({__proto__:null,default:Jr},[Kr]);function Xr(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){const r=new t(e),i=Jr.parseCandidate(e.candidate);for(const e in i)e in r||Object.defineProperty(r,e,{value:i[e]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,sr(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Yr(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||sr(e,"icecandidate",e=>{if(e.candidate){const t=Jr.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Zr(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(function(e){if(!e||!e.sdp)return!1;const t=Jr.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Jr.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})}(arguments[0])){const e=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r}(arguments[0]),r=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r}(e),i=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=Jr.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i}(arguments[0],e);let n;n=0===r&&0===i?Number.POSITIVE_INFINITY:0===r||0===i?Math.max(r,i):Math.min(r,i);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>n}),this._sctp=s}return r.apply(this,arguments)}}function ei(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},sr(e,"datachannel",e=>(t(e.channel,e.target),e))}function ti(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function ri(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t._safariVersion>=13.1)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function ii(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ni(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.setLocalDescription;r&&0!==r.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return r.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return r.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>r.apply(this,[e]))})}var si=Object.freeze({__proto__:null,removeExtmapAllowMixed:ri,shimAddIceCandidateNullOrEmpty:ii,shimConnectionState:ti,shimMaxMessageSize:Zr,shimParameterlessSetLocalDescription:ni,shimRTCIceCandidate:Xr,shimRTCIceCandidateRelayProtocol:Yr,shimSendThrowTypeError:ei});const oi=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=cr,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.userAgentData&&r.userAgentData.brands){const e=r.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(r.mozGetUserMedia)t.browser="firefox",t.version=parseInt(nr(r.userAgent,/Firefox\/(\d+)\./,1));else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=parseInt(nr(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=parseInt(nr(r.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=nr(r.userAgent,/Version\/(\d+(\.?\d+))/,1)}return t}(e),n={browserDetails:i,commonShim:si,extractVersion:nr,disableLog:or,disableWarnings:ar,sdp:Qr};switch(i.browser){case"chrome":if(!Rr||!Sr||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=Rr,ii(e,i),ni(e),mr(e,i),gr(e),Sr(e,i),vr(e),_r(e,i),br(e),yr(e),Cr(e,i),Xr(e),Yr(e),ti(e),Zr(e,i),ei(e),ri(e,i);break;case"firefox":if(!Ar||!Pr||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Ar,ii(e,i),ni(e),kr(e,i),Pr(e,i),Tr(e),Dr(e),Or(e),Er(e),xr(e),Ir(e),Mr(e),jr(e),Lr(e),Xr(e),ti(e),Zr(e,i),ei(e);break;case"safari":if(!Hr||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=Hr,ii(e,i),ni(e),Ur(e),Gr(e),Fr(e),Nr(e),Br(e),$r(e),zr(e),qr(e),Xr(e),Yr(e),Zr(e,i),ei(e),ri(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});function ai(e){return{id:e.id,tracks:e.getTracks().map(function(e){return{id:e.id,kind:e.kind,label:e.label,enabled:e.enabled,muted:e.muted,readyState:e.readyState}})}}var ci=function(e,t,r){var i=0,n=!!window.mozRTCPeerConnection,s=!!window.RTCIceGatherer,o={};if(r.forEach(function(r){if(window[r+"RTCPeerConnection"]&&("webkit"!==r||!s)){var a=window[r+"RTCPeerConnection"],c=function(r,c){var d=new a(r,c),l="PC_"+i++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach(function(e){delete e.credential}),r.browserType=n?"moz":s?"edge":"webkit",e("create",l,r),c&&e("constraints",l,c),d.addEventListener("icecandidate",function(t){e("onicecandidate",l,t.candidate)}),d.addEventListener("addstream",function(t){e("onaddstream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("track",function(t){e("ontrack",l,t.track.kind+":"+t.track.id+" "+t.streams.map(function(e){return"stream:"+e.id}))}),d.addEventListener("removestream",function(t){e("onremovestream",l,t.stream.id+" "+t.stream.getTracks().map(function(e){return e.kind+":"+e.id}))}),d.addEventListener("signalingstatechange",function(){e("onsignalingstatechange",l,d.signalingState)}),d.addEventListener("iceconnectionstatechange",function(){e("oniceconnectionstatechange",l,d.iceConnectionState)}),d.addEventListener("icegatheringstatechange",function(){e("onicegatheringstatechange",l,d.iceGatheringState)}),d.addEventListener("connectionstatechange",function(){e("onconnectionstatechange",l,d.connectionState)}),d.addEventListener("negotiationneeded",function(){e("onnegotiationneeded",l,void 0)}),d.addEventListener("datachannel",function(t){e("ondatachannel",l,[t.channel.id,t.channel.label])});var u=function(){d.getStats(null).then(function(t){var r=function(e){if(!e.entries)return e;var t={};return e.forEach(function(e,r){t[r]=e}),t}(t),i=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach(function(r){var i=t[r];delete i.id,e[r]&&Object.keys(i).forEach(function(n){i[n]===e[r][n]&&delete t[r][n],(0===Object.keys(i).length||1===Object.keys(i).length&&i.timestamp)&&delete t[r]})});var r=-1/0;return Object.keys(t).forEach(function(e){var i=t[e];i.timestamp>r&&(r=i.timestamp)}),Object.keys(t).forEach(function(e){var i=t[e];i.timestamp===r&&(i.timestamp=0)}),t.timestamp=r,t}(o[l]||{},r)),o[l]=i})};if(!s&&t)var p=window.setInterval(function(){"closed"!==d.signalingState?u():window.clearInterval(p)},t);return s||d.addEventListener("connectionstatechange",function(){"connected"!==d.connectionState&&"failed"!==d.connectionState||u()}),d};["createDataChannel","close"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){return e(t,this.__rtcStatsId,arguments),r.apply(this,arguments)})}),["addStream","removeStream"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=i.getTracks().map(function(e){return e.kind+":"+e.id}).join(",");return e(t,this.__rtcStatsId,i.id+" "+n),r.apply(this,arguments)})}),["addTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0],n=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,i.kind+":"+i.id+" "+(n.map(function(e){return"stream:"+e.id}).join(";")||"-")),r.apply(this,arguments)})}),["removeTrack"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=arguments[0].track;return e(t,this.__rtcStatsId,i?i.kind+":"+i.id:"null"),r.apply(this,arguments)})}),["createOffer","createAnswer"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i,n=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?i=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(i=arguments[2]),e(t,this.__rtcStatsId,i),r.apply(this,i?[i]:void 0).then(function(r){if(e(t+"OnSuccess",n,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])},function(r){if(e(t+"OnFailure",n,r.toString()),!(s.length>1&&"function"==typeof s[1]))throw r;s[1].apply(null,[r])})})}),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var i=this.__rtcStatsId,n=arguments;return e(t,this.__rtcStatsId,n[0]),r.apply(this,[n[0]]).then(function(){e(t+"OnSuccess",i,void 0),n.length>=2&&"function"==typeof n[1]&&n[1].apply(null,[])},function(r){if(e(t+"OnFailure",i,r.toString()),!(n.length>=3&&"function"==typeof n[2]))throw r;n[2].apply(null,[r])})})}),a.generateCertificate&&Object.defineProperty(c,"generateCertificate",{get:function(){return arguments.length?a.generateCertificate.apply(null,arguments):a.generateCertificate}}),window[r+"RTCPeerConnection"]=c,window[r+"RTCPeerConnection"].prototype=a.prototype}}),r.forEach(function(t){var r=t+(t.length?"GetUserMedia":"getUserMedia");if(navigator[r]){var i=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];i(arguments[0],function(r){e("getUserMediaOnSuccess",null,ai(r)),t&&t(r)},function(t){e("getUserMediaOnFailure",null,t.name),r&&r(t)})}.bind(navigator)}}),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return e("navigator.mediaDevices.getUserMedia",null,arguments[0]),a.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getUserMediaOnSuccess",null,ai(t)),t},function(t){return e("navigator.mediaDevices.getUserMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var c=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return e("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),c.apply(navigator.mediaDevices,arguments).then(function(t){return e("navigator.mediaDevices.getDisplayMediaOnSuccess",null,ai(t)),t},function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)})}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},di=c(ci);let li;const ui=new Uint8Array(16);function pi(){if(!li&&(li="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!li))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return li(ui)}const hi=[];for(let xD=0;xD<256;++xD)hi.push((xD+256).toString(16).slice(1));var fi={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function mi(e,t,r){if(fi.randomUUID&&!e)return fi.randomUUID();const i=(e=e||{}).random||(e.rng||pi)();return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return hi[e[t+0]]+hi[e[t+1]]+hi[e[t+2]]+hi[e[t+3]]+"-"+hi[e[t+4]]+hi[e[t+5]]+"-"+hi[e[t+6]]+hi[e[t+7]]+"-"+hi[e[t+8]]+hi[e[t+9]]+"-"+hi[e[t+10]]+hi[e[t+11]]+hi[e[t+12]]+hi[e[t+13]]+hi[e[t+14]]+hi[e[t+15]]}(i)}var gi={},vi={},bi={exports:{}},yi=bi.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"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(e){return null!=e.subtype?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.maxMessageSize?"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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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(yi).forEach(function(e){yi[e].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})});var wi=bi.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,i){var n=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:n&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:n?r[e.name]:r;!function(e,r,i,n){if(n&&!i)r[n]=t(e[1]);else for(var s=0;s<i.length;s+=1)null!=e[s+1]&&(r[i[s]]=t(e[s+1]))}(i.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},i=wi,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(n).forEach(function(e){var t=e[0],n=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(i[t]||[]).length;a+=1){var c=i[t][a];if(c.reg.test(n))return r(c,o,n)}}),t.media=s,t};var s=function(e,r){var i=r.split(/=(.+)/,2);return 2===i.length?e[i[0]]=t(i[1]):1===i.length&&r.length>1&&(e[i[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var r=[],i=e.split(" ").map(t),n=0;n<i.length;n+=3)r.push({component:i[n],ip:i[n+1],port:i[n+2]});return r},e.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(e){return e.split(";").map(function(e){return e.split(",").map(function(e){var r,i=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),i=!0),{scid:r,paused:i}})})}}(vi);var _i=wi,Si=/%[sdv%]/g,Ci=function(e){var t=1,r=arguments,i=r.length;return e.replace(Si,function(e){if(t>=i)return e;var n=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Ri=function(e,t,r){var i=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var s=t.names[n];t.name?i.push(r[t.name][s]):i.push(r[t.names[n]])}else i.push(r[t.name]);return Ci.apply(null,i)},ki=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ti=["i","c","b","a"],Pi=vi,Oi=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var r=t.outerOrder||ki,i=t.innerOrder||Ti,n=[];return r.forEach(function(t){_i[t].forEach(function(r){r.name in e&&null!=e[r.name]?n.push(Ri(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){n.push(Ri(t,r,e))})})}),e.media.forEach(function(e){n.push(Ri("m",_i.m[0],e)),i.forEach(function(t){_i[t].forEach(function(r){r.name in e&&null!=e[r.name]?n.push(Ri(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach(function(e){n.push(Ri(t,r,e))})})})}),n.join("\r\n")+"\r\n"},Ei=wi;gi.grammar=Ei;var Di=gi.write=Oi,xi=gi.parse=Pi.parse;gi.parseParams=Pi.parseParams,gi.parseFmtpConfig=Pi.parseFmtpConfig,gi.parsePayloads=Pi.parsePayloads,gi.parseRemoteCandidates=Pi.parseRemoteCandidates,gi.parseImageAttributes=Pi.parseImageAttributes,gi.parseSimulcastStreamList=Pi.parseSimulcastStreamList;var Ii={},Mi={},ji={};Object.defineProperty(ji,"__esModule",{value:!0}),ji.isCorrect=ji.isInSubnet=void 0,ji.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},ji.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var Li={};Object.defineProperty(Li,"__esModule",{value:!0}),Li.RE_SUBNET_STRING=Li.RE_ADDRESS=Li.GROUPS=Li.BITS=void 0,Li.BITS=32,Li.GROUPS=4,Li.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,Li.RE_SUBNET_STRING=/\/\d{1,2}$/;var Ai={};Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.AddressError=void 0;class Ni extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}Ai.AddressError=Ni;var Bi,Fi={exports:{}};Bi=Fi,function(){var e;function t(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function r(){return new t(null)}var i="undefined"!=typeof navigator;i&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(var o=32767&t,a=t>>15;--s>=0;){var c=32767&this[e],d=this[e++]>>15,l=a*c+d*o;n=((c=o*c+((32767&l)<<15)+r[i]+(1073741823&n))>>>30)+(l>>>15)+a*d+(n>>>30),r[i++]=1073741823&c}return n},e=30):i&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,i,n,s){for(;--s>=0;){var o=t*this[e++]+r[i]+n;n=Math.floor(o/67108864),r[i++]=67108863&o}return n},e=26):(t.prototype.am=function(e,t,r,i,n,s){for(var o=16383&t,a=t>>14;--s>=0;){var c=16383&this[e],d=this[e++]>>14,l=a*c+d*o;n=((c=o*c+((16383&l)<<14)+r[i]+n)>>28)+(l>>14)+a*d,r[i++]=268435455&c}return n},e=28),t.prototype.DB=e,t.prototype.DM=(1<<e)-1,t.prototype.DV=1<<e,t.prototype.FV=Math.pow(2,52),t.prototype.F1=52-e,t.prototype.F2=2*e-52;var n,s,o=new Array;for(n="0".charCodeAt(0),s=0;s<=9;++s)o[n++]=s;for(n="a".charCodeAt(0),s=10;s<36;++s)o[n++]=s;for(n="A".charCodeAt(0),s=10;s<36;++s)o[n++]=s;function a(e){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(e)}function c(e,t){var r=o[e.charCodeAt(t)];return null==r?-1:r}function d(e){var t=r();return t.fromInt(e),t}function l(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function u(e){this.m=e}function p(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function h(e,t){return e&t}function f(e,t){return e|t}function m(e,t){return e^t}function g(e,t){return e&~t}function v(e){if(0==e)return-1;var t=0;return 65535&e||(e>>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function b(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function y(){}function w(e){return e}function _(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}u.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},u.prototype.revert=function(e){return e},u.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},u.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},u.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},p.prototype.convert=function(e){var i=r();return e.abs().dlShiftTo(this.m.t,i),i.divRemTo(this.m,null,i),e.s<0&&i.compareTo(t.ZERO)>0&&this.m.subTo(i,i),i},p.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},p.prototype.reduce=function(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t<this.m.t;++t){var r=32767&e[t],i=r*this.mpl+((r*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,i,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},p.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},p.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},t.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s},t.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0},t.prototype.fromString=function(e,r){var i;if(16==r)i=4;else if(8==r)i=3;else if(256==r)i=8;else if(2==r)i=1;else if(32==r)i=5;else{if(4!=r)return void this.fromRadix(e,r);i=2}this.t=0,this.s=0;for(var n=e.length,s=!1,o=0;--n>=0;){var a=8==i?255&e[n]:c(e,n);a<0?"-"==e.charAt(n)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+i>this.DB?(this[this.t-1]|=(a&(1<<this.DB-o)-1)<<o,this[this.t++]=a>>this.DB-o):this[this.t-1]|=a<<o,(o+=i)>=this.DB&&(o-=this.DB))}8==i&&128&e[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<<this.DB-o)-1<<o)),this.clamp(),s&&t.ZERO.subTo(this,this)},t.prototype.clamp=function(){for(var e=this.s&this.DM;this.t>0&&this[this.t-1]==e;)--this.t},t.prototype.dlShiftTo=function(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s},t.prototype.drShiftTo=function(e,t){for(var r=e;r<this.t;++r)t[r-e]=this[r];t.t=Math.max(this.t-e,0),t.s=this.s},t.prototype.lShiftTo=function(e,t){var r,i=e%this.DB,n=this.DB-i,s=(1<<n)-1,o=Math.floor(e/this.DB),a=this.s<<i&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>n|a,a=(this[r]&s)<<i;for(r=o-1;r>=0;--r)t[r]=0;t[o]=a,t.t=this.t+o+1,t.s=this.s,t.clamp()},t.prototype.rShiftTo=function(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var i=e%this.DB,n=this.DB-i,s=(1<<i)-1;t[0]=this[r]>>i;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<n,t[o-r]=this[o]>>i;i>0&&(t[this.t-r-1]|=(this.s&s)<<n),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]-e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i-=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i-=e[r],t[r++]=i&this.DM,i>>=this.DB;i-=e.s}t.s=i<0?-1:0,i<-1?t[r++]=this.DV+i:i>0&&(t[r++]=i),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var i=this.abs(),n=e.abs(),s=i.t;for(r.t=s+n.t;--s>=0;)r[s]=0;for(s=0;s<n.t;++s)r[s+i.t]=i.am(0,n[s],r,s,0,i.t);r.s=0,r.clamp(),this.s!=e.s&&t.ZERO.subTo(r,r)},t.prototype.squareTo=function(e){for(var t=this.abs(),r=e.t=2*t.t;--r>=0;)e[r]=0;for(r=0;r<t.t-1;++r){var i=t.am(r,t[r],e,2*r,0,1);(e[r+t.t]+=t.am(r+1,2*t[r],e,2*r+1,i,t.t-r-1))>=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()},t.prototype.divRemTo=function(e,i,n){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=i&&i.fromInt(0),void(null!=n&&this.copyTo(n));null==n&&(n=r());var a=r(),c=this.s,d=e.s,u=this.DB-l(s[s.t-1]);u>0?(s.lShiftTo(u,a),o.lShiftTo(u,n)):(s.copyTo(a),o.copyTo(n));var p=a.t,h=a[p-1];if(0!=h){var f=h*(1<<this.F1)+(p>1?a[p-2]>>this.F2:0),m=this.FV/f,g=(1<<this.F1)/f,v=1<<this.F2,b=n.t,y=b-p,w=null==i?r():i;for(a.dlShiftTo(y,w),n.compareTo(w)>=0&&(n[n.t++]=1,n.subTo(w,n)),t.ONE.dlShiftTo(p,w),w.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var _=n[--b]==h?this.DM:Math.floor(n[b]*m+(n[b-1]+v)*g);if((n[b]+=a.am(0,_,n,y,0,p))<_)for(a.dlShiftTo(y,w),n.subTo(w,n);n[b]<--_;)n.subTo(w,n)}null!=i&&(n.drShiftTo(p,i),c!=d&&t.ZERO.subTo(i,i)),n.t=p,n.clamp(),u>0&&n.rShiftTo(u,n),c<0&&t.ZERO.subTo(n,n)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},t.prototype.isEven=function(){return 0==(this.t>0?1&this[0]:this.s)},t.prototype.exp=function(e,i){if(e>4294967295||e<1)return t.ONE;var n=r(),s=r(),o=i.convert(this),a=l(e)-1;for(o.copyTo(n);--a>=0;)if(i.sqrTo(n,s),(e&1<<a)>0)i.mulTo(s,o,n);else{var c=n;n=s,s=c}return i.revert(n)},t.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,i=(1<<t)-1,n=!1,s="",o=this.t,c=this.DB-o*this.DB%t;if(o-- >0)for(c<this.DB&&(r=this[o]>>c)>0&&(n=!0,s=a(r));o>=0;)c<t?(r=(this[o]&(1<<c)-1)<<t-c,r|=this[--o]>>(c+=this.DB-t)):(r=this[o]>>(c-=t)&i,c<=0&&(c+=this.DB,--o)),r>0&&(n=!0),n&&(s+=a(r));return n?s:"0"},t.prototype.negate=function(){var e=r();return t.ZERO.subTo(this,e),e},t.prototype.abs=function(){return this.s<0?this.negate():this},t.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0},t.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+l(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var i=r();return this.abs().divRemTo(e,null,i),this.s<0&&i.compareTo(t.ZERO)>0&&e.subTo(i,i),i},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new u(t):new p(t),this.exp(e,r)},t.ZERO=d(0),t.ONE=d(1),y.prototype.convert=w,y.prototype.revert=w,y.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},y.prototype.sqrTo=function(e,t){e.squareTo(t)},_.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=r();return e.copyTo(t),this.reduce(t),t},_.prototype.revert=function(e){return e},_.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},_.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},_.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var S,C,R,k=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],T=(1<<26)/k[k.length-1];function P(){var e;e=(new Date).getTime(),C[R++]^=255&e,C[R++]^=e>>8&255,C[R++]^=e>>16&255,C[R++]^=e>>24&255,R>=j&&(R-=j)}if(t.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},t.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),i=Math.pow(e,t),n=d(i),s=r(),o=r(),a="";for(this.divRemTo(n,s,o);s.signum()>0;)a=(i+o.intValue()).toString(e).substr(1)+a,s.divRemTo(n,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var i=this.chunkSize(r),n=Math.pow(r,i),s=!1,o=0,a=0,d=0;d<e.length;++d){var l=c(e,d);l<0?"-"==e.charAt(d)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=i&&(this.dMultiply(n),this.dAddOffset(a,0),o=0,a=0))}o>0&&(this.dMultiply(Math.pow(r,o)),this.dAddOffset(a,0)),s&&t.ZERO.subTo(this,this)},t.prototype.fromNumber=function(e,r,i){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,i),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),f,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(r);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(t.ONE.shiftLeft(e-1),this);else{var n=new Array,s=7&e;n.length=1+(e>>3),r.nextBytes(n),s>0?n[0]&=(1<<s)-1:n[0]=0,this.fromString(n,256)}},t.prototype.bitwiseTo=function(e,t,r){var i,n,s=Math.min(e.t,this.t);for(i=0;i<s;++i)r[i]=t(this[i],e[i]);if(e.t<this.t){for(n=e.s&this.DM,i=s;i<this.t;++i)r[i]=t(this[i],n);r.t=this.t}else{for(n=this.s&this.DM,i=s;i<e.t;++i)r[i]=t(n,e[i]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var i=t.ONE.shiftLeft(e);return this.bitwiseTo(i,r,i),i},t.prototype.addTo=function(e,t){for(var r=0,i=0,n=Math.min(e.t,this.t);r<n;)i+=this[r]+e[r],t[r++]=i&this.DM,i>>=this.DB;if(e.t<this.t){for(i+=e.s;r<this.t;)i+=this[r],t[r++]=i&this.DM,i>>=this.DB;i+=this.s}else{for(i+=this.s;r<e.t;)i+=e[r],t[r++]=i&this.DM,i>>=this.DB;i+=e.s}t.s=i<0?-1:0,i>0?t[r++]=i:i<-1&&(t[r++]=this.DV+i),t.t=r,t.clamp()},t.prototype.dMultiply=function(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},t.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}},t.prototype.multiplyLowerTo=function(e,t,r){var i,n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r[--n]=0;for(i=r.t-this.t;n<i;++n)r[n+this.t]=this.am(0,e[n],r,n,0,this.t);for(i=Math.min(e.t,t);n<i;++n)this.am(0,e[n],r,n,0,t-n);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var i=r.t=this.t+e.t-t;for(r.s=0;--i>=0;)r[i]=0;for(i=Math.max(t-this.t,0);i<e.t;++i)r[this.t+i-t]=this.am(t-i,e[i],r,0,0,this.t+i-t);r.clamp(),r.drShiftTo(1,r)},t.prototype.modInt=function(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var i=this.t-1;i>=0;--i)r=(t*r+this[i])%e;return r},t.prototype.millerRabin=function(e){var i=this.subtract(t.ONE),n=i.getLowestSetBit();if(n<=0)return!1;var s=i.shiftRight(n);(e=e+1>>1)>k.length&&(e=k.length);for(var o=r(),a=0;a<e;++a){o.fromInt(k[Math.floor(Math.random()*k.length)]);var c=o.modPow(s,this);if(0!=c.compareTo(t.ONE)&&0!=c.compareTo(i)){for(var d=1;d++<n&&0!=c.compareTo(i);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(i))return!1}}return!0},t.prototype.clone=function(){var e=r();return this.copyTo(e),e},t.prototype.intValue=function(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]},t.prototype.byteValue=function(){return 0==this.t?this.s:this[0]<<24>>24},t.prototype.shortValue=function(){return 0==this.t?this.s:this[0]<<16>>16},t.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1},t.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var r,i=this.DB-e*this.DB%8,n=0;if(e-- >0)for(i<this.DB&&(r=this[e]>>i)!=(this.s&this.DM)>>i&&(t[n++]=r|this.s<<this.DB-i);e>=0;)i<8?(r=(this[e]&(1<<i)-1)<<8-i,r|=this[--e]>>(i+=this.DB-8)):(r=this[e]>>(i-=8)&255,i<=0&&(i+=this.DB,--e)),128&r&&(r|=-256),0==n&&(128&this.s)!=(128&r)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t},t.prototype.equals=function(e){return 0==this.compareTo(e)},t.prototype.min=function(e){return this.compareTo(e)<0?this:e},t.prototype.max=function(e){return this.compareTo(e)>0?this:e},t.prototype.and=function(e){var t=r();return this.bitwiseTo(e,h,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,f,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.not=function(){for(var e=r(),t=0;t<this.t;++t)e[t]=this.DM&~this[t];return e.t=this.t,e.s=~this.s,e},t.prototype.shiftLeft=function(e){var t=r();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t},t.prototype.shiftRight=function(e){var t=r();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t},t.prototype.getLowestSetBit=function(){for(var e=0;e<this.t;++e)if(0!=this[e])return e*this.DB+v(this[e]);return this.s<0?this.t*this.DB:-1},t.prototype.bitCount=function(){for(var e=0,t=this.s&this.DM,r=0;r<this.t;++r)e+=b(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:!!(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,f)},t.prototype.clearBit=function(e){return this.changeBit(e,g)},t.prototype.flipBit=function(e){return this.changeBit(e,m)},t.prototype.add=function(e){var t=r();return this.addTo(e,t),t},t.prototype.subtract=function(e){var t=r();return this.subTo(e,t),t},t.prototype.multiply=function(e){var t=r();return this.multiplyTo(e,t),t},t.prototype.divide=function(e){var t=r();return this.divRemTo(e,t,null),t},t.prototype.remainder=function(e){var t=r();return this.divRemTo(e,null,t),t},t.prototype.divideAndRemainder=function(e){var t=r(),i=r();return this.divRemTo(e,t,i),new Array(t,i)},t.prototype.modPow=function(e,t){var i,n,s=e.bitLength(),o=d(1);if(s<=0)return o;i=s<18?1:s<48?3:s<144?4:s<768?5:6,n=s<8?new u(t):t.isEven()?new _(t):new p(t);var a=new Array,c=3,h=i-1,f=(1<<i)-1;if(a[1]=n.convert(this),i>1){var m=r();for(n.sqrTo(a[1],m);c<=f;)a[c]=r(),n.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,w=r();for(s=l(e[b])-1;b>=0;){for(s>=h?g=e[b]>>s-h&f:(g=(e[b]&(1<<s+1)-1)<<h-s,b>0&&(g|=e[b-1]>>this.DB+s-h)),c=i;!(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)n.sqrTo(o,w),n.sqrTo(w,o),c-=2;c>0?n.sqrTo(o,w):(v=o,o=w,w=v),n.mulTo(w,a[g],o)}for(;b>=0&&!(e[b]&1<<s);)n.sqrTo(o,w),v=o,o=w,w=v,--s<0&&(s=this.DB-1,--b)}return n.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var i=e.clone(),n=this.clone(),s=d(1),o=d(0),a=d(0),c=d(1);0!=i.signum();){for(;i.isEven();)i.rShiftTo(1,i),r?(s.isEven()&&o.isEven()||(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),r?(a.isEven()&&c.isEven()||(a.addTo(this,a),c.subTo(e,c)),a.rShiftTo(1,a)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);i.compareTo(n)>=0?(i.subTo(n,i),r&&s.subTo(a,s),o.subTo(c,o)):(n.subTo(i,n),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=n.compareTo(t.ONE)?t.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c},t.prototype.pow=function(e){return this.exp(e,new y)},t.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),r=e.s<0?e.negate():e.clone();if(t.compareTo(r)<0){var i=t;t=r,r=i}var n=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(n<s&&(s=n),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=r.getLowestSetBit())>0&&r.rShiftTo(n,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return s>0&&r.lShiftTo(s,r),r},t.prototype.isProbablePrime=function(e){var t,r=this.abs();if(1==r.t&&r[0]<=k[k.length-1]){for(t=0;t<k.length;++t)if(r[0]==k[t])return!0;return!1}if(r.isEven())return!1;for(t=1;t<k.length;){for(var i=k[t],n=t+1;n<k.length&&i<T;)i*=k[n++];for(i=r.modInt(i);t<n;)if(i%k[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=_,null==C){var O;if(C=new Array,R=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var E=new Uint8Array(32);for(window.crypto.getRandomValues(E),O=0;O<32;++O)C[R++]=E[O]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var D=window.crypto.random(32);for(O=0;O<D.length;++O)C[R++]=255&D.charCodeAt(O)}for(;R<j;)O=Math.floor(65536*Math.random()),C[R++]=O>>>8,C[R++]=255&O;R=0,P()}function x(){if(null==S){for(P(),(S=new M).init(C),R=0;R<C.length;++R)C[R]=0;R=0}return S.next()}function I(){}function M(){this.i=0,this.j=0,this.S=new Array}I.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=x()},M.prototype.init=function(e){var t,r,i;for(t=0;t<256;++t)this.S[t]=t;for(r=0,t=0;t<256;++t)r=r+this.S[t]+e[t%e.length]&255,i=this.S[t],this.S[t]=this.S[r],this.S[r]=i;this.i=0,this.j=0},M.prototype.next=function(){var e;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,e=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=e,this.S[e+this.S[this.i]&255]};var j=256;Bi.exports={default:t,BigInteger:t,SecureRandom:I}}.call(a);var zi=Fi.exports,Vi={};!function(e){!function(){var t={not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function r(e){return function(e,i){var n,s,o,a,c,d,l,u,p,h=1,f=e.length,m="";for(s=0;s<f;s++)if("string"==typeof e[s])m+=e[s];else if("object"==typeof e[s]){if((a=e[s]).keys)for(n=i[h],o=0;o<a.keys.length;o++){if(null==n)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));n=n[a.keys[o]]}else n=a.param_no?i[a.param_no]:i[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&n instanceof Function&&(n=n()),t.numeric_arg.test(a.type)&&"number"!=typeof n&&isNaN(n))throw new TypeError(r("[sprintf] expecting number but found %T",n));switch(t.number.test(a.type)&&(u=n>=0),a.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,a.width?parseInt(a.width):0);break;case"e":n=a.precision?parseFloat(n).toExponential(a.precision):parseFloat(n).toExponential();break;case"f":n=a.precision?parseFloat(n).toFixed(a.precision):parseFloat(n);break;case"g":n=a.precision?String(Number(n.toPrecision(a.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=a.precision?n.substring(0,a.precision):n;break;case"t":n=String(!!n),n=a.precision?n.substring(0,a.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=a.precision?n.substring(0,a.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=a.precision?n.substring(0,a.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=n:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",n=n.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+n).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+n+c:"0"===d?p+c+n:c+p+n)}return m}(function(e){if(n[e])return n[e];var r,i=e,s=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))s.push(r[0]);else if(null!==(r=t.modulo.exec(i)))s.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var a=[],c=r[2],d=[];if(null===(d=t.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(d[1]);""!==(c=c.substring(d[0].length));)if(null!==(d=t.key_access.exec(c)))a.push(d[1]);else{if(null===(d=t.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(d[1])}r[2]=a}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");s.push({placeholder:r[0],param_no:r[1],keys:r[2],sign:r[3],pad_char:r[4],align:r[5],width:r[6],precision:r[7],type:r[8]})}i=i.substring(r[0].length)}return n[e]=s}(e),arguments)}function i(e,t){return r.apply(null,[e].concat(t||[]))}var n=Object.create(null);e.sprintf=r,e.vsprintf=i,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=i)}()}(Vi);var Ui=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),$i=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Gi=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&Ui(t,e,r);return $i(t,e),t};Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.Address4=void 0;const qi=Gi(ji),Hi=Gi(Li),Wi=Ai,Ki=zi,Ji=Vi;class Qi{constructor(e){this.groups=Hi.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=qi.isCorrect(Hi.BITS),this.isInSubnet=qi.isInSubnet,this.address=e;const t=Hi.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>Hi.BITS)throw new Wi.AddressError("Invalid subnet mask.");e=e.replace(Hi.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new Qi(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Hi.RE_ADDRESS))throw new Wi.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let i;for(i=0;i<8;i+=2){const e=t.slice(i,i+2);r.push(parseInt(e,16))}return new Qi(r.join("."))}static fromInteger(e){return Qi.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new Qi(t)}toHex(){return this.parsedAddress.map(e=>(0,Ji.sprintf)("%02x",parseInt(e,10))).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){const e=[];let t;for(t=0;t<Hi.GROUPS;t+=2){const r=(0,Ji.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,Ji.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Ki.BigInteger(this.parsedAddress.map(e=>(0,Ji.sprintf)("%02x",parseInt(e,10))).join(""),16)}_startAddress(){return new Ki.BigInteger(this.mask()+"0".repeat(Hi.BITS-this.subnetMask),2)}startAddress(){return Qi.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Ki.BigInteger("1");return Qi.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Ki.BigInteger(this.mask()+"1".repeat(Hi.BITS-this.subnetMask),2)}endAddress(){return Qi.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Ki.BigInteger("1");return Qi.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return Qi.fromInteger(parseInt(e.toString(),10))}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:(0,Ji.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new Qi("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Hi.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Hi.RE_ADDRESS,(0,Ji.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>',e.slice(0,2).join("."),e.slice(2,4).join(".")))}}Mi.Address4=Qi;var Xi={},Yi={};Object.defineProperty(Yi,"__esModule",{value:!0}),Yi.RE_URL_WITH_PORT=Yi.RE_URL=Yi.RE_ZONE_STRING=Yi.RE_SUBNET_STRING=Yi.RE_BAD_ADDRESS=Yi.RE_BAD_CHARACTERS=Yi.TYPES=Yi.SCOPES=Yi.GROUPS=Yi.BITS=void 0,Yi.BITS=128,Yi.GROUPS=8,Yi.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},Yi.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},Yi.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,Yi.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,Yi.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,Yi.RE_ZONE_STRING=/%.*$/,Yi.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),Yi.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.simpleGroup=Zi.spanLeadingZeroes=Zi.spanAll=Zi.spanAllZeroes=void 0;const en=Vi;function tn(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function rn(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}Zi.spanAllZeroes=tn,Zi.spanAll=function(e,t=0){return e.split("").map((e,r)=>(0,en.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,tn(e))).join("")},Zi.spanLeadingZeroes=function(e){return e.split(":").map(e=>rn(e)).join(":")},Zi.simpleGroup=function(e,t=0){return e.split(":").map((e,r)=>/group-v4/.test(e)?e:(0,en.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,rn(e)))};var nn={},sn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),on=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),an=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&sn(t,e,r);return on(t,e),t};Object.defineProperty(nn,"__esModule",{value:!0}),nn.possibleElisions=nn.simpleRegularExpression=nn.ADDRESS_BOUNDARY=nn.padGroup=nn.groupPossibilities=void 0;const cn=an(Yi),dn=Vi;function ln(e){return(0,dn.sprintf)("(%s)",e.join("|"))}function un(e){return e.length<4?(0,dn.sprintf)("0{0,%d}%s",4-e.length,e):e}nn.groupPossibilities=ln,nn.padGroup=un,nn.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",nn.simpleRegularExpression=function(e){const t=[];e.forEach((e,r)=>{0===parseInt(e,16)&&t.push(r)});const r=t.map(t=>e.map((e,r)=>{if(r===t){const t=0===r||r===cn.GROUPS-1?":":"";return ln([un(e),t])}return un(e)}).join(":"));return r.push(e.map(un).join(":")),ln(r)},nn.possibleElisions=function(e,t,r){const i=t?"":":",n=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,dn.sprintf)("%s(:0{1,4}){1,%d}",i,e-1)),s.push((0,dn.sprintf)("(0{1,4}:){1,%d}%s",e-1,n)),s.push((0,dn.sprintf)("(0{1,4}:){%d}0{1,4}",e-1));for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)s.push((0,dn.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return ln(s)};var pn=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),hn=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fn=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&pn(t,e,r);return hn(t,e),t};Object.defineProperty(Xi,"__esModule",{value:!0}),Xi.Address6=void 0;const mn=fn(ji),gn=fn(Li),vn=fn(Yi),bn=fn(Zi),yn=Mi,wn=nn,_n=Ai,Sn=zi,Cn=Vi;function Rn(e){if(!e)throw new Error("Assertion failed.")}function kn(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function Tn(e){return(0,Cn.sprintf)("%04x",parseInt(e,16))}function Pn(e){return 255&e}class On{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=mn.isInSubnet,this.isCorrect=mn.isCorrect(vn.BITS),this.groups=void 0===t?vn.GROUPS:t,this.address=e;const r=vn.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>vn.BITS)throw new _n.AddressError("Invalid subnet mask.");e=e.replace(vn.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new _n.AddressError("Invalid subnet mask.");const i=vn.RE_ZONE_STRING.exec(e);i&&(this.zone=i[0],e=e.replace(vn.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new On(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let i;for(i=0;i<vn.GROUPS;i++)r.push(t.slice(4*i,4*(i+1)));return new On(r.join(":"))}static fromURL(e){let t,r,i=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=vn.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],i=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=vn.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return i?(i=parseInt(i,10),(i<0||i>65536)&&(i=null)):i=null,{address:new On(t),port:i}}static fromAddress4(e){const t=new yn.Address4(e),r=vn.BITS-(gn.BITS-t.subnetMask);return new On(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new _n.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new On(t)}microsoftTranscription(){return(0,Cn.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=vn.BITS-this.subnetMask-Math.abs(e-vn.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}(new Sn.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new Sn.BigInteger(this.mask()+"0".repeat(vn.BITS-this.subnetMask),2)}startAddress(){return On.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Sn.BigInteger("1");return On.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Sn.BigInteger(this.mask()+"1".repeat(vn.BITS-this.subnetMask),2)}endAddress(){return On.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Sn.BigInteger("1");return On.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=vn.SCOPES[this.getBits(12,16).intValue()];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(vn.TYPES))if(this.isInSubnet(new On(e)))return vn.TYPES[e];return"Global unicast"}getBits(e,t){return new Sn.BigInteger(this.getBitsBase2(e,t),2)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,vn.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:(0,Cn.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const i=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&i.push([e-r,e-1]),r=0)}r>1&&i.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const n=i.map(e=>e[1]-e[0]+1);if(i.length>0){const e=n.indexOf(Math.max(...n));t=function(e,t){const r=[],i=[];let n;for(n=0;n<e.length;n++)n<t[0]?r.push(e[n]):n>t[1]&&i.push(e[n]);return r.concat(["compact"]).concat(i)}(this.parsedAddress,i[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let s=t.join(":");return s=s.replace(/^compact$/,"::"),s=s.replace(/^compact|compact$/,":"),s=s.replace(/compact/,""),s}binaryZeroPad(){return this.bigInteger().toString(2).padStart(vn.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(gn.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new yn.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new _n.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(gn.RE_ADDRESS,this.address4.parsedAddress.map(kn).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(vn.RE_BAD_CHARACTERS);if(t)throw new _n.AddressError((0,Cn.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(vn.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(vn.RE_BAD_ADDRESS);if(r)throw new _n.AddressError((0,Cn.sprintf)("Address failed regex: %s",r.join("")),e.replace(vn.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let i=[];const n=e.split("::");if(2===n.length){let e=n[0].split(":"),t=n[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new _n.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,i=i.concat(e);for(let e=0;e<r;e++)i.push("0");i=i.concat(t)}else{if(1!==n.length)throw new _n.AddressError("Too many :: groups found");i=e.split(":"),this.elidedGroups=0}if(i=i.map(e=>(0,Cn.sprintf)("%x",parseInt(e,16))),i.length!==this.groups)throw new _n.AddressError("Incorrect number of groups found");return i}canonicalForm(){return this.parsedAddress.map(Tn).join(":")}decimal(){return this.parsedAddress.map(e=>(0,Cn.sprintf)("%05d",parseInt(e,16))).join(":")}bigInteger(){return new Sn.BigInteger(this.parsedAddress.map(Tn).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return yn.Address4.fromHex(new Sn.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new On(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=this.getBits(80,96).xor(new Sn.BigInteger("ffff",16)).toString(),r=yn.Address4.fromHex(this.getBitsBase16(32,64)),i=yn.Address4.fromHex(this.getBits(96,128).xor(new Sn.BigInteger("ffffffff",16)).toString(16)),n=this.getBits(64,80),s=this.getBitsBase2(64,80),o=n.testBit(15),a=n.testBit(14),c=n.testBit(8),d=n.testBit(9),l=new Sn.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Cn.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:i.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=yn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Cn.sprintf)("%s",e.slice(0,4)),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new On(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(Pn)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(Pn))}static fromUnsignedByteArray(e){const t=new Sn.BigInteger("256",10);let r=new Sn.BigInteger("0",10),i=new Sn.BigInteger("1",10);for(let n=e.length-1;n>=0;n--)r=r.add(i.multiply(new Sn.BigInteger(e[n].toString(10),10))),i=i.multiply(t);return On.fromBigInteger(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new On("2001::/32"))}is6to4(){return this.isInSubnet(new On("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Cn.sprintf)(":%s",e),(0,Cn.sprintf)("http://[%s]%s/",this.correctForm(),e)}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;return e.v4&&(t=this.to4in6),e.className?(0,Cn.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Cn.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return bn.simpleGroup(this.address).join(":");Rn("number"==typeof this.elidedGroups),Rn("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...bn.simpleGroup(t)):e.push("");const i=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)i.push((0,Cn.sprintf)("group-%d",e));return e.push((0,Cn.sprintf)('<span class="%s"></span>',i.join(" "))),r.length?e.push(...bn.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Rn(this.address4 instanceof yn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new On(this.correctForm());if(0===r.elidedGroups)t.push((0,wn.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===vn.GROUPS)t.push((0,wn.possibleElisions)(vn.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,wn.simpleRegularExpression)(e[0].split(":"))),Rn("number"==typeof r.elidedGroups),t.push((0,wn.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,wn.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",wn.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",wn.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}Xi.Address6=On,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var i={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&t(i,e,n);return r(i,e),i};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const n=Mi;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return n.Address4}});const s=Xi;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=Ai;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=i(Zi);e.v6={helpers:c}}(Ii);var En={exports:{}};!function(e){(function(){var t,r,i,n,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,i){var n,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(n=0;i>0;){if((s=r-i)<0&&(s=0),e[n]>>s!==t[n]>>s)return!1;i-=r,n+=1}return!0},r.subnetMatch=function(e,t,r){var i,n,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),i=0,n=o.length;i<n;i++)if(a=o[i],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,i;if(4!==e.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,r=e.length;t<r;t++)if(!(0<=(i=e[t])&&i<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=e}return e.prototype.kind=function(){return"ipv4"},e.prototype.toString=function(){return this.octets.join(".")},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv4"!==e.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,e.octets,8,t)},e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.toIPv4MappedAddress=function(){return r.IPv6.parse("::ffff:"+this.toString())},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,n=!1,t=r=3;r>=0;t=r+=-1){if(!((i=this.octets[t])in o))return null;if(s=o[i],n&&0!==s)return null;8!==s&&(n=!0),e+=s}return 32-e},e}(),i="(0?\\d+|0x[a-f0-9]+)",n={fourOctet:new RegExp("^"+i+"\\."+i+"\\."+i+"\\."+i+"$","i"),longValue:new RegExp("^"+i+"$","i")},r.IPv4.parser=function(e){var t,r,i,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(n.fourOctet))return function(){var e,n,s,o;for(o=[],e=0,n=(s=t.slice(1,6)).length;e<n;e++)i=s[e],o.push(r(i));return o}();if(t=e.match(n.longValue)){if((o=r(t[1]))>4294967295||o<0)throw new Error("ipaddr: address outside defined range");return function(){var e,t;for(t=[],s=e=0;e<=24;s=e+=8)t.push(o>>s&255);return t}().reverse()}return null},r.IPv6=function(){function e(e,t){var r,i,n,s,o,a;if(16===e.length)for(this.parts=[],r=i=0;i<=14;r=i+=2)this.parts.push(e[r]<<8|e[r+1]);else{if(8!==e.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=e}for(n=0,s=(a=this.parts).length;n<s;n++)if(!(0<=(o=a[n])&&o<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return e.prototype.kind=function(){return"ipv6"},e.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},e.prototype.toRFC5952String=function(){var e,t,r,i,n;for(i=/((^|:)(0(:|$)){2,})/g,n=this.toNormalizedString(),e=0,t=-1;r=i.exec(n);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?n:n.substring(0,e)+"::"+n.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,i,n;for(e=[],t=0,r=(n=this.parts).length;t<r;t++)i=n[t],e.push(i>>8),e.push(255&i);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.toFixedLengthString=function(){var e,t,r;return e=function(){var e,r,i,n;for(n=[],e=0,r=(i=this.parts).length;e<r;e++)t=i[e],n.push(t.toString(16).padStart(4,"0"));return n}.call(this).join(":"),r="",this.zoneId&&(r="%"+this.zoneId),e+r},e.prototype.match=function(e,t){var r;if(void 0===t&&(e=(r=e)[0],t=r[1]),"ipv6"!==e.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,e.parts,16,t)},e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[new e([100,65435,0,0,0,0,0,0]),96],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],reserved:[[new e([8193,3512,0,0,0,0,0,0]),32]]},e.prototype.range=function(){return r.subnetMatch(this,this.SpecialRanges)},e.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},e.prototype.toIPv4Address=function(){var e,t,i;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(i=this.parts.slice(-2))[0],t=i[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,i,n,s,o;for(o={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},e=0,n=!1,t=r=7;r>=0;t=r+=-1){if(!((i=this.parts[t])in o))return null;if(s=o[i],n&&0!==s)return null;16!==s&&(n=!0),e+=s}return 128-e},e}(),s="(?:[0-9a-f]+::?)+",c="%[0-9a-z]{1,}",o={zoneIndex:new RegExp(c,"i"),native:new RegExp("^(::)?("+s+")?([0-9a-f]+)?(::)?("+c+")?$","i"),transitional:new RegExp("^((?:"+s+")|(?:::)(?:"+s+")?)"+i+"\\."+i+"\\."+i+"\\."+i+"("+c+")?$","i")},t=function(e,t){var r,i,n,s,a,c;if(e.indexOf("::")!==e.lastIndexOf("::"))return null;for((c=(e.match(o.zoneIndex)||[])[0])&&(c=c.substring(1),e=e.replace(/%.+$/,"")),r=0,i=-1;(i=e.indexOf(":",i+1))>=0;)r++;if("::"===e.substr(0,2)&&r--,"::"===e.substr(-2,2)&&r--,r>t)return null;for(a=t-r,s=":";a--;)s+="0:";return":"===(e=e.replace("::",s))[0]&&(e=e.slice(1)),":"===e[e.length-1]&&(e=e.slice(0,-1)),{parts:t=function(){var t,r,i,s;for(s=[],t=0,r=(i=e.split(":")).length;t<r;t++)n=i[t],s.push(parseInt(n,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,i,n,s,a,c,d;if(o.native.test(e))return t(e,8);if((s=e.match(o.transitional))&&(d=s[6]||"",(r=t(s[1].slice(0,-1)+d,6)).parts)){for(i=0,n=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;i<n;i++)if(!(0<=(a=c[i])&&a<=255))return null;return r.parts.push(c[0]<<8|c[1]),r.parts.push(c[2]<<8|c[3]),{parts:r.parts,zoneId:r.zoneId}}return null},r.IPv4.isIPv4=r.IPv6.isIPv6=function(e){return null!==this.parser(e)},r.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch(e){return!1}},r.IPv4.isValidFourPartDecimal=function(e){return!(!r.IPv4.isValid(e)||!e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},r.IPv6.isValid=function(e){var t;if("string"==typeof e&&-1===e.indexOf(":"))return!1;try{return new this((t=this.parser(e)).parts,t.zoneId),!0}catch(e){return!1}},r.IPv4.parse=function(e){var t;if(null===(t=this.parser(e)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},r.IPv6.parse=function(e){var t;if(null===(t=this.parser(e)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},r.IPv4.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,i;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(i=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)i[r]=255,r++;return t<4&&(i[t]=Math.pow(2,e%8)-1<<8-e%8),new this(i)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)|255^parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,i,n,s;try{for(i=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),n=[],r=0;r<4;)n.push(parseInt(i[r],10)&parseInt(s[r],10)),r++;return new this(n)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,i;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return i=[this.parse(r[1]),t],Object.defineProperty(i,"toString",{value:function(){return this.join("/")}}),i;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},r.isValid=function(e){return r.IPv6.isValid(e)||r.IPv4.isValid(e)},r.parse=function(e){if(r.IPv6.isValid(e))return r.IPv6.parse(e);if(r.IPv4.isValid(e))return r.IPv4.parse(e);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},r.parseCIDR=function(e){try{return r.IPv6.parseCIDR(e)}catch(t){try{return r.IPv4.parseCIDR(e)}catch(e){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},r.fromByteArray=function(e){var t;if(4===(t=e.length))return new r.IPv4(e);if(16===t)return new r.IPv6(e);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},r.process=function(e){var t;return"ipv6"===(t=this.parse(e)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(a)}(En);var Dn=En.exports,xn=function(e,t){if("string"==typeof t)return In(e,t);if("object"==typeof t){for(var r=!1,i=0;i<t.length;i++)if(In(e,t[i])){r=!0;break}return r}};function In(e,t){try{var r=Dn.process(e);if(-1===t.indexOf("/")){var i=Dn.process(t);return"ipv6"===r.kind()&&"ipv6"===i.kind()?r.toNormalizedString()===i.toNormalizedString():r.toString()==i.toString()}var n=Dn.parseCIDR(t);return r.match(n)}catch(e){return!1}}var Mn=xn,jn=/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,Ln=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.2.0/24","192.168.0.0/16","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","224.0.0.0/3"],An=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var Nn=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(jn.test(e)){r.isValid=!0;for(var i=e.split("."),n=0;n<4;n++)t.push(parseInt(i[n],10));r.boiledIp=t.join("."),Mn(r.boiledIp,Ln)&&(r.isBogon=!0),Mn(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),Mn(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),Mn(r.boiledIp,An)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},Bn=c(Nn),Fn={exports:{}},zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Vn=[],Un=0;Un<256;Un++)Vn[Un]=(Un+256).toString(16).substr(1);Fn.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e){var t=0,r=Vn;return r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+"-"+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]+r[e[t++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!zn.test(r))return!1;if(void 0===t)t=qn(r);else if(qn(r)!==t)return!1;switch(t){case 1:case 2:return!0;case 3:case 4:case 5:return-1!==["8","9","a","b"].indexOf(r.charAt(19));default:throw new Error("Invalid version provided.")}};var $n,Gn,qn=Fn.exports.version=function(e){return 0|e.charAt(14)},Hn=c(Fn.exports),Wn={},Kn={exports:{}};function Jn(){if(Gn)return $n;Gn=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,s=365.25*i;function o(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return $n=function(a,c){c=c||{};var d=typeof a;if("string"===d&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===d&&isFinite(a))return c.long?function(n){var s=Math.abs(n);if(s>=i)return o(n,s,i,"day");if(s>=r)return o(n,s,r,"hour");if(s>=t)return o(n,s,t,"minute");if(s>=e)return o(n,s,e,"second");return n+" ms"}(a):function(n){var s=Math.abs(n);if(s>=i)return Math.round(n/i)+"d";if(s>=r)return Math.round(n/r)+"h";if(s>=t)return Math.round(n/t)+"m";if(s>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},$n}var Qn=function(e){function t(e){let i,n,s,o=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),s=n-(i||n);r.diff=s,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,n)=>{if("%%"===i)return"%";o++;const s=t.formatters[n];if("function"==typeof s){const t=e[o];i=s.call(r,t),e.splice(o,1),o--}return i}),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==t.namespaces&&(n=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e,t){let r=0,i=0,n=-1,s=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(n=i,s=r,i++):(r++,i++);else{if(-1===n)return!1;i=n+1,s++,r=s}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=Jn(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))}),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=Qn(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Kn,Kn.exports);var Xn=Kn.exports,Yn={},Zn={exports:{}};!function(e,t){!function(r,i){var n,s="user-agent",o="",a="function",c="undefined",d="object",l="string",u="browser",p="cpu",h="device",f="engine",m="os",g="result",v="name",b="type",y="vendor",w="version",_="architecture",S="major",C="model",R="console",k="mobile",T="tablet",P="smarttv",O="wearable",E="xr",D="embedded",x="inapp",I="brands",M="formFactors",j="fullVersionList",L="platform",A="platformVersion",N="bitness",B="sec-ch-ua",F=B+"-full-version-list",z=B+"-arch",V=B+"-"+N,U=B+"-form-factors",$=B+"-"+k,G=B+"-"+C,q=B+"-"+L,H=q+"-version",W=[I,j,k,C,L,A,_,M,N],K="Amazon",J="Apple",Q="ASUS",X="BlackBerry",Y="Google",Z="Huawei",ee="Lenovo",te="Honor",re="LG",ie="Microsoft",ne="Motorola",se="Nvidia",oe="OnePlus",ae="OPPO",ce="Samsung",de="Sharp",le="Sony",ue="Xiaomi",pe="Zebra",he="Chrome",fe="Chromium",me="Chromecast",ge="Edge",ve="Firefox",be="Opera",ye="Facebook",we="Sogou",_e="Mobile ",Se=" Browser",Ce="Windows",Re=typeof r!==c,ke=Re&&r.navigator?r.navigator:i,Te=ke&&ke.userAgentData?ke.userAgentData:i,Pe=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},Oe=function(e,t){if(typeof e===d&&e.length>0){for(var r in e)if(Ie(t)==Ie(e[r]))return!0;return!1}return!!De(e)&&Ie(t)==Ie(e)},Ee=function(e,t){for(var r in e)return/^(browser|cpu|device|engine|os)$/.test(r)||!!t&&Ee(e[r])},De=function(e){return typeof e===l},xe=function(e){if(!e)return i;for(var t=[],r=Le(/\\?\"/g,e).split(","),n=0;n<r.length;n++)if(r[n].indexOf(";")>-1){var s=Ne(r[n]).split(";v=");t[n]={brand:s[0],version:s[1]}}else t[n]=Ne(r[n]);return t},Ie=function(e){return De(e)?e.toLowerCase():e},Me=function(e){return De(e)?Le(/[^\d\.]/g,e).split(".")[0]:i},je=function(e){for(var t in e){var r=e[t];typeof r==d&&2==r.length?this[r[0]]=r[1]:this[r]=i}return this},Le=function(e,t){return De(t)?t.replace(e,o):t},Ae=function(e){return Le(/\\?\"/g,e)},Ne=function(e,t){if(De(e))return e=Le(/^\s\s*/,e),typeof t===c?e:e.substring(0,500)},Be=function(e,t){if(e&&t)for(var r,n,s,o,c,l,u=0;u<t.length&&!c;){var p=t[u],h=t[u+1];for(r=n=0;r<p.length&&!c&&p[r];)if(c=p[r++].exec(e))for(s=0;s<h.length;s++)l=c[++n],typeof(o=h[s])===d&&o.length>0?2===o.length?typeof o[1]==a?this[o[0]]=o[1].call(this,l):this[o[0]]=o[1]:o.length>=3&&(typeof o[1]!==a||o[1].exec&&o[1].test?3==o.length?this[o[0]]=l?l.replace(o[1],o[2]):i:4==o.length?this[o[0]]=l?o[3].call(this,l.replace(o[1],o[2])):i:o.length>4&&(this[o[0]]=l?o[3].apply(this,[l.replace(o[1],o[2])].concat(o.slice(4))):i):o.length>3?this[o[0]]=l?o[1].apply(this,o.slice(2)):i:this[o[0]]=l?o[1].call(this,l,o[2]):i):this[o]=l||i;u+=2}},Fe=function(e,t){for(var r in t)if(typeof t[r]===d&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(Oe(t[r][n],e))return"?"===r?i:r}else if(Oe(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},ze={ME:"4.90","NT 3.51":"3.51","NT 4.0":"4.0",2e3:["5.0","5.01"],XP:["5.1","5.2"],Vista:"6.0",7:"6.1",8:"6.2",8.1:"6.3",10:["6.4","10.0"],NT:""},Ve={embedded:"Automotive",mobile:"Mobile",tablet:["Tablet","EInk"],smarttv:"TV",wearable:"Watch",xr:["VR","XR"],"?":["Desktop","Unknown"],"*":i},Ue={Chrome:"Google Chrome",Edge:"Microsoft Edge","Edge WebView2":"Microsoft Edge WebView2","Chrome WebView":"Android WebView","Chrome Headless":"HeadlessChrome","Huawei Browser":"HuaweiBrowser","MIUI Browser":"Miui Browser","Opera Mobi":"OperaMobile",Yandex:"YaBrowser"},$e={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[w,[v,_e+"Chrome"]],[/webview.+edge\/([\w\.]+)/i],[w,[v,ge+" WebView"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[w,[v,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[v,w],[/opios[\/ ]+([\w\.]+)/i],[w,[v,be+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[w,[v,be+" GX"]],[/\bopr\/([\w\.]+)/i],[w,[v,be]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[w,[v,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[w,[v,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon|otter|dooble|(?:lg |qute)browser)\/([-\w\.]+)/i,/(heytap|ovi|115|surf)browser\/([\d\.]+)/i,/(ecosia|weibo)(?:__| \w+@)([\d\.]+)/i],[v,w],[/quark(?:pc)?\/([-\w\.]+)/i],[w,[v,"Quark"]],[/\bddg\/([\w\.]+)/i],[w,[v,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[w,[v,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[w,[v,"WeChat"]],[/konqueror\/([\w\.]+)/i],[w,[v,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[w,[v,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[w,[v,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[w,[v,"Smart "+ee+Se]],[/(avast|avg)\/([\w\.]+)/i],[[v,/(.+)/,"$1 Secure"+Se],w],[/\bfocus\/([\w\.]+)/i],[w,[v,ve+" Focus"]],[/\bopt\/([\w\.]+)/i],[w,[v,be+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[w,[v,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[w,[v,"Dolphin"]],[/coast\/([\w\.]+)/i],[w,[v,be+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[w,[v,"MIUI"+Se]],[/fxios\/([\w\.-]+)/i],[w,[v,_e+ve]],[/\bqihoobrowser\/?([\w\.]*)/i],[w,[v,"360"]],[/\b(qq)\/([\w\.]+)/i],[[v,/(.+)/,"$1Browser"],w],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[v,/(.+)/,"$1"+Se],w],[/samsungbrowser\/([\w\.]+)/i],[w,[v,ce+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[w,[v,we+" Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[v,we+" Mobile"],w],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[v,w],[/(lbbrowser|rekonq)/i],[v],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[w,v],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[v,ye],w,[b,x]],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(instagram|snapchat|klarna)[\/ ]([-\w\.]+)/i],[v,w,[b,x]],[/\bgsa\/([\w\.]+) .*safari\//i],[w,[v,"GSA"],[b,x]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[w,[v,"TikTok"],[b,x]],[/\[(linkedin)app\]/i],[v,[b,x]],[/(chromium)[\/ ]([-\w\.]+)/i],[v,w],[/headlesschrome(?:\/([\w\.]+)| )/i],[w,[v,he+" Headless"]],[/wv\).+chrome\/([\w\.]+).+edgw\//i],[w,[v,ge+" WebView2"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[v,he+" WebView"],w],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[w,[v,"Android"+Se]],[/chrome\/([\w\.]+) mobile/i],[w,[v,_e+"Chrome"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[v,w],[/version\/([\w\.\,]+) .*mobile(?:\/\w+ | ?)safari/i],[w,[v,_e+"Safari"]],[/iphone .*mobile(?:\/\w+ | ?)safari/i],[[v,_e+"Safari"]],[/version\/([\w\.\,]+) .*(safari)/i],[w,v],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[v,[w,"1"]],[/(webkit|khtml)\/([\w\.]+)/i],[v,w],[/(?:mobile|tablet);.*(firefox)\/([\w\.-]+)/i],[[v,_e+ve],w],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[v,"Netscape"],w],[/(wolvic|librewolf)\/([\w\.]+)/i],[v,w],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[w,[v,ve+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[v,[w,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[v,[w,/[^\d\.]+./,o]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[_,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[_,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[_,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[_,/ower/,o,Ie]],[/ sun4\w[;\)]/i],[[_,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[_,Ie]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[C,[y,ce],[b,T]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,/sec-(sgh\w+)/i],[C,[y,ce],[b,k]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[C,[y,J],[b,k]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[C,[y,J],[b,T]],[/(macintosh);/i],[C,[y,J]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[C,[y,de],[b,k]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[C,[y,te],[b,T]],[/honor([-\w ]+)[;\)]/i],[C,[y,te],[b,k]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[C,[y,Z],[b,T]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[C,[y,Z],[b,k]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[C,/_/g," "],[y,ue],[b,T]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[C,/_/g," "],[y,ue],[b,k]],[/droid.+; (cph2[3-6]\d[13579]|((gm|hd)19|(ac|be|in|kb)20|(d[en]|eb|le|mt)21|ne22)[0-2]\d|p[g-k]\w[1m]10)\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[C,[y,oe],[b,k]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[C,[y,ae],[b,k]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[C,[y,Fe,{OnePlus:["203","304","403","404","413","415"],"*":ae}],[b,T]],[/(vivo (5r?|6|8l?|go|one|s|x[il]?[2-4]?)[\w\+ ]*)(?: bui|\))/i],[C,[y,"BLU"],[b,k]],[/; vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[C,[y,"Vivo"],[b,k]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[C,[y,"Realme"],[b,k]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[C,[y,ee],[b,T]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i],[C,[y,ee],[b,k]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,/((?:moto(?! 360)[-\w\(\) ]+|xt\d{3,4}[cgkosw\+]?[-\d]*|nexus 6)(?= bui|\)))/i],[C,[y,ne],[b,k]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[C,[y,ne],[b,T]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[C,[y,re],[b,T]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,/\blg-?([\d\w]+) bui/i],[C,[y,re],[b,k]],[/(nokia) (t[12][01])/i],[y,C,[b,T]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[C,/_/g," "],[b,k],[y,"Nokia"]],[/(pixel (c|tablet))\b/i],[C,[y,Y],[b,T]],[/droid.+;(?: google)? (g(01[13]a|020[aem]|025[jn]|1b60|1f8f|2ybb|4s1m|576d|5nz6|8hhn|8vou|a02099|c15s|d1yq|e2ae|ec77|gh2x|kv4x|p4bc|pj41|r83y|tt9q|ur25|wvk6)|pixel[\d ]*a?( pro)?( xl)?( fold)?( \(5g\))?)( bui|\))/i],[C,[y,Y],[b,k]],[/(google) (pixelbook( go)?)/i],[y,C],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-\w\w\d\d)(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[C,[y,le],[b,k]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[C,"Xperia Tablet"],[y,le],[b,T]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[C,[y,K],[b,T]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[C,/(.+)/g,"Fire Phone $1"],[y,K],[b,k]],[/(playbook);[-\w\),; ]+(rim)/i],[C,y,[b,T]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[C,[y,X],[b,k]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[C,[y,Q],[b,T]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[C,[y,Q],[b,k]],[/(nexus 9)/i],[C,[y,"HTC"],[b,T]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[y,[C,/_/g," "],[b,k]],[/tcl (xess p17aa)/i,/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])(_\w(\w|\w\w))?(\)| bui)/i],[C,[y,"TCL"],[b,T]],[/droid [\w\.]+; (418(?:7d|8v)|5087z|5102l|61(?:02[dh]|25[adfh]|27[ai]|56[dh]|59k|65[ah])|a509dl|t(?:43(?:0w|1[adepqu])|50(?:6d|7[adju])|6(?:09dl|10k|12b|71[efho]|76[hjk])|7(?:66[ahju]|67[hw]|7[045][bh]|71[hk]|73o|76[ho]|79w|81[hks]?|82h|90[bhsy]|99b)|810[hs]))(_\w(\w|\w\w))?(\)| bui)/i],[C,[y,"TCL"],[b,k]],[/(itel) ((\w+))/i],[[y,Ie],C,[b,Fe,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[C,[y,"Acer"],[b,T]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[C,[y,"Meizu"],[b,k]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[C,[y,"Ulefone"],[b,k]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[C,[y,"Energizer"],[b,k]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[C,[y,"Cat"],[b,k]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[C,[y,"Smartfren"],[b,k]],[/droid.+; (a(in)?(0(15|59|6[35])|142)p?)/i],[C,[y,"Nothing"],[b,k]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[C,[y,"Archos"],[b,T]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[C,[y,"Archos"],[b,k]],[/; (n159v)/i],[C,[y,"HMD"],[b,k]],[/(imo) (tab \w+)/i,/(infinix|tecno) (x1101b?|p904|dp(7c|8d|10a)( pro)?|p70[1-3]a?|p904|t1101)/i],[y,C,[b,T]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (blu|hmd|imo|infinix|lava|oneplus|tcl)[_ ]([\w\+ ]+?)(?: bui|\)|; r)/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(oppo) ?([\w ]+) bui/i],[y,C,[b,k]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i],[y,C,[b,T]],[/(surface duo)/i],[C,[y,ie],[b,T]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[C,[y,"Fairphone"],[b,k]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[C,[y,se],[b,T]],[/(sprint) (\w+)/i],[y,C,[b,k]],[/(kin\.[onetw]{3})/i],[[C,/\./g," "],[y,ie],[b,k]],[/droid.+; ([c6]+|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[C,[y,pe],[b,T]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[C,[y,pe],[b,k]],[/smart-tv.+(samsung)/i],[y,[b,P]],[/hbbtv.+maple;(\d+)/i],[[C,/^/,"SmartTV"],[y,ce],[b,P]],[/(vizio)(?: |.+model\/)(\w+-\w+)/i,/tcast.+(lg)e?. ([-\w]+)/i],[y,C,[b,P]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[y,re],[b,P]],[/(apple) ?tv/i],[y,[C,J+" TV"],[b,P]],[/crkey.*devicetype\/chromecast/i],[[C,me+" Third Generation"],[y,Y],[b,P]],[/crkey.*devicetype\/([^/]*)/i],[[C,/^/,"Chromecast "],[y,Y],[b,P]],[/fuchsia.*crkey/i],[[C,me+" Nest Hub"],[y,Y],[b,P]],[/crkey/i],[[C,me],[y,Y],[b,P]],[/(portaltv)/i],[C,[y,ye],[b,P]],[/droid.+aft(\w+)( bui|\))/i],[C,[y,K],[b,P]],[/(shield \w+ tv)/i],[C,[y,se],[b,P]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[C,[y,de],[b,P]],[/(bravia[\w ]+)( bui|\))/i],[C,[y,le],[b,P]],[/(mi(tv|box)-?\w+) bui/i],[C,[y,ue],[b,P]],[/Hbbtv.*(technisat) (.*);/i],[y,C,[b,P]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[y,/.+\/(\w+)/,"$1",Fe,{LG:"lge"}],[C,Ne],[b,P]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[C,[b,P]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:|large screen[\w ]+safari)\b/i],[[b,P]],[/(playstation \w+)/i],[C,[y,le],[b,R]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[C,[y,ie],[b,R]],[/(ouya)/i,/(nintendo) (\w+)/i,/(retroid) (pocket ([^\)]+))/i],[y,C,[b,R]],[/droid.+; (shield)( bui|\))/i],[C,[y,se],[b,R]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[C,[y,ce],[b,O]],[/((pebble))app/i,/(asus|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[y,C,[b,O]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[C,[y,ae],[b,O]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[C,[y,J],[b,O]],[/(opwwe\d{3})/i],[C,[y,oe],[b,O]],[/(moto 360)/i],[C,[y,ne],[b,O]],[/(smartwatch 3)/i],[C,[y,le],[b,O]],[/(g watch r)/i],[C,[y,re],[b,O]],[/droid.+; (wt63?0{2,3})\)/i],[C,[y,pe],[b,O]],[/droid.+; (glass) \d/i],[C,[y,Y],[b,E]],[/(pico) (4|neo3(?: link|pro)?)/i],[y,C,[b,E]],[/(quest( \d| pro)?s?).+vr/i],[C,[y,ye],[b,E]],[/mobile vr; rv.+firefox/i],[[b,E]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[y,[b,D]],[/(aeobc)\b/i],[C,[y,K],[b,D]],[/(homepod).+mac os/i],[C,[y,J],[b,D]],[/windows iot/i],[[b,D]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+?(mobile|vr|\d) safari/i],[C,[b,Fe,{mobile:"Mobile",xr:"VR","*":T}]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[b,T]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[b,k]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[C,[y,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[w,[v,ge+"HTML"]],[/(arkweb)\/([\w\.]+)/i],[v,w],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[w,[v,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[v,w],[/ladybird\//i],[[v,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[w,v]],os:[[/(windows nt) (6\.[23]); arm/i],[[v,/N/,"R"],[w,Fe,ze]],[/(windows (?:phone|mobile|iot))(?: os)?[\/ ]?([\d\.]*( se)?)/i,/(windows)[\/ ](1[01]|2000|3\.1|7|8(\.1)?|9[58]|me|server 20\d\d( r2)?|vista|xp)/i],[v,w],[/windows nt ?([\d\.\)]*)(?!.+xbox)/i,/\bwin(?=3| ?9|n)(?:nt| 9x )?([\d\.;]*)/i],[[w,/(;|\))/g,"",Fe,ze],[v,Ce]],[/(windows ce)\/?([\d\.]*)/i],[v,w],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[w,/_/g,"."],[v,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+(haiku|morphos))/i],[[v,"macOS"],[w,/_/g,"."]],[/android ([\d\.]+).*crkey/i],[w,[v,me+" Android"]],[/fuchsia.*crkey\/([\d\.]+)/i],[w,[v,me+" Fuchsia"]],[/crkey\/([\d\.]+).*devicetype\/smartspeaker/i],[w,[v,me+" SmartSpeaker"]],[/linux.*crkey\/([\d\.]+)/i],[w,[v,me+" Linux"]],[/crkey\/([\d\.]+)/i],[w,[v,me]],[/droid ([\w\.]+)\b.+(android[- ]x86)/i],[w,v],[/(ubuntu) ([\w\.]+) like android/i],[[v,/(.+)/,"$1 Touch"],w],[/(harmonyos)[\/ ]?([\d\.]*)/i,/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen)\w*[-\/\.; ]?([\d\.]*)/i],[v,w],[/\(bb(10);/i],[w,[v,X]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[w,[v,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[w,[v,ve+" OS"]],[/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i,/webos(?:[ \/]?|\.tv-20(?=2[2-9]))(\d[\d\.]*)/i],[w,[v,"webOS"]],[/web0s;.+?(?:chr[o0]me|safari)\/(\d+)/i],[[w,Fe,{25:"120",24:"108",23:"94",22:"87",6:"79",5:"68",4:"53",3:"38",2:"538",1:"537","*":"TV"}],[v,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[w,[v,"watchOS"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[v,"Chrome OS"],w],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) (\w+)/i,/(xbox); +xbox ([^\);]+)/i,/(pico) .+os([\w\.]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/linux.+(mint)[\/\(\) ]?([\w\.]*)/i,/(mageia|vectorlinux|fuchsia|arcaos|arch(?= ?linux))[;l ]([\d\.]*)/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire|knoppix)(?: gnu[\/ ]linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/\b(aix)[; ]([1-9\.]{0,4})/i,/(hurd|linux|morphos)(?: (?:arm|x86|ppc)\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) ?(r\d)?/i],[v,w],[/(sunos) ?([\d\.]*)/i],[[v,"Solaris"],w],[/\b(beos|os\/2|amigaos|openvms|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[v,w]]},Ge=(je.call((n={init:{},isIgnore:{},isIgnoreRgx:{},toString:{}}).init,[[u,[v,w,S,b]],[p,[_]],[h,[b,C,y]],[f,[v,w]],[m,[v,w]]]),je.call(n.isIgnore,[[u,[w,S]],[f,[w]],[m,[w]]]),je.call(n.isIgnoreRgx,[[u,/ ?browser$/i],[m,/ ?os$/i]]),je.call(n.toString,[[u,[v,w]],[p,[_]],[h,[y,C]],[f,[v,w]],[m,[v,w]]]),n),qe=function(e,t){var r=Ge.init[t],i=Ge.isIgnore[t]||0,n=Ge.isIgnoreRgx[t]||0,s=Ge.toString[t]||0;function a(){je.call(this,r)}return a.prototype.getItem=function(){return e},a.prototype.withClientHints=function(){return Te?Te.getHighEntropyValues(W).then(function(t){return e.setCH(new He(t,!1)).parseCH().get()}):e.parseCH().get()},a.prototype.withFeatureCheck=function(){return e.detectFeature().get()},t!=g&&(a.prototype.is=function(e){var t=!1;for(var r in this)if(this.hasOwnProperty(r)&&!Oe(i,r)&&Ie(n?Le(n,this[r]):this[r])==Ie(n?Le(n,e):e)){if(t=!0,e!=c)break}else if(e==c&&t){t=!t;break}return t},a.prototype.toString=function(){var e=o;for(var t in s)typeof this[s[t]]!==c&&(e+=(e?" ":o)+this[s[t]]);return e||c}),Te||(a.prototype.then=function(e){var t=this,r=function(){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e])};r.prototype={is:a.prototype.is,toString:a.prototype.toString};var i=new r;return e(i),i}),new a};function He(e,t){if(e=e||{},je.call(this,W),t)je.call(this,[[I,xe(e[B])],[j,xe(e[F])],[k,/\?1/.test(e[$])],[C,Ae(e[G])],[L,Ae(e[q])],[A,Ae(e[H])],[_,Ae(e[z])],[M,xe(e[U])],[N,Ae(e[V])]]);else for(var r in e)this.hasOwnProperty(r)&&typeof e[r]!==c&&(this[r]=e[r])}function We(e,t,r,n){return this.get=function(e){return e?this.data.hasOwnProperty(e)?this.data[e]:i:this.data},this.set=function(e,t){return this.data[e]=t,this},this.setCH=function(e){return this.uaCH=e,this},this.detectFeature=function(){if(ke&&ke.userAgent==this.ua)switch(this.itemType){case u:ke.brave&&typeof ke.brave.isBrave==a&&this.set(v,"Brave");break;case h:!this.get(b)&&Te&&Te[k]&&this.set(b,k),"Macintosh"==this.get(C)&&ke&&typeof ke.standalone!==c&&ke.maxTouchPoints&&ke.maxTouchPoints>2&&this.set(C,"iPad").set(b,T);break;case m:!this.get(v)&&Te&&Te[L]&&this.set(v,Te[L]);break;case g:var e=this.data,t=function(t){return e[t].getItem().detectFeature().get()};this.set(u,t(u)).set(p,t(p)).set(h,t(h)).set(f,t(f)).set(m,t(m))}return this},this.parseUA=function(){return this.itemType!=g&&Be.call(this.data,this.ua,this.rgxMap),this.itemType==u&&this.set(S,Me(this.get(w))),this},this.parseCH=function(){var e=this.uaCH,t=this.rgxMap;switch(this.itemType){case u:case f:var r,n=e[j]||e[I];if(n)for(var s in n){var o=n[s].brand||n[s],a=n[s].version;this.itemType==u&&!/not.a.brand/i.test(o)&&(!r||/Chrom/.test(r)&&o!=fe||r==ge&&/WebView2/.test(o))&&(o=Fe(o,Ue),(r=this.get(v))&&!/Chrom/.test(r)&&/Chrom/.test(o)||this.set(v,o).set(w,a).set(S,Me(a)),r=o),this.itemType==f&&o==fe&&this.set(w,a)}break;case p:var c=e[_];c&&(c&&"64"==e[N]&&(c+="64"),Be.call(this.data,c+";",t));break;case h:if(e[k]&&this.set(b,k),e[C]&&(this.set(C,e[C]),!this.get(b)||!this.get(y))){var d={};Be.call(d,"droid 9; "+e[C]+")",t),!this.get(b)&&d.type&&this.set(b,d.type),!this.get(y)&&d.vendor&&this.set(y,d.vendor)}if(e[M]){var l;if("string"!=typeof e[M])for(var R=0;!l&&R<e[M].length;)l=Fe(e[M][R++],Ve);else l=Fe(e[M],Ve);this.set(b,l)}break;case m:var T=e[L];if(T){var P=e[A];T==Ce&&(P=parseInt(Me(P),10)>=13?"11":"10"),this.set(v,T).set(w,P)}this.get(v)==Ce&&"Xbox"==e[C]&&this.set(v,"Xbox").set(w,i);break;case g:var O=this.data,E=function(t){return O[t].getItem().setCH(e).parseCH().get()};this.set(u,E(u)).set(p,E(p)).set(h,E(h)).set(f,E(f)).set(m,E(m))}return this},je.call(this,[["itemType",e],["ua",t],["uaCH",n],["rgxMap",r],["data",qe(this,e)]]),this}function Ke(e,t,r){if(typeof e===d?(Ee(e,!0)?(typeof t===d&&(r=t),t=e):(r=e,t=i),e=i):typeof e!==l||Ee(t,!0)||(r=t,t=i),r&&typeof r.append===a){var n={};r.forEach(function(e,t){n[t]=e}),r=n}if(!(this instanceof Ke))return new Ke(e,t,r).getResult();var c=typeof e===l?e:r&&r[s]?r[s]:ke&&ke.userAgent?ke.userAgent:o,v=new He(r,!0),b=t?function(e,t){var r={},i=t;if(!Ee(t))for(var n in i={},t)for(var s in t[n])i[s]=t[n][s].concat(i[s]?i[s]:[]);for(var o in e)r[o]=i[o]&&i[o].length%2==0?i[o].concat(e[o]):e[o];return r}($e,t):$e,y=function(e){return e==g?function(){return new We(e,c,b,v).set("ua",c).set(u,this.getBrowser()).set(p,this.getCPU()).set(h,this.getDevice()).set(f,this.getEngine()).set(m,this.getOS()).get()}:function(){return new We(e,c,b[e],v).parseUA().get()}};return je.call(this,[["getBrowser",y(u)],["getCPU",y(p)],["getDevice",y(h)],["getEngine",y(f)],["getOS",y(m)],["getResult",y(g)],["getUA",function(){return c}],["setUA",function(e){return De(e)&&(c=e.length>500?Ne(e,500):e),this}]]).setUA(c),this}Ke.VERSION="2.0.4",Ke.BROWSER=Pe([v,w,S,b]),Ke.CPU=Pe([_]),Ke.DEVICE=Pe([C,y,b,R,k,P,T,O,D]),Ke.ENGINE=Ke.OS=Pe([v,w]),e.exports&&(t=e.exports=Ke),t.UAParser=Ke;var Je=Re&&(r.jQuery||r.Zepto);if(Je&&!Je.ua){var Qe=new Ke;Je.ua=Qe.getResult(),Je.ua.get=function(){return Qe.getUA()},Je.ua.set=function(e){Qe.setUA(e);var t=Qe.getResult();for(var r in t)Je.ua[r]=t[r]}}}("object"==typeof window?window:a)}(Zn,Zn.exports);var es=Zn.exports,ts={},rs=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ts,"__esModule",{value:!0});var is=ts.Logger=void 0;const ns=rs(Xn),ss="mediasoup-client";is=ts.Logger=class{constructor(e){e?(this._debug=(0,ns.default)(`${ss}:${e}`),this._warn=(0,ns.default)(`${ss}:WARN:${e}`),this._error=(0,ns.default)(`${ss}:ERROR:${e}`)):(this._debug=(0,ns.default)(ss),this._warn=(0,ns.default)(`${ss}:WARN`),this._error=(0,ns.default)(`${ss}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var os,as={},cs={exports:{}},ds="object"==typeof Reflect?Reflect:null,ls=ds&&"function"==typeof ds.apply?ds.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};os=ds&&"function"==typeof ds.ownKeys?ds.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var us=Number.isNaN||function(e){return e!=e};function ps(){ps.init.call(this)}cs.exports=ps,cs.exports.once=function(e,t){return new Promise(function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}Ss(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Ss(e,"error",t,r)}(e,n,{once:!0})})},ps.EventEmitter=ps,ps.prototype._events=void 0,ps.prototype._eventsCount=0,ps.prototype._maxListeners=void 0;var hs=10;function fs(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function ms(e){return void 0===e._maxListeners?ps.defaultMaxListeners:e._maxListeners}function gs(e,t,r,i){var n,s,o;if(fs(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),void 0===o)o=s[t]=r,++e._eventsCount;else if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(n=ms(e))>0&&o.length>n&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,function(e){console&&console.warn&&console.warn(e)}(a)}return e}function vs(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function bs(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=vs.bind(i);return n.listener=r,i.wrapFn=n,n}function ys(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(n):_s(n,n.length)}function ws(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function _s(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function Ss(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function n(s){i.once&&e.removeEventListener(t,n),r(s)})}}Object.defineProperty(ps,"defaultMaxListeners",{enumerable:!0,get:function(){return hs},set:function(e){if("number"!=typeof e||e<0||us(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");hs=e}}),ps.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ps.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||us(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},ps.prototype.getMaxListeners=function(){return ms(this)},ps.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=n[e];if(void 0===a)return!1;if("function"==typeof a)ls(a,this,t);else{var c=a.length,d=_s(a,c);for(r=0;r<c;++r)ls(d[r],this,t)}return!0},ps.prototype.addListener=function(e,t){return gs(this,e,t,!1)},ps.prototype.on=ps.prototype.addListener,ps.prototype.prependListener=function(e,t){return gs(this,e,t,!0)},ps.prototype.once=function(e,t){return fs(t),this.on(e,bs(this,e,t)),this},ps.prototype.prependOnceListener=function(e,t){return fs(t),this.prependListener(e,bs(this,e,t)),this},ps.prototype.removeListener=function(e,t){var r,i,n,s,o;if(fs(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,n),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},ps.prototype.off=ps.prototype.removeListener,ps.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var n,s=Object.keys(r);for(i=0;i<s.length;++i)"removeListener"!==(n=s[i])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},ps.prototype.listeners=function(e){return ys(this,e,!0)},ps.prototype.rawListeners=function(e){return ys(this,e,!1)},ps.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):ws.call(e,t)},ps.prototype.listenerCount=ws,ps.prototype.eventNames=function(){return this._eventsCount>0?os(this._events):[]};var Cs=cs.exports;Object.defineProperty(as,"__esModule",{value:!0}),as.EnhancedEventEmitter=void 0;const Rs=Cs,ks=new ts.Logger("EnhancedEventEmitter");class Ts extends Rs.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(t){ks.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,t);try{super.emit("listenererror",e,t)}catch(e){}return Boolean(super.listenerCount(e))}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}}as.EnhancedEventEmitter=Ts;var Ps={};Object.defineProperty(Ps,"__esModule",{value:!0});var Os=Ps.InvalidStateError=Ps.UnsupportedError=void 0;class Es extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Es):this.stack=new Error(e).stack}}Ps.UnsupportedError=Es;class Ds extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ds):this.stack=new Error(e).stack}}Os=Ps.InvalidStateError=Ds;var xs={};Object.defineProperty(xs,"__esModule",{value:!0});var Is=xs.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))};xs.generateRandomNumber=function(){return Math.round(1e7*Math.random())},xs.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const i of r){const r=t[i];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var Ms={},js={},Ls={},As=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.Logger=void 0;const Ns=As(Xn),Bs="h264-profile-level-id";Ls.Logger=class{constructor(e){e?(this._debug=(0,Ns.default)(`${Bs}:${e}`),this._warn=(0,Ns.default)(`${Bs}:WARN:${e}`),this._error=(0,Ns.default)(`${Bs}:ERROR:${e}`)):(this._debug=(0,Ns.default)(Bs),this._warn=(0,Ns.default)(`${Bs}:WARN`),this._error=(0,Ns.default)(`${Bs}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}},Object.defineProperty(js,"__esModule",{value:!0}),js.ProfileLevelId=js.Level=js.Profile=void 0,js.parseProfileLevelId=Ks,js.profileLevelIdToString=Js,js.profileToString=function(e){switch(e){case zs.ConstrainedBaseline:return"ConstrainedBaseline";case zs.Baseline:return"Baseline";case zs.Main:return"Main";case zs.ConstrainedHigh:return"ConstrainedHigh";case zs.High:return"High";case zs.PredictiveHigh444:return"PredictiveHigh444";default:return void Fs.warn(`profileToString() | unrecognized profile ${e}`)}},js.levelToString=function(e){switch(e){case Vs.L1_b:return"1b";case Vs.L1:return"1";case Vs.L1_1:return"1.1";case Vs.L1_2:return"1.2";case Vs.L1_3:return"1.3";case Vs.L2:return"2";case Vs.L2_1:return"2.1";case Vs.L2_2:return"2.2";case Vs.L3:return"3";case Vs.L3_1:return"3.1";case Vs.L3_2:return"3.2";case Vs.L4:return"4";case Vs.L4_1:return"4.1";case Vs.L4_2:return"4.2";case Vs.L5:return"5";case Vs.L5_1:return"5.1";case Vs.L5_2:return"5.2";default:return void Fs.warn(`levelToString() | unrecognized level ${e}`)}},js.parseSdpProfileLevelId=Qs,js.isSameProfile=function(e={},t={}){const r=Qs(e),i=Qs(t);return Boolean(r&&i&&r.profile===i.profile)},js.isSameProfileAndLevel=function(e={},t={}){const r=Qs(e),i=Qs(t);return Boolean(r&&i&&r.profile===i.profile&&r.level==i.level)},js.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Fs.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=Qs(e),i=Qs(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!i)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==i.profile)throw new TypeError("H264 Profile mismatch");const n=Ys(e)&&Ys(t),s=r.level,o=i.level,a=(d=s,l=o,function(e,t){return e===Vs.L1_b?t!==Vs.L1&&t!==Vs.L1_b:t===Vs.L1_b?e!==Vs.L1:e<t}(d,l)?d:l),c=n?s:a;var d,l;return Fs.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${c}]`),Js(new Us(r.profile,c))},js.supportedLevel=function(e,t){for(let r=Ws.length-1;r>=0;--r){const i=Ws[r];if(256*i.max_macroblock_frame_size<=e&&i.max_macroblocks_per_second<=t*i.max_macroblock_frame_size)return Fs.debug(`supportedLevel() | result [max_frame_pixel_count:${e}, max_fps:${t}, level:${i.level}]`),i.level}return void Fs.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${e}, max_fps:${t}]`)};const Fs=new Ls.Logger;var zs,Vs;!function(e){e[e.ConstrainedBaseline=1]="ConstrainedBaseline",e[e.Baseline=2]="Baseline",e[e.Main=3]="Main",e[e.ConstrainedHigh=4]="ConstrainedHigh",e[e.High=5]="High",e[e.PredictiveHigh444=6]="PredictiveHigh444"}(zs||(js.Profile=zs={})),function(e){e[e.L1_b=0]="L1_b",e[e.L1=10]="L1",e[e.L1_1=11]="L1_1",e[e.L1_2=12]="L1_2",e[e.L1_3=13]="L1_3",e[e.L2=20]="L2",e[e.L2_1=21]="L2_1",e[e.L2_2=22]="L2_2",e[e.L3=30]="L3",e[e.L3_1=31]="L3_1",e[e.L3_2=32]="L3_2",e[e.L4=40]="L4",e[e.L4_1=41]="L4_1",e[e.L4_2=42]="L4_2",e[e.L5=50]="L5",e[e.L5_1=51]="L5_1",e[e.L5_2=52]="L5_2"}(Vs||(js.Level=Vs={}));class Us{constructor(e,t){this.profile=e,this.level=t}}js.ProfileLevelId=Us;const $s=new Us(zs.ConstrainedBaseline,Vs.L3_1);class Gs{constructor(e){this.mask=~Xs("x",e),this.masked_value=Xs("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class qs{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const Hs=[new qs(66,new Gs("x1xx0000"),zs.ConstrainedBaseline),new qs(77,new Gs("1xxx0000"),zs.ConstrainedBaseline),new qs(88,new Gs("11xx0000"),zs.ConstrainedBaseline),new qs(66,new Gs("x0xx0000"),zs.Baseline),new qs(88,new Gs("10xx0000"),zs.Baseline),new qs(77,new Gs("0x0x0000"),zs.Main),new qs(100,new Gs("00000000"),zs.High),new qs(100,new Gs("00001100"),zs.ConstrainedHigh),new qs(244,new Gs("00000000"),zs.PredictiveHigh444)],Ws=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Vs.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:Vs.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:Vs.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:Vs.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Vs.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:Vs.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:Vs.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:Vs.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:Vs.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:Vs.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:Vs.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Vs.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:Vs.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:Vs.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:Vs.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:Vs.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:Vs.L5_2}];function Ks(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,i=t>>8&255,n=t>>16&255;let s;switch(r){case Vs.L1_1:s=16&i?Vs.L1_b:Vs.L1_1;break;case Vs.L1:case Vs.L1_2:case Vs.L1_3:case Vs.L2:case Vs.L2_1:case Vs.L2_2:case Vs.L3:case Vs.L3_1:case Vs.L3_2:case Vs.L4:case Vs.L4_1:case Vs.L4_2:case Vs.L5:case Vs.L5_1:case Vs.L5_2:s=r;break;default:return void Fs.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const t of Hs)if(n===t.profile_idc&&t.profile_iop.isMatch(i))return Fs.debug(`parseProfileLevelId() | result [str:${e}, profile:${t.profile}, level:${s}]`),new Us(t.profile,s);Fs.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${n}, profile_iop:${i}]`)}function Js(e){if(e.level==Vs.L1_b)switch(e.profile){case zs.ConstrainedBaseline:return"42f00b";case zs.Baseline:return"42100b";case zs.Main:return"4d100b";default:return void Fs.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case zs.ConstrainedBaseline:t="42e0";break;case zs.Baseline:t="4200";break;case zs.Main:t="4d00";break;case zs.ConstrainedHigh:t="640c";break;case zs.High:t="6400";break;case zs.PredictiveHigh444:t="f400";break;default:return void Fs.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function Qs(e={}){const t=e["profile-level-id"];return t?Ks(t):$s}function Xs(e,t){return Number(t[0]===e)<<7|Number(t[1]===e)<<6|Number(t[2]===e)<<5|Number(t[3]===e)<<4|Number(t[4]===e)<<3|Number(t[5]===e)<<2|Number(t[6]===e)<<1|Number(t[7]===e)}function Ys(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}var Zs,eo=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),to=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ro=a&&a.__importStar||(Zs=function(e){return Zs=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},Zs(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=Zs(e),i=0;i<r.length;i++)"default"!==r[i]&&eo(t,e,r[i]);return to(t,e),t});Object.defineProperty(Ms,"__esModule",{value:!0}),Ms.validateRtpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(e.codecs&&!Array.isArray(e.codecs))throw new TypeError("caps.codecs is not an array");e.codecs||(e.codecs=[]);for(const t of e.codecs)ho(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)mo(t)},Ms.validateRtpParameters=po,Ms.validateSctpStreamParameters=function(e){if("object"!=typeof e)throw new TypeError("params is not an object");if("number"!=typeof e.streamId)throw new TypeError("missing params.streamId");let t=!1;"boolean"==typeof e.ordered?t=!0:e.ordered=!0;if(e.maxPacketLifeTime&&"number"!=typeof e.maxPacketLifeTime)throw new TypeError("invalid params.maxPacketLifeTime");if(e.maxRetransmits&&"number"!=typeof e.maxRetransmits)throw new TypeError("invalid params.maxRetransmits");if(e.maxPacketLifeTime&&e.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(t&&e.ordered&&(e.maxPacketLifeTime||e.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");t||!e.maxPacketLifeTime&&!e.maxRetransmits||(e.ordered=!1);if(e.label&&"string"!=typeof e.label)throw new TypeError("invalid params.label");if(e.protocol&&"string"!=typeof e.protocol)throw new TypeError("invalid params.protocol")},Ms.validateSctpCapabilities=function(e){if("object"!=typeof e)throw new TypeError("caps is not an object");if(!e.numStreams||"object"!=typeof e.numStreams)throw new TypeError("missing caps.numStreams");!function(e){if("object"!=typeof e)throw new TypeError("numStreams is not an object");if("number"!=typeof e.OS)throw new TypeError("missing numStreams.OS");if("number"!=typeof e.MIS)throw new TypeError("missing numStreams.MIS")}(e.numStreams)},Ms.getExtendedRtpCapabilities=function(e,t){const r={codecs:[],headerExtensions:[]};for(const i of t.codecs??[]){if(yo(i))continue;const t=(e.codecs??[]).find(e=>wo(e,i,{strict:!0,modify:!0}));if(!t)continue;const n={mimeType:t.mimeType,kind:t.kind,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters,remoteParameters:i.parameters,rtcpFeedback:So(t,i)};r.codecs.push(n)}for(const i of r.codecs){const r=e.codecs.find(e=>yo(e)&&e.parameters.apt===i.localPayloadType),n=t.codecs.find(e=>yo(e)&&e.parameters.apt===i.remotePayloadType);r&&n&&(i.localRtxPayloadType=r.preferredPayloadType,i.remoteRtxPayloadType=n.preferredPayloadType)}for(const i of t.headerExtensions){const t=e.headerExtensions.find(e=>_o(e,i));if(!t)continue;const n={kind:i.kind,uri:i.uri,sendId:t.preferredId,recvId:i.preferredId,encrypt:t.preferredEncrypt,direction:"sendrecv"};switch(i.direction){case"sendrecv":n.direction="sendrecv";break;case"recvonly":n.direction="sendonly";break;case"sendonly":n.direction="recvonly";break;case"inactive":n.direction="inactive"}r.headerExtensions.push(n)}return r},Ms.getRecvRtpCapabilities=function(e){const t={codecs:[],headerExtensions:[]};for(const r of e.codecs){const e={mimeType:r.mimeType,kind:r.kind,preferredPayloadType:r.remotePayloadType,clockRate:r.clockRate,channels:r.channels,parameters:r.localParameters,rtcpFeedback:r.rtcpFeedback};if(t.codecs.push(e),!r.remoteRtxPayloadType)continue;const i={mimeType:`${r.kind}/rtx`,kind:r.kind,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(const r of e.headerExtensions){if("sendrecv"!==r.direction&&"recvonly"!==r.direction)continue;const e={kind:r.kind,uri:r.uri,preferredId:r.recvId,preferredEncrypt:r.encrypt,direction:r.direction};t.headerExtensions.push(e)}return t};var io=Ms.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.localParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},no=Ms.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const i of t.codecs){if(i.kind!==e)continue;const t={mimeType:i.mimeType,payloadType:i.localPayloadType,clockRate:i.clockRate,channels:i.channels,parameters:i.remoteParameters,rtcpFeedback:i.rtcpFeedback};if(r.codecs.push(t),i.localRtxPayloadType){const e={mimeType:`${i.kind}/rtx`,payloadType:i.localRtxPayloadType,clockRate:i.clockRate,parameters:{apt:i.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const i of t.headerExtensions){if(i.kind&&i.kind!==e||"sendrecv"!==i.direction&&"sendonly"!==i.direction)continue;const t={uri:i.uri,id:i.sendId,encrypt:i.encrypt,parameters:{}};r.headerExtensions.push(t)}if(r.headerExtensions.some(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"goog-remb"!==e.type);else if(r.headerExtensions.some(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.uri))for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type);else for(const e of r.codecs)e.rtcpFeedback=(e.rtcpFeedback??[]).filter(e=>"transport-cc"!==e.type&&"goog-remb"!==e.type);return r},so=Ms.reduceCodecs=function(e,t){const r=[];if(t){for(let i=0;i<e.length;++i)if(wo(e[i],t,{strict:!0})){r.push(e[i]),yo(e[i+1])&&r.push(e[i+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),yo(e[1])&&r.push(e[1]);return r};Ms.generateProbatorRtpParameters=function(e){po(e=ao.clone(e));const t={mid:co,codecs:[],headerExtensions:[],encodings:[{ssrc:lo}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=uo,t.headerExtensions=e.headerExtensions,t},Ms.canSend=function(e,t){return t.codecs.some(t=>t.kind===e)},Ms.canReceive=function(e,t){if(po(e),0===e.codecs.length)return!1;const r=e.codecs[0];return t.codecs.some(e=>e.remotePayloadType===r.payloadType)};const oo=ro(js),ao=ro(xs),co="probator",lo=1234,uo=127;function po(e){if("object"!=typeof e)throw new TypeError("params is not an object");if(e.mid&&"string"!=typeof e.mid)throw new TypeError("params.mid is not a string");if(!Array.isArray(e.codecs))throw new TypeError("missing params.codecs");for(const t of e.codecs)go(t);if(e.headerExtensions&&!Array.isArray(e.headerExtensions))throw new TypeError("params.headerExtensions is not an array");e.headerExtensions||(e.headerExtensions=[]);for(const t of e.headerExtensions)vo(t);if(e.encodings&&!Array.isArray(e.encodings))throw new TypeError("params.encodings is not an array");e.encodings||(e.encodings=[]);for(const t of e.encodings)bo(t);if(e.rtcp&&"object"!=typeof e.rtcp)throw new TypeError("params.rtcp is not an object");e.rtcp||(e.rtcp={}),function(e){if("object"!=typeof e)throw new TypeError("rtcp is not an object");if(e.cname&&"string"!=typeof e.cname)throw new TypeError("invalid rtcp.cname");e.reducedSize&&"boolean"==typeof e.reducedSize||(e.reducedSize=!0)}(e.rtcp)}function ho(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if(e.kind=r[1].toLowerCase(),e.preferredPayloadType&&"number"!=typeof e.preferredPayloadType)throw new TypeError("invalid codec.preferredPayloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===e.kind?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)fo(t)}function fo(e){if("object"!=typeof e)throw new TypeError("fb is not an object");if(!e.type||"string"!=typeof e.type)throw new TypeError("missing fb.type");e.parameter&&"string"==typeof e.parameter||(e.parameter="")}function mo(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if("audio"!==e.kind&&"video"!==e.kind)throw new TypeError("invalid ext.kind");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.preferredId)throw new TypeError("missing ext.preferredId");if(e.preferredEncrypt&&"boolean"!=typeof e.preferredEncrypt)throw new TypeError("invalid ext.preferredEncrypt");if(e.preferredEncrypt||(e.preferredEncrypt=!1),e.direction&&"string"!=typeof e.direction)throw new TypeError("invalid ext.direction");e.direction||(e.direction="sendrecv")}function go(e){const t=new RegExp("^(audio|video)/(.+)","i");if("object"!=typeof e)throw new TypeError("codec is not an object");if(!e.mimeType||"string"!=typeof e.mimeType)throw new TypeError("missing codec.mimeType");const r=t.exec(e.mimeType);if(!r)throw new TypeError("invalid codec.mimeType");if("number"!=typeof e.payloadType)throw new TypeError("missing codec.payloadType");if("number"!=typeof e.clockRate)throw new TypeError("missing codec.clockRate");"audio"===r[1].toLowerCase()?"number"!=typeof e.channels&&(e.channels=1):delete e.channels,e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError(`invalid codec parameter [key:${t}s, value:${r}]`);if("apt"===t&&"number"!=typeof r)throw new TypeError("invalid codec apt parameter")}e.rtcpFeedback&&Array.isArray(e.rtcpFeedback)||(e.rtcpFeedback=[]);for(const t of e.rtcpFeedback)fo(t)}function vo(e){if("object"!=typeof e)throw new TypeError("ext is not an object");if(!e.uri||"string"!=typeof e.uri)throw new TypeError("missing ext.uri");if("number"!=typeof e.id)throw new TypeError("missing ext.id");if(e.encrypt&&"boolean"!=typeof e.encrypt)throw new TypeError("invalid ext.encrypt");e.encrypt||(e.encrypt=!1),e.parameters&&"object"==typeof e.parameters||(e.parameters={});for(const t of Object.keys(e.parameters)){let r=e.parameters[t];if(void 0===r&&(e.parameters[t]="",r=""),"string"!=typeof r&&"number"!=typeof r)throw new TypeError("invalid header extension parameter")}}function bo(e){if("object"!=typeof e)throw new TypeError("encoding is not an object");if(e.ssrc&&"number"!=typeof e.ssrc)throw new TypeError("invalid encoding.ssrc");if(e.rid&&"string"!=typeof e.rid)throw new TypeError("invalid encoding.rid");if(e.rtx&&"object"!=typeof e.rtx)throw new TypeError("invalid encoding.rtx");if(e.rtx&&"number"!=typeof e.rtx.ssrc)throw new TypeError("missing encoding.rtx.ssrc");if(e.dtx&&"boolean"==typeof e.dtx||(e.dtx=!1),e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("invalid encoding.scalabilityMode")}function yo(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function wo(e,t,{strict:r=!1,modify:i=!1}={}){const n=e.mimeType.toLowerCase();if(n!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(n){case"video/h264":if(r){if((e.parameters["packetization-mode"]||0)!==(t.parameters["packetization-mode"]||0))return!1;if(!oo.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=oo.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}i&&(r?(e.parameters["profile-level-id"]=r,t.parameters["profile-level-id"]=r):(delete e.parameters["profile-level-id"],delete t.parameters["profile-level-id"]))}break;case"video/vp9":if(r){if((e.parameters["profile-id"]||0)!==(t.parameters["profile-id"]||0))return!1}}return!0}function _o(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function So(e,t){const r=[];for(const i of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find(e=>e.type===i.type&&(e.parameter===i.parameter||!e.parameter&&!i.parameter));e&&r.push(e)}return r}var Co={},Ro={},ko={},To={};Object.defineProperty(To,"__esModule",{value:!0}),To.Logger=void 0;const Po=Xn,Oo="awaitqueue";To.Logger=class{_debug;_warn;_error;constructor(e){e?(this._debug=Po(`${Oo}:${e}`),this._warn=Po(`${Oo}:WARN:${e}`),this._error=Po(`${Oo}:ERROR:${e}`)):(this._debug=Po(Oo),this._warn=Po(`${Oo}:WARN`),this._error=Po(`${Oo}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};var Eo={};Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.AwaitQueueRemovedTaskError=Eo.AwaitQueueStoppedError=void 0;class Do extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Do)}}Eo.AwaitQueueStoppedError=Do;class xo extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,xo)}}Eo.AwaitQueueRemovedTaskError=xo,Object.defineProperty(ko,"__esModule",{value:!0}),ko.AwaitQueue=void 0;const Io=Eo,Mo=new To.Logger("AwaitQueue");
2
2
  /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
- let jo;ko.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;stopping=!1;constructor(){Mo.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,Mo.debug(`push() [name:${t}]`),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise((r,i)=>{const n={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(n.completed)return;n.completed=!0,this.pendingTasks.delete(n.id),Mo.debug(`resolving task [name:${n.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!n.completed&&(n.completed=!0,this.pendingTasks.delete(n.id),Mo.debug(`rejecting task [name:${n.name}]: %s`,String(e)),i(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(n.id,n),1===this.pendingTasks.size&&this.execute(n)})}stop(){Mo.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Mo.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Io.AwaitQueueStoppedError);this.stopping=!1}remove(e){Mo.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Io.AwaitQueueRemovedTaskError):Mo.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let t=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0}))}async execute(e){if(Mo.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=ko;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Eo;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Ro);var Lo="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:a):e=>(jo||(jo=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0)),Ao={};Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.Producer=void 0;const No=as,Bo=Ps,Fo=new ts.Logger("Producer");class zo extends No.EnhancedEventEmitter{constructor({id:e,localId:t,rtpSender:r,track:i,rtpParameters:n,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),this._closed=!1,this._observer=new No.EnhancedEventEmitter,Fo.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=i,this._kind=i.kind,this._rtpParameters=n,this._paused=!!o&&!i.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Fo.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Fo.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Bo.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){Fo.debug("pause()"),this._closed?Fo.error("pause() | Producer closed"):(this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause"))}resume(){Fo.debug("resume()"),this._closed?Fo.error("resume() | Producer closed"):(this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume"))}async replaceTrack({track:e}){if(Fo.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Bo.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new Bo.InvalidStateError("track ended");e!==this._track?(await new Promise((t,r)=>{this.safeEmit("@replacetrack",e,t,r)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()):Fo.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Bo.InvalidStateError("closed");if("video"!==this._kind)throw new Bo.UnsupportedError("not a video Producer");if("number"!=typeof e)throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Bo.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){Fo.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch(e){}}}Ao.Producer=zo;var Vo={};Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.Consumer=void 0;const Uo=as,$o=Ps,Go=new ts.Logger("Consumer");class qo extends Uo.EnhancedEventEmitter{constructor({id:e,localId:t,producerId:r,rtpReceiver:i,track:n,rtpParameters:s,appData:o}){super(),this._closed=!1,this._observer=new Uo.EnhancedEventEmitter,Go.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=i,this._track=n,this._rtpParameters=s,this._paused=!n.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Go.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Go.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new $o.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){Go.debug("pause()"),this._closed?Go.error("pause() | Consumer closed"):this._paused?Go.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Go.debug("resume()"),this._closed?Go.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Go.debug("resume() | Consumer is already resumed")}onTrackEnded(){Go.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Vo.Consumer=qo;var Ho={};Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.DataProducer=void 0;const Wo=as,Ko=Ps,Jo=new ts.Logger("DataProducer");class Qo extends Wo.EnhancedEventEmitter{constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:i}){super(),this._closed=!1,this._observer=new Wo.EnhancedEventEmitter,Jo.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Jo.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Jo.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(Jo.debug("send()"),this._closed)throw new Ko.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Jo.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?Jo.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):Jo.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Jo.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||Jo.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}}Ho.DataProducer=Qo;var Yo={};Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.DataConsumer=void 0;const Xo=as,Zo=new ts.Logger("DataConsumer");class ea extends Xo.EnhancedEventEmitter{constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:i,appData:n}){super(),this._closed=!1,this._observer=new Xo.EnhancedEventEmitter,Zo.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=i,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Zo.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Zo.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Zo.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?Zo.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):Zo.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Zo.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}}Yo.DataConsumer=ea;var ta=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ra=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ia=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ta(r,t,i[n]);return ra(r,t),r}}(),na=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Co,"__esModule",{value:!0}),Co.Transport=void 0;const sa=Ro,oa=na(Lo),aa=ts,ca=as,da=Ps,la=ia(xs),ua=ia(Ms),pa=Ao,ha=Vo,fa=Ho,ma=Yo,ga=new aa.Logger("Transport");class va{constructor(e){this.consumerOptions=e,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}let ba=class extends ca.EnhancedEventEmitter{constructor({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:u,extendedRtpCapabilities:p,canProduceByKind:h}){super(),this._closed=!1,this._iceGatheringState="new",this._connectionState="new",this._producers=new Map,this._consumers=new Map,this._dataProducers=new Map,this._dataConsumers=new Map,this._probatorConsumerCreated=!1,this._awaitQueue=new sa.AwaitQueue,this._pendingConsumerTasks=[],this._consumerCreationInProgress=!1,this._pendingPauseConsumers=new Map,this._consumerPauseInProgress=!1,this._pendingResumeConsumers=new Map,this._consumerResumeInProgress=!1,this._pendingCloseConsumers=new Map,this._consumerCloseInProgress=!1,this._observer=new ca.EnhancedEventEmitter,ga.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._extendedRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=la.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,delete f.sdpSemantics,this._handler=u(),this._handler.run({direction:e,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,proprietaryConstraints:d,extendedRtpCapabilities:p}),this._appData=l??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){ga.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close")}}async getStats(){if(this._closed)throw new da.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(ga.debug("restartIce()"),this._closed)throw new da.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(ga.debug("updateIceServers()"),this._closed)throw new da.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,encodings:t,codecOptions:r,codec:i,stopTracks:n=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(ga.debug("produce() [track:%o]",e),this._closed)throw new da.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new da.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new da.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new da.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push(async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.map(e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t}));const{localId:l,rtpParameters:u,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:i,onRtpSender:a});try{ua.validateRtpParameters(u);const{id:t}=await new Promise((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:u,appData:c},t,r)}),r=new pa.Producer({id:t,localId:l,rtpSender:p,track:e,rtpParameters:u,stopTracks:n,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(l).catch(()=>{}),e}},"transport.produce()").catch(t=>{if(n)try{e.stop()}catch(e){}throw t})}async consume({id:e,producerId:t,kind:r,rtpParameters:i,streamId:n,onRtpReceiver:s,appData:o={}}){if(ga.debug("consume()"),this._closed)throw new da.InvalidStateError("closed");if("recv"!==this._direction)throw new da.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=la.clone(i);if(!ua.canReceive(a,this._extendedRtpCapabilities))throw new da.UnsupportedError("cannot consume this Producer");const c=new va({id:e,producerId:t,kind:r,rtpParameters:a,streamId:n,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),(0,oa.default)(()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()}),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:i="",protocol:n="",appData:s={}}={}){if(ga.debug("produceData()"),this._closed)throw new da.InvalidStateError("closed");if("send"!==this._direction)throw new da.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new da.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push(async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n});ua.validateSctpStreamParameters(a);const{id:c}=await new Promise((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:i,protocol:n,appData:s},e,t)}),d=new fa.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:i="",protocol:n="",appData:s={}}){if(ga.debug("consumeData()"),this._closed)throw new da.InvalidStateError("closed");if("recv"!==this._direction)throw new da.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new da.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=la.clone(r);return ua.validateSctpStreamParameters(o),this._awaitQueue.push(async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:i,protocol:n}),a=new ma.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a},"transport.consumeData()")}async createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingConsumerTasks.length)return void ga.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o})}try{const i=await this._handler.receive(r);for(let r=0;r<i.length;++r){const n=e[r],s=i[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=n.consumerOptions,{localId:u,rtpReceiver:p,track:h}=s,f=new ha.Consumer({id:o,localId:u,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:l});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),n.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=ua.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),ga.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){ga.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingPauseConsumers.size)return void ga.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.pauseReceiving(t)}catch(e){ga.error("pausePendingConsumers() | failed to pause Consumers:",e)}},"transport.pausePendingConsumers").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingResumeConsumers.size)return void ga.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.resumeReceiving(t)}catch(e){ga.error("resumePendingConsumers() | failed to resume Consumers:",e)}},"transport.resumePendingConsumers").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingCloseConsumers.size)return void ga.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(e=>e.localId))}catch(e){ga.error("closePendingConsumers() | failed to close Consumers:",e)}},"transport.closePendingConsumers").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){const e=this._handler;e.on("@connect",({dtlsParameters:e},t,r)=>{this._closed?r(new da.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)}),e.on("@icegatheringstatechange",e=>{e!==this._iceGatheringState&&(ga.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))}),e.on("@connectionstatechange",e=>{e!==this._connectionState&&(ga.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),this._closed||this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(e=>ga.warn("producer.close() failed:%o",e))}),e.on("@pause",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(r)}),e.on("@resume",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(r)}),e.on("@replacetrack",(t,r,i)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(r).catch(i)}),e.on("@setmaxspatiallayer",(t,r,i)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(r).catch(i)}),e.on("@setrtpencodingparameters",(t,r,i)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(r).catch(i)}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new da.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),this._closed||(this._pendingCloseConsumers.set(e.id,e),!1===this._consumerCloseInProgress&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),(0,oa.default)(()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),(0,oa.default)(()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()})}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new da.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};Co.Transport=ba;var ya={},wa={},_a=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Sa=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ca=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&_a(r,t,i[n]);return Sa(r,t),r}}();Object.defineProperty(wa,"__esModule",{value:!0});var Ra=wa.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=[];let i=!1,n=!1;for(const s of e.media){const e=s.type;switch(e){case"audio":if(i)continue;i=!0;break;case"video":if(n)continue;n=!0;break;default:continue}for(const r of s.rtp){const i={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(i.preferredPayloadType,i)}for(const e of s.fmtp||[]){const r=Oa.parseParams(e.config),i=t.get(e.payload);i&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),i.parameters=r)}for(const r of s.rtcpFb||[]){const i={type:r.type,parameter:r.subtype};if(i.parameter||delete i.parameter,"*"!==r.payload){const e=t.get(r.payload);if(!e)continue;e.rtcpFeedback.push(i)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(i)}for(const t of s.ext||[]){if(t["encrypt-uri"])continue;const i={kind:e,uri:t.uri,preferredId:t.value};r.push(i)}}return{codecs:Array.from(t.values()),headerExtensions:r}},ka=wa.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,i=e.fingerprint;if(!r||!i){const t=(e.media||[]).find(e=>0!==e.port);t&&(r??(r=t.setup),i??(i=t.fingerprint))}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!i)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:i.type,value:i.hash}]}},Ta=wa.getCname=function({offerMediaObject:e}){const t=(e.ssrcs||[]).find(e=>"cname"===e.attribute);if(!t)return"";return t.value},Pa=wa.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;if(!(t.rtp||[]).find(e=>e.payload===r.payloadType))continue;t.fmtp=t.fmtp||[];let i=t.fmtp.find(e=>e.payload===r.payloadType);i||(i={payload:r.payloadType,config:""},t.fmtp.push(i));const n=Oa.parseParams(i.config);switch(e){case"audio/opus":{const e=r.parameters["sprop-stereo"];void 0!==e&&(n.stereo=Number(e)?1:0);break}}i.config="";for(const e of Object.keys(n))i.config&&(i.config+=";"),i.config+=`${e}=${n[e]}`}};const Oa=Ca(gi);var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs||[]){const e=r.id;t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const i of e.ssrcGroups||[]){if("FID"!==i.semantics)continue;let[e,n]=i.ssrcs.split(/\s+/);e=Number(e),n=Number(n),t.has(e)&&(t.delete(e),t.delete(n),r.set(e,n))}for(const e of t)r.set(e,null);const i=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),i.push(r)}return i},Ea.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs||[]).find(e=>"msid"===e.attribute);if(!r)throw new Error("a=ssrc line with msid information not found");const[i,n]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups||[]).some(e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)});const a=e.ssrcs.find(e=>"cname"===e.attribute);if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],l=[];for(let e=0;e<t;++e)d.push(s+e),o&&l.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${i} ${n}`});for(let t=0;t<l.length;++t){const r=d[t],s=l[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${i} ${n}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Da={};Object.defineProperty(Da,"__esModule",{value:!0});var xa=Da.addNackSuppportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some(e=>"nack"===e.type&&!e.parameter)||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))};var Ia={};Object.defineProperty(Ia,"__esModule",{value:!0});var Ma=Ia.HandlerInterface=void 0;const ja=as;class La extends ja.EnhancedEventEmitter{constructor(){super()}}Ma=Ia.HandlerInterface=La;var Aa={},Na={},Ba=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Fa=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),za=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Ba(r,t,i[n]);return Fa(r,t),r}}();Object.defineProperty(Na,"__esModule",{value:!0}),Na.OfferMediaSection=Na.AnswerMediaSection=Na.MediaSection=void 0;const Va=za(gi),Ua=za(xs);class $a{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:i=!1}){if(this._mediaObject={},this._planB=i,e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={component:1};t.foundation=e.foundation,t.ip=e.address??e.ip,t.port=e.port,t.priority=e.priority,t.transport=e.protocol,t.type=e.type,e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause(),delete this._mediaObject.ext,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}close(){this.disable(),this._mediaObject.port=0}}Na.MediaSection=$a;Na.AnswerMediaSection=class extends $a{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d,extmapAllowMixed:l=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of c.codecs){const t={payload:e.payloadType,codec:Ga(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Ua.clone(e.parameters)??{};let i=Ua.clone(e.rtcpFeedback)??[];if(d){const{opusStereo:t,opusFec:n,opusDtx:s,opusMaxPlaybackRate:o,opusMaxAverageBitrate:c,opusPtime:l,opusNack:u,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=d,m=a.codecs.find(t=>t.payloadType===e.payloadType);switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==n&&(m.parameters.useinbandfec=n?1:0,r.useinbandfec=n?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==o&&(r.maxplaybackrate=o),void 0!==c&&(r.maxaveragebitrate=c),void 0!==l&&(m.parameters.ptime=l,r.ptime=l),u||(m.rtcpFeedback=m.rtcpFeedback.filter(e=>"nack"!==e.type||e.parameter),i=i.filter(e=>"nack"!==e.type||e.parameter));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const n={payload:e.payloadType,config:""};for(const e of Object.keys(r))n.config&&(n.config+=";"),n.config+=`${e}=${r[e]}`;n.config&&this._mediaObject.fmtp.push(n);for(const t of i)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions){(o.ext??[]).some(t=>t.uri===e.uri)&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if(l&&"extmap-allow-mixed"===o.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize",this._planB&&"video"===this._mediaObject.type&&(this._mediaObject.xGoogleFlag="conference");break;case"application":"number"==typeof o.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,i=Va.parseSimulcastStreamList(r);for(const e of i)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=i.map(e=>e.map(e=>`${e.paused?"~":""}${e.scid}`).join(",")).join(";")}};function Ga(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}Na.OfferMediaSection=class extends $a{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:l,oldDataChannelSpec:u=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o),this._mediaObject.type=a,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=i?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._planB||(this._mediaObject.msid=`${d??"-"} ${l}`);for(const e of c.codecs){const t={payload:e.payloadType,codec:Ga(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=c.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],c.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:t,attribute:"msid",value:`${d??"-"} ${l}`}),r&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:r,attribute:"msid",value:`${d??"-"} ${l}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":u?(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize}):(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize)}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}planBReceive({offerRtpParameters:e,streamId:t,trackId:r}){const i=e.encodings[0],n=i.ssrc,s=i.rtx?.ssrc,o=this._mediaObject.payloads.split(" ");for(const t of e.codecs){if(o.includes(String(t.payloadType)))continue;const e={payload:t.payloadType,codec:Ga(t),rate:t.clockRate};t.channels>1&&(e.encoding=t.channels),this._mediaObject.rtp.push(e);const r={payload:t.payloadType,config:""};for(const e of Object.keys(t.parameters))r.config&&(r.config+=";"),r.config+=`${e}=${t.parameters[e]}`;r.config&&this._mediaObject.fmtp.push(r);for(const e of t.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:t.payloadType,type:e.type,subtype:e.parameter})}this._mediaObject.payloads+=` ${e.codecs.filter(e=>!this._mediaObject.payloads.includes(e.payloadType)).map(e=>e.payloadType).join(" ")}`,this._mediaObject.payloads=this._mediaObject.payloads.trim(),e.rtcp.cname&&this._mediaObject.ssrcs.push({id:n,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:n,attribute:"msid",value:`${t??"-"} ${r}`}),s&&(e.rtcp.cname&&this._mediaObject.ssrcs.push({id:s,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:s,attribute:"msid",value:`${t??"-"} ${r}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${n} ${s}`}))}planBStopReceiving({offerRtpParameters:e}){const t=e.encodings[0],r=t.ssrc,i=t.rtx?.ssrc;this._mediaObject.ssrcs=this._mediaObject.ssrcs.filter(e=>e.id!==r&&e.id!==i),i&&(this._mediaObject.ssrcGroups=this._mediaObject.ssrcGroups.filter(e=>e.ssrcs!==`${r} ${i}`))}};var qa=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ha=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Wa=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&qa(r,t,i[n]);return Ha(r,t),r}}();Object.defineProperty(Aa,"__esModule",{value:!0});var Ka=Aa.RemoteSdp=void 0;const Ja=Wa(gi),Qa=Na,Ya=new ts.Logger("RemoteSdp");Ka=Aa.RemoteSdp=class{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1}){if(this._mediaSections=[],this._midToIndex=new Map,this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=i,this._plainRtpParameters=n,this._planB=s,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:1e4,sessionVersion:0,username:"mediasoup-client"},name:"-",timing:{start:0,stop:0},media:[]},e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}n&&(this._sdpObject.origin.address=n.ip,this._sdpObject.origin.ipVer=n.ipVersion)}updateIceParameters(e){Ya.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Ya.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s=!1}){const o=new Qa.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s});t?this._replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this._replaceMediaSection(o):this._addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n}){const s=this._midToIndex.get(e);let o;if(void 0!==s&&(o=this._mediaSections[s]),o)o.planBReceive({offerRtpParameters:r,streamId:i,trackId:n}),this._replaceMediaSection(o);else{o=new Qa.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n});const s=this._mediaSections.find(e=>e.closed);s?this._replaceMediaSection(o,s.mid):this._addMediaSection(o)}}pauseMediaSection(e){this._findMediaSection(e).pause()}resumeSendingMediaSection(e){this._findMediaSection(e).resume()}resumeReceivingMediaSection(e){this._findMediaSection(e).resume()}disableMediaSection(e){this._findMediaSection(e).disable()}closeMediaSection(e){const t=this._findMediaSection(e);return e===this._firstMid?(Ya.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this._regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){const r=this._findMediaSection(e);r.muxSimulcastStreams(t),this._replaceMediaSection(r)}planBStopReceiving({mid:e,offerRtpParameters:t}){const r=this._findMediaSection(e);r.planBStopReceiving({offerRtpParameters:t}),this._replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new Qa.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this._addMediaSection(t)}receiveSctpAssociation({oldDataChannelSpec:e=!1}={}){const t=new Qa.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application",oldDataChannelSpec:e});this._addMediaSection(t)}getSdp(){return this._sdpObject.origin.sessionVersion++,Ja.write(this._sdpObject)}_addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this._regenerateBundleMids()}_replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const i=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(i.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this._regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}_findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}_regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};var Xa={};Object.defineProperty(Xa,"__esModule",{value:!0});var Za=Xa.parse=function(e){const t=ec.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const ec=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var tc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),rc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ic=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&tc(r,t,i[n]);return rc(r,t),r}}();Object.defineProperty(ya,"__esModule",{value:!0}),ya.Chrome111=void 0;const nc=ic(gi),sc=ts,oc=ic(xs),ac=ic(Ms),cc=ic(wa),dc=ic(Ea),lc=ic(Da),uc=Ps,pc=Ia,hc=Aa,fc=Xa,mc=new sc.Logger("Chrome111"),gc={OS:1024,MIS:1024};class vc extends pc.HandlerInterface{static createFactory(){return()=>new vc}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome111"}close(){if(mc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){mc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=nc.parse(t.sdp),i=cc.extractRtpCapabilities({sdpObject:r});return lc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return mc.debug("getNativeSctpCapabilities()"),{numStreams:gc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),mc.debug("run()"),this._direction=e,this._remoteSdp=new hc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:ac.getSendingRtpParameters("audio",d),video:ac.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:ac.getSendingRemoteRtpParameters("audio",d),video:ac.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):(mc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),mc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),mc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});mc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();mc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){if(this.assertNotClosed(),this.assertSendDirection(),mc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,fc.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`})}const s=oc.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=ac.reduceCodecs(s.codecs,i);const o=oc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=ac.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);const d=await this._pc.createOffer();let l=nc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),mc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const u=c.mid;s.mid=u,l=nc.parse(this._pc.localDescription.sdp);const p=l.media[a.idx];if(s.rtcp.cname=cc.getCname({offerMediaObject:p}),t)if(1===t.length){const e=dc.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=dc.getRtpEncodings({offerMediaObject:p});this._remoteSdp.send({offerMediaObject:p,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return mc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,c),{localId:u,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),mc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();mc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),mc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();mc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),mc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();mc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?mc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):mc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),mc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();mc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),mc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();mc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};mc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%gc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=nc.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),mc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;mc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=nc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);cc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:nc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),mc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){mc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){mc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){mc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};mc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=nc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=nc.parse(this._pc.localDescription.sdp));const r=cc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new uc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}ya.Chrome111=vc;var bc={},yc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),wc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),_c=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&yc(r,t,i[n]);return wc(r,t),r}}();Object.defineProperty(bc,"__esModule",{value:!0}),bc.Chrome74=void 0;const Sc=_c(gi),Cc=ts,Rc=_c(xs),kc=_c(Ms),Tc=_c(wa),Pc=_c(Ea),Oc=_c(Da),Ec=Ps,Dc=Ia,xc=Aa,Ic=Xa,Mc=new Cc.Logger("Chrome74"),jc={OS:1024,MIS:1024};class Lc extends Dc.HandlerInterface{static createFactory(){return()=>new Lc}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome74"}close(){if(Mc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Mc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Sc.parse(t.sdp),i=Tc.extractRtpCapabilities({sdpObject:r});return Oc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Mc.debug("getNativeSctpCapabilities()"),{numStreams:jc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Mc.debug("run()"),this._direction=e,this._remoteSdp=new xc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:kc.getSendingRtpParameters("audio",d),video:kc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:kc.getSendingRemoteRtpParameters("audio",d),video:kc.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):(Mc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),Mc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Mc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Mc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Mc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const n=Rc.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=kc.reduceCodecs(n.codecs,i);const s=Rc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=kc.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let c,d=await this._pc.createOffer(),l=Sc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let u=!1;const p=(0,Ic.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(Mc.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=Sc.parse(d.sdp),c=l.media[o.idx],Pc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:Sc.write(l)}),Mc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const h=a.mid;if(n.mid=h,l=Sc.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=Tc.getCname({offerMediaObject:c}),t)if(1===t.length){let e=Pc.getRtpEncodings({offerMediaObject:c});Object.assign(e[0],t[0]),u&&(e=[e[0]]),n.encodings=e}else n.encodings=t;else n.encodings=Pc.getRtpEncodings({offerMediaObject:c});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Mc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Mc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Mc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Mc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Mc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Mc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Mc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Mc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Mc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Mc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%jc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Sc.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Mc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Mc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Sc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);Tc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Sc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Mc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Mc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Mc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Sc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Sc.parse(this._pc.localDescription.sdp));const r=Tc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ec.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}bc.Chrome74=Lc;var Ac={},Nc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Bc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Fc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Nc(r,t,i[n]);return Bc(r,t),r}}();Object.defineProperty(Ac,"__esModule",{value:!0}),Ac.Chrome70=void 0;const zc=Fc(gi),Vc=ts,Uc=Fc(xs),$c=Fc(Ms),Gc=Fc(wa),qc=Fc(Ea),Hc=Ia,Wc=Aa,Kc=Xa,Jc=new Vc.Logger("Chrome70"),Qc={OS:1024,MIS:1024};class Yc extends Hc.HandlerInterface{static createFactory(){return()=>new Yc}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome70"}close(){if(Jc.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Jc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=zc.parse(t.sdp);return Gc.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Jc.debug("getNativeSctpCapabilities()"),{numStreams:Qc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Jc.debug("run()"),this._direction=e,this._remoteSdp=new Wc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:$c.getSendingRtpParameters("audio",d),video:$c.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:$c.getSendingRemoteRtpParameters("audio",d),video:$c.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Jc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Jc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Jc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Jc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Jc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Jc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const n=Uc.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=$c.reduceCodecs(n.codecs,i);const s=Uc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=$c.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let c,d=await this._pc.createOffer(),l=zc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),t&&t.length>1&&(Jc.debug("send() | enabling legacy simulcast"),l=zc.parse(d.sdp),c=l.media[o.idx],qc.addLegacySimulcast({offerMediaObject:c,numStreams:t.length}),d={type:"offer",sdp:zc.write(l)});let u=!1;const p=(0,Kc.parse)((t??[{}])[0].scalabilityMode);if(t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(Jc.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=zc.parse(d.sdp),c=l.media[o.idx],qc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:zc.write(l)}),Jc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d),t){Jc.debug("send() | applying given encodings");const e=a.sender.getParameters();for(let r=0;r<(e.encodings??[]).length;++r){const i=e.encodings[r],n=t[r];if(!n)break;e.encodings[r]=Object.assign(i,n)}await a.sender.setParameters(e)}const h=a.mid;if(n.mid=h,l=zc.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=Gc.getCname({offerMediaObject:c}),n.encodings=qc.getRtpEncodings({offerMediaObject:c}),t)for(let e=0;e<n.encodings.length;++e)t[e]&&Object.assign(n.encodings[e],t[e]);if(u&&(n.encodings=[n.encodings[0]]),n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Jc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){this.assertSendDirection(),Jc.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Jc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Jc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Jc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),Jc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Jc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Jc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Jc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Jc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Qc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=zc.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Jc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Jc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=zc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);Gc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:zc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Jc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Jc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Jc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Jc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=zc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Jc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=zc.parse(this._pc.localDescription.sdp));const r=Gc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Ac.Chrome70=Yc;var Xc={},Zc={};Object.defineProperty(Zc,"__esModule",{value:!0}),Zc.getRtpEncodings=function({offerMediaObject:e,track:t}){const r=new Set;for(const i of e.ssrcs||[]){if("msid"!==i.attribute)continue;if(i.value.split(" ")[1]===t.id){const e=i.id;r.add(e)}}if(0===r.size)throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);const i=new Map;for(const t of e.ssrcGroups||[]){if("FID"!==t.semantics)continue;let[e,n]=t.ssrcs.split(/\s+/);e=Number(e),n=Number(n),r.has(e)&&(r.delete(e),r.delete(n),i.set(e,n))}for(const e of r)i.set(e,null);const n=[];for(const[e,t]of i){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},Zc.addLegacySimulcast=function({offerMediaObject:e,track:t,numStreams:r}){if(r<=1)throw new TypeError("numStreams must be greater than 1");let i,n,s;if(!(e.ssrcs||[]).find(e=>{if("msid"!==e.attribute)return!1;return e.value.split(" ")[1]===t.id&&(i=e.id,s=e.value.split(" ")[0],!0)}))throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);(e.ssrcGroups||[]).some(e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===i&&(n=Number(t[1]),!0)});const o=e.ssrcs.find(e=>"cname"===e.attribute&&e.id===i);if(!o)throw new Error(`a=ssrc line with cname information not found [track.id:${t.id}]`);const a=o.value,c=[],d=[];for(let e=0;e<r;++e)c.push(i+e),n&&d.push(n+e);e.ssrcGroups=e.ssrcGroups||[],e.ssrcs=e.ssrcs||[],e.ssrcGroups.push({semantics:"SIM",ssrcs:c.join(" ")});for(const r of c)e.ssrcs.push({id:r,attribute:"cname",value:a}),e.ssrcs.push({id:r,attribute:"msid",value:`${s} ${t.id}`});for(let r=0;r<d.length;++r){const i=c[r],n=d[r];e.ssrcs.push({id:n,attribute:"cname",value:a}),e.ssrcs.push({id:n,attribute:"msid",value:`${s} ${t.id}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${i} ${n}`})}};var ed=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),td=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),rd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ed(r,t,i[n]);return td(r,t),r}}();Object.defineProperty(Xc,"__esModule",{value:!0}),Xc.Chrome67=void 0;const id=rd(gi),nd=ts,sd=rd(xs),od=rd(Ms),ad=rd(wa),cd=rd(Zc),dd=Ia,ld=Aa,ud=new nd.Logger("Chrome67"),pd={OS:1024,MIS:1024};class hd extends dd.HandlerInterface{static createFactory(){return()=>new hd}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome67"}close(){if(ud.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){ud.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=id.parse(t.sdp);return ad.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return ud.debug("getNativeSctpCapabilities()"),{numStreams:pd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){ud.debug("run()"),this._direction=e,this._remoteSdp=new ld.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:od.getSendingRtpParameters("audio",d),video:od.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:od.getSendingRemoteRtpParameters("audio",d),video:od.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(ud.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){ud.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(ud.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ud.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ud.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),ud.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&ud.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=id.parse(s.sdp);const a=sd.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=od.reduceCodecs(a.codecs);const c=sd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=od.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(ud.debug("send() | enabling simulcast"),o=id.parse(s.sdp),n=o.media.find(e=>"video"===e.type),cd.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:id.write(o)}),ud.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=id.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=ad.getCname({offerMediaObject:n}),a.encodings=cd.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find(t=>t.track===e);return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection(),ud.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");this._pc.removeTrack(t),t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();ud.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void ud.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?ud.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ud.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),ud.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),ud.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};ud.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%pd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=id.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),ud.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;ud.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=id.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find(e=>String(e.mid)===i);ad.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:id.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),ud.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=i,o=e,a=this._pc.getReceivers().find(e=>e.track&&e.track.id===s);if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(s,{mid:o,rtpParameters:n,rtpReceiver:a}),t.push({localId:s,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){ud.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ud.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};ud.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=id.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}ud.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=id.parse(this._pc.localDescription.sdp));const r=ad.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Xc.Chrome67=hd;var fd={},md=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),gd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),vd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&md(r,t,i[n]);return gd(r,t),r}}();Object.defineProperty(fd,"__esModule",{value:!0}),fd.Chrome55=void 0;const bd=vd(gi),yd=ts,wd=Ps,_d=vd(xs),Sd=vd(Ms),Cd=vd(wa),Rd=vd(Zc),kd=Ia,Td=Aa,Pd=new yd.Logger("Chrome55"),Od={OS:1024,MIS:1024};class Ed extends kd.HandlerInterface{static createFactory(){return()=>new Ed}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome55"}close(){if(Pd.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Pd.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=bd.parse(t.sdp);return Cd.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Pd.debug("getNativeSctpCapabilities()"),{numStreams:Od}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Pd.debug("run()"),this._direction=e,this._remoteSdp=new Td.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Sd.getSendingRtpParameters("audio",d),video:Sd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Sd.getSendingRemoteRtpParameters("audio",d),video:Sd.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Pd.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Pd.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Pd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Pd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Pd.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Pd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Pd.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=bd.parse(s.sdp);const a=_d.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Sd.reduceCodecs(a.codecs);const c=_d.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Sd.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Pd.debug("send() | enabling simulcast"),o=bd.parse(s.sdp),n=o.media.find(e=>"video"===e.type),Rd.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:bd.write(o)}),Pd.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=bd.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=Cd.getCname({offerMediaObject:n}),a.encodings=Rd.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),Pd.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();Pd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Pd.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new wd.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new wd.UnsupportedError(" not implemented")}async setRtpEncodingParameters(e,t){throw new wd.UnsupportedError("not supported")}async getSenderStats(e){throw new wd.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Pd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Od.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=bd.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Pd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Pd.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=bd.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find(e=>String(e.mid)===i);Cd.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:bd.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Pd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=r.streamId??n.rtcp.cname,c=this._pc.getRemoteStreams().find(e=>e.id===a).getTrackById(o);if(!c)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n}),t.push({localId:o,track:c})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Pd.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pd.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new wd.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Pd.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=bd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Pd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=bd.parse(this._pc.localDescription.sdp));const r=Cd.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}fd.Chrome55=Ed;var Dd={},xd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Id=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Md=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&xd(r,t,i[n]);return Id(r,t),r}}();Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.Firefox120=void 0;const jd=Md(gi),Ld=ts,Ad=Ps,Nd=Md(xs),Bd=Md(Ms),Fd=Md(wa),zd=Md(Ea),Vd=Ia,Ud=Aa,$d=Xa,Gd=new Ld.Logger("Firefox120"),qd={OS:16,MIS:2048};class Hd extends Vd.HandlerInterface{static createFactory(){return()=>new Hd}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox120"}close(){if(Gd.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Gd.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const n=jd.parse(i.sdp);return Fd.extractRtpCapabilities({sdpObject:n})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return Gd.debug("getNativeSctpCapabilities()"),{numStreams:qd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Gd.debug("run()"),this._direction=e,this._remoteSdp=new Ud.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:Bd.getSendingRtpParameters("audio",d),video:Bd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Bd.getSendingRemoteRtpParameters("audio",d),video:Bd.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Gd.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){throw this.assertNotClosed(),new Ad.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Gd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Gd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Gd.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=Nd.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Bd.reduceCodecs(s.codecs,i);const o=Nd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Bd.reduceCodecs(o.codecs,i);const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(a.sender);const c=await this._pc.createOffer();let d=jd.parse(c.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});const l=(0,$d.parse)((t??[{}])[0].scalabilityMode);Gd.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);const u=a.mid;s.mid=u,d=jd.parse(this._pc.localDescription.sdp);const p=d.media[d.media.length-1];if(s.rtcp.cname=Fd.getCname({offerMediaObject:p}),t)if(1===t.length){const e=zd.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=zd.getRtpEncodings({offerMediaObject:p});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${l.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:p,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return Gd.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,a),{localId:u,rtpParameters:s,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Gd.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();Gd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Gd.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Gd.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Gd.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Gd.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Gd.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Gd.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Gd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%qd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=jd.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Gd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Gd.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=jd.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find(e=>String(e.mid)===o);Fd.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:jd.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Gd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Gd.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Gd.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Gd.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Gd.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Gd.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Gd.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Gd.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=jd.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Gd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=jd.parse(this._pc.localDescription.sdp));const r=Fd.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ad.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Dd.Firefox120=Hd;var Wd={},Kd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Jd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Qd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Kd(r,t,i[n]);return Jd(r,t),r}}();Object.defineProperty(Wd,"__esModule",{value:!0}),Wd.Firefox60=void 0;const Yd=Qd(gi),Xd=ts,Zd=Ps,el=Qd(xs),tl=Qd(Ms),rl=Qd(wa),il=Qd(Ea),nl=Ia,sl=Aa,ol=Xa,al=new Xd.Logger("Firefox60"),cl={OS:16,MIS:2048};class dl extends nl.HandlerInterface{static createFactory(){return()=>new dl}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox60"}close(){if(al.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){al.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"});const i=e.addTransceiver(r,{direction:"sendrecv"}),n=i.sender.getParameters(),s=[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}];n.encodings=s,await i.sender.setParameters(n);const o=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const a=Yd.parse(o.sdp);return rl.extractRtpCapabilities({sdpObject:a})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return al.debug("getNativeSctpCapabilities()"),{numStreams:cl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),al.debug("run()"),this._direction=e,this._remoteSdp=new sl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:tl.getSendingRtpParameters("audio",d),video:tl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:tl.getSendingRemoteRtpParameters("audio",d),video:tl.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(al.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){throw this.assertNotClosed(),new Zd.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),al.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});al.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();al.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),al.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&((t=el.clone(t)).forEach((e,t)=>{e.rid=`r${t}`}),t.reverse());const n=el.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=tl.reduceCodecs(n.codecs,i);const s=el.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=tl.reduceCodecs(s.codecs,i);const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});if(t){const e=o.sender.getParameters();e.encodings=t,await o.sender.setParameters(e)}const a=await this._pc.createOffer();let c=Yd.parse(a.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const d=(0,ol.parse)((t??[{}])[0].scalabilityMode);al.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const l=o.mid;n.mid=l,c=Yd.parse(this._pc.localDescription.sdp);const u=c.media[c.media.length-1];if(n.rtcp.cname=rl.getCname({offerMediaObject:u}),t)if(1===t.length){const e=il.getRtpEncodings({offerMediaObject:u});Object.assign(e[0],t[0]),n.encodings=e}else n.encodings=t.reverse();else n.encodings=il.getRtpEncodings({offerMediaObject:u});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${d.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:u,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const p={type:"answer",sdp:this._remoteSdp.getSdp()};return al.debug("send() | calling pc.setRemoteDescription() [answer:%o]",p),await this._pc.setRemoteDescription(p),this._mapMidTransceiver.set(l,o),{localId:l,rtpParameters:n,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),al.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();al.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),al.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();al.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),al.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();al.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?al.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):al.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),al.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();t=i.encodings.length-1-t,i.encodings.forEach((e,r)=>{e.active=r>=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();al.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),al.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();al.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};al.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%cl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Yd.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),al.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;al.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Yd.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find(e=>String(e.mid)===o);rl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:Yd.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),al.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){al.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();al.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){al.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();al.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){al.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();al.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};al.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Yd.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}al.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Yd.parse(this._pc.localDescription.sdp));const r=rl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Zd.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Wd.Firefox60=dl;var ll={},ul=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),pl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),hl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ul(r,t,i[n]);return pl(r,t),r}}();Object.defineProperty(ll,"__esModule",{value:!0});var fl=ll.Safari12=void 0;const ml=hl(gi),gl=ts,vl=hl(xs),bl=hl(Ms),yl=hl(wa),wl=hl(Ea),_l=hl(Da),Sl=Ps,Cl=Ia,Rl=Aa,kl=Xa,Tl=new gl.Logger("Safari12"),Pl={OS:1024,MIS:1024};class Ol extends Cl.HandlerInterface{static createFactory(){return()=>new Ol}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari12"}close(){if(Tl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Tl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=ml.parse(t.sdp),i=yl.extractRtpCapabilities({sdpObject:r});return _l.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Tl.debug("getNativeSctpCapabilities()"),{numStreams:Pl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Tl.debug("run()"),this._direction=e,this._remoteSdp=new Rl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:bl.getSendingRtpParameters("audio",d),video:bl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:bl.getSendingRemoteRtpParameters("audio",d),video:bl.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Tl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){this.assertNotClosed(),Tl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Tl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Tl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Tl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=vl.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=bl.reduceCodecs(s.codecs,i);const o=vl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=bl.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=ml.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const p=(0,kl.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(Tl.debug("send() | enabling legacy simulcast"),u=ml.parse(l.sdp),d=u.media[a.idx],wl.addLegacySimulcast({offerMediaObject:d,numStreams:t.length}),l={type:"offer",sdp:ml.write(u)}),Tl.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);const h=c.mid;if(s.mid=h,u=ml.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=yl.getCname({offerMediaObject:d}),s.encodings=wl.getRtpEncodings({offerMediaObject:d}),t)for(let e=0;e<s.encodings.length;++e)t[e]&&Object.assign(s.encodings[e],t[e]);if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Tl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,c),{localId:h,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Tl.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Tl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Tl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Tl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Tl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Tl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Tl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Tl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Tl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Pl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=ml.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Tl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Tl.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=ml.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);yl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:ml.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Tl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Tl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Tl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Tl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Tl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Tl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Tl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Tl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=ml.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Tl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ml.parse(this._pc.localDescription.sdp));const r=yl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Sl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}fl=ll.Safari12=Ol;var El={},Dl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),xl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Il=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Dl(r,t,i[n]);return xl(r,t),r}}();Object.defineProperty(El,"__esModule",{value:!0}),El.Safari11=void 0;const Ml=Il(gi),jl=ts,Ll=Il(xs),Al=Il(Ms),Nl=Il(wa),Bl=Il(Zc),Fl=Ia,zl=Aa,Vl=new jl.Logger("Safari11"),Ul={OS:1024,MIS:1024};class $l extends Fl.HandlerInterface{static createFactory(){return()=>new $l}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari11"}close(){if(Vl.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Vl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Ml.parse(t.sdp);return Nl.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Vl.debug("getNativeSctpCapabilities()"),{numStreams:Ul}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Vl.debug("run()"),this._direction=e,this._remoteSdp=new zl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Al.getSendingRtpParameters("audio",d),video:Al.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Al.getSendingRemoteRtpParameters("audio",d),video:Al.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Vl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Vl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Vl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Vl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Vl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Vl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Vl.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=Ml.parse(s.sdp);const a=Ll.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Al.reduceCodecs(a.codecs);const c=Ll.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Al.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Vl.debug("send() | enabling simulcast"),o=Ml.parse(s.sdp),n=o.media.find(e=>"video"===e.type),Bl.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Ml.write(o)}),Vl.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Ml.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=Nl.getCname({offerMediaObject:n}),a.encodings=Bl.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find(t=>t.track===e);return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();Vl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Vl.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Vl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Vl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),Vl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Vl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Vl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ul.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ml.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Vl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Vl.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Ml.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find(e=>String(e.mid)===i);Nl.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Ml.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Vl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=this._pc.getReceivers().find(e=>e.track&&e.track.id===o);if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n,rtpReceiver:a}),t.push({localId:o,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Vl.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Vl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async pauseReceiving(e){}async resumeReceiving(e){}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Vl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ml.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Vl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ml.parse(this._pc.localDescription.sdp));const r=Nl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}El.Safari11=$l;var Gl={},ql={},Hl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Wl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Kl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Hl(r,t,i[n]);return Wl(r,t),r}}();Object.defineProperty(ql,"__esModule",{value:!0}),ql.getCapabilities=function(){const e=RTCRtpReceiver.getCapabilities(),t=Jl.clone(e);for(const e of t.codecs??[]){if(e.channels=e.numChannels,delete e.numChannels,e.mimeType=e.mimeType??`${e.kind}/${e.name}`,e.parameters){const t=e.parameters;t.apt&&(t.apt=Number(t.apt)),t["packetization-mode"]&&(t["packetization-mode"]=Number(t["packetization-mode"]))}for(const t of e.rtcpFeedback??[])t.parameter||(t.parameter="")}return t},ql.mangleRtpParameters=function(e){const t=Jl.clone(e);t.mid&&(t.muxId=t.mid,delete t.mid);for(const e of t.codecs)e.channels&&(e.numChannels=e.channels,delete e.channels),e.mimeType&&!e.name&&(e.name=e.mimeType.split("/")[1]),delete e.mimeType;return t};const Jl=Kl(xs);var Ql=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Yl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Xl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Ql(r,t,i[n]);return Yl(r,t),r}}();Object.defineProperty(Gl,"__esModule",{value:!0}),Gl.Edge11=void 0;const Zl=ts,eu=Ps,tu=Xl(xs),ru=Xl(Ms),iu=Xl(ql),nu=Ia,su=new Zl.Logger("Edge11");class ou extends nu.HandlerInterface{static createFactory(){return()=>new ou}constructor(){super(),this._rtpSenders=new Map,this._rtpReceivers=new Map,this._nextSendLocalId=0,this._transportReady=!1}get name(){return"Edge11"}close(){su.debug("close()");try{this._iceGatherer.close()}catch(e){}try{this._iceTransport.stop()}catch(e){}try{this._dtlsTransport.stop()}catch(e){}for(const e of this._rtpSenders.values())try{e.stop()}catch(e){}for(const e of this._rtpReceivers.values())try{e.stop()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){return su.debug("getNativeRtpCapabilities()"),iu.getCapabilities()}async getNativeSctpCapabilities(){return su.debug("getNativeSctpCapabilities()"),{numStreams:{OS:0,MIS:0}}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){su.debug("run()"),this._sendingRtpParametersByKind={audio:ru.getSendingRtpParameters("audio",d),video:ru.getSendingRtpParameters("video",d)},this._remoteIceParameters=t,this._remoteIceCandidates=r,this._remoteDtlsParameters=i,this._cname=`CNAME-${tu.generateRandomNumber()}`,this.setIceGatherer({iceServers:s,iceTransportPolicy:o}),this.setIceTransport(),this.setDtlsTransport()}async updateIceServers(e){throw new eu.UnsupportedError("not supported")}async restartIce(e){if(su.debug("restartIce()"),this._remoteIceParameters=e,this._transportReady){su.debug("restartIce() | calling iceTransport.start()"),this._iceTransport.start(this._iceGatherer,e,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({})}}async getTransportStats(){return this._iceTransport.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){su.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),su.debug("send() | calling new RTCRtpSender()");const n=new RTCRtpSender(e,this._dtlsTransport),s=tu.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=ru.reduceCodecs(s.codecs,i);const o=s.codecs.some(e=>/.+\/rtx$/i.test(e.mimeType));t||(t=[{}]);for(const e of t)e.ssrc=tu.generateRandomNumber(),o&&(e.rtx={ssrc:tu.generateRandomNumber()});s.encodings=t,s.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const a=iu.mangleRtpParameters(s);su.debug("send() | calling rtpSender.send() [params:%o]",a),await n.send(a);const c=String(this._nextSendLocalId);return this._nextSendLocalId++,this._rtpSenders.set(c,n),{localId:c,rtpParameters:s,rtpSender:n}}async stopSending(e){su.debug("stopSending() [localId:%s]",e);const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");this._rtpSenders.delete(e);try{su.debug("stopSending() | calling rtpSender.stop()"),t.stop()}catch(e){throw su.warn("stopSending() | rtpSender.stop() failed:%o",e),e}}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){t?su.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):su.debug("replaceTrack() [localId:%s, no track]",e);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");r.setTrack(t)}async setMaxSpatialLayer(e,t){su.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.setParameters(i)}async setRtpEncodingParameters(e,t){su.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.setParameters(i)}async getSenderStats(e){const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");return t.getStats()}async sendDataChannel(e){throw new eu.UnsupportedError("not implemented")}async receive(e){const t=[];for(const t of e){const{trackId:e,kind:r}=t;su.debug("receive() [trackId:%s, kind:%s]",e,r)}this._transportReady||await this.setupTransport({localDtlsRole:"server"});for(const r of e){const{trackId:e,kind:i,rtpParameters:n}=r;su.debug("receive() | calling new RTCRtpReceiver()");const s=new RTCRtpReceiver(this._dtlsTransport,i);s.addEventListener("error",e=>{su.error('rtpReceiver "error" event [event:%o]',e)});const o=iu.mangleRtpParameters(n);su.debug("receive() | calling rtpReceiver.receive() [params:%o]",o),await s.receive(o);const a=e;this._rtpReceivers.set(a,s),t.push({localId:a,track:s.track,rtpReceiver:s})}return t}async stopReceiving(e){for(const t of e){su.debug("stopReceiving() [localId:%s]",t);const e=this._rtpReceivers.get(t);if(!e)throw new Error("RTCRtpReceiver not found");this._rtpReceivers.delete(t);try{su.debug("stopReceiving() | calling rtpReceiver.stop()"),e.stop()}catch(e){su.warn("stopReceiving() | rtpReceiver.stop() failed:%o",e)}}}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){const t=this._rtpReceivers.get(e);if(!t)throw new Error("RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel(e){throw new eu.UnsupportedError("not implemented")}setIceGatherer({iceServers:e,iceTransportPolicy:t}){const r=new RTCIceGatherer({iceServers:e??[],gatherPolicy:t??"all"});r.addEventListener("error",e=>{su.error('iceGatherer "error" event [event:%o]',e)});try{r.gather()}catch(e){su.debug("setIceGatherer() | iceGatherer.gather() failed: %s",e.toString())}this._iceGatherer=r}setIceTransport(){const e=new RTCIceTransport(this._iceGatherer);e.addEventListener("statechange",()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}),e.addEventListener("icestatechange",()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}),e.addEventListener("candidatepairchange",e=>{su.debug('iceTransport "candidatepairchange" event [pair:%o]',e.pair)}),this._iceTransport=e}setDtlsTransport(){const e=new RTCDtlsTransport(this._iceTransport);e.addEventListener("statechange",()=>{su.debug('dtlsTransport "statechange" event [state:%s]',e.state)}),e.addEventListener("dtlsstatechange",()=>{su.debug('dtlsTransport "dtlsstatechange" event [state:%s]',e.state),"closed"===e.state&&this.emit("@connectionstatechange","closed")}),e.addEventListener("error",e=>{su.error('dtlsTransport "error" event [event:%o]',e)}),this._dtlsTransport=e}async setupTransport({localDtlsRole:e}){su.debug("setupTransport()");const t=this._dtlsTransport.getLocalParameters();t.role=e,await new Promise((e,r)=>{this.safeEmit("@connect",{dtlsParameters:t},e,r)}),this._iceTransport.start(this._iceGatherer,this._remoteIceParameters,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({}),this._remoteDtlsParameters.fingerprints=this._remoteDtlsParameters.fingerprints.filter(e=>"sha-256"===e.algorithm||"sha-384"===e.algorithm||"sha-512"===e.algorithm),this._dtlsTransport.start(this._remoteDtlsParameters),this._transportReady=!0}}Gl.Edge11=ou;var au={},cu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),du=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),lu=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&cu(r,t,i[n]);return du(r,t),r}}();Object.defineProperty(au,"__esModule",{value:!0}),au.ReactNativeUnifiedPlan=void 0;const uu=lu(gi),pu=ts,hu=lu(xs),fu=lu(Ms),mu=lu(wa),gu=lu(Ea),vu=lu(Da),bu=Ps,yu=Ia,wu=Aa,_u=Xa,Su=new pu.Logger("ReactNativeUnifiedPlan"),Cu={OS:1024,MIS:1024};class Ru extends yu.HandlerInterface{static createFactory(){return()=>new Ru}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNativeUnifiedPlan"}close(){if(Su.debug("close()"),!this._closed){if(this._closed=!0,this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Su.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=uu.parse(t.sdp),i=mu.extractRtpCapabilities({sdpObject:r});return vu.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Su.debug("getNativeSctpCapabilities()"),{numStreams:Cu}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Su.debug("run()"),this._direction=e,this._remoteSdp=new wu.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:fu.getSendingRtpParameters("audio",d),video:fu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:fu.getSendingRemoteRtpParameters("audio",d),video:fu.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Su.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){this.assertNotClosed(),Su.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Su.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Su.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Su.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Su.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=hu.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=fu.reduceCodecs(s.codecs,i);const o=hu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=fu.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=uu.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let p=!1;const h=(0,_u.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===s.codecs[0].mimeType.toLowerCase()&&(Su.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,u=uu.parse(l.sdp),d=u.media[a.idx],gu.addLegacySimulcast({offerMediaObject:d,numStreams:h.spatialLayers}),l={type:"offer",sdp:uu.write(u)}),Su.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);let f=c.mid??void 0;if(f||Su.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),s.mid=f,u=uu.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=mu.getCname({offerMediaObject:d}),t)if(1===t.length){let e=gu.getRtpEncodings({offerMediaObject:d});Object.assign(e[0],t[0]),p&&(e=[e[0]]),s.encodings=e}else s.encodings=t;else s.encodings=gu.getRtpEncodings({offerMediaObject:d});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Su.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),f||(f=c.mid,s.mid=f),this._mapMidTransceiver.set(f,c),{localId:f,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Su.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Su.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Su.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Su.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Su.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Su.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Su.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Su.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Su.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Su.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Su.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Su.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Su.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Cu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=uu.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Su.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Su.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=uu.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);mu.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:uu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Su.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Su.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Su.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Su.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Su.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Su.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Su.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Su.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=uu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Su.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=uu.parse(this._pc.localDescription.sdp));const r=mu.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new bu.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}au.ReactNativeUnifiedPlan=Ru;var ku={},Tu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Pu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ou=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Tu(r,t,i[n]);return Pu(r,t),r}}();Object.defineProperty(ku,"__esModule",{value:!0}),ku.ReactNative=void 0;const Eu=Ou(gi),Du=ts,xu=Ps,Iu=Ou(xs),Mu=Ou(Ms),ju=Ou(wa),Lu=Ou(Zc),Au=Ia,Nu=Aa,Bu=new Du.Logger("ReactNative"),Fu={OS:1024,MIS:1024};class zu extends Au.HandlerInterface{static createFactory(){return()=>new zu}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNative"}close(){if(Bu.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Bu.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Eu.parse(t.sdp);return ju.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Bu.debug("getNativeSctpCapabilities()"),{numStreams:Fu}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Bu.debug("run()"),this._direction=e,this._remoteSdp=new Nu.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Mu.getSendingRtpParameters("audio",d),video:Mu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Mu.getSendingRemoteRtpParameters("audio",d),video:Mu.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Bu.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Bu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Bu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Bu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Bu.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Bu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Bu.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=Eu.parse(s.sdp);const a=Iu.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Mu.reduceCodecs(a.codecs);const c=Iu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Mu.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Bu.debug("send() | enabling simulcast"),o=Eu.parse(s.sdp),n=o.media.find(e=>"video"===e.type),Lu.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Eu.write(o)}),Bu.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Eu.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=ju.getCname({offerMediaObject:n}),a.encodings=Lu.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&("video/vp8"===a.codecs[0].mimeType.toLowerCase()||"video/h264"===a.codecs[0].mimeType.toLowerCase()))for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),Bu.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();Bu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Bu.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new xu.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new xu.UnsupportedError("not implemented")}async setRtpEncodingParameters(e,t){throw new xu.UnsupportedError("not implemented")}async getSenderStats(e){throw new xu.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Bu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Fu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Eu.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Bu.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n}=t;Bu.debug("receive() [trackId:%s, kind:%s]",e,i);const s=i;let o=t.streamId??n.rtcp.cname;Bu.debug("receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc"),o+=`-hack-${Iu.generateRandomNumber()}`,r.set(e,o),this._remoteSdp.receive({mid:s,kind:i,offerRtpParameters:n,streamId:o,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Eu.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,n=s.media.find(e=>String(e.mid)===i);ju.applyCodecParameters({offerRtpParameters:r,answerMediaObject:n})}n={type:"answer",sdp:Eu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Bu.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{kind:e,trackId:n,rtpParameters:s}=i,o=n,a=e,c=r.get(n),d=this._pc.getRemoteStreams().find(e=>e.id===c).getTrackById(o);if(!d)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:a,rtpParameters:s}),t.push({localId:o,track:d})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Bu.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Bu.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new xu.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Bu.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Eu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Bu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Eu.parse(this._pc.localDescription.sdp));const r=ju.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}ku.ReactNative=zu;var Vu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Uu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$u=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Vu(r,t,i[n]);return Uu(r,t),r}}();Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.Device=void 0,Xn.detectDevice=lp;const Gu=es,qu=ts,Hu=as,Wu=Ps,Ku=$u(xs),Ju=$u(Ms),Qu=Co,Yu=ya,Xu=bc,Zu=Ac,ep=Xc,tp=fd,rp=Dd,ip=Wd,np=ll,sp=El,op=Gl,ap=au,cp=ku,dp=new qu.Logger("Device");function lp(e){if(!e&&"object"==typeof navigator&&"ReactNative"===navigator.product)return dp.debug("detectDevice() | React-Native detected"),"undefined"==typeof RTCPeerConnection?void dp.warn("detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?"):"undefined"!=typeof RTCRtpTransceiver?(dp.debug("detectDevice() | ReactNative UnifiedPlan handler chosen"),"ReactNativeUnifiedPlan"):(dp.debug("detectDevice() | ReactNative PlanB handler chosen"),"ReactNative");if(e||"object"==typeof navigator&&"string"==typeof navigator.userAgent){e??(e=navigator.userAgent);const t=new Gu.UAParser(e);dp.debug("detectDevice() | browser detected [userAgent:%s, parsed:%o]",e,t.getResult());const r=t.getBrowser(),i=r.name?.toLowerCase(),n=parseInt(r.major??"0"),s=t.getEngine(),o=s.name?.toLowerCase(),a=t.getOS(),c=a.name?.toLowerCase(),d=parseFloat(a.version??"0"),l=t.getDevice(),u=l.model?.toLowerCase(),p="ios"===c||"ipad"===u,h=i&&["chrome","chromium","mobile chrome","chrome webview","chrome headless"].includes(i),f=i&&["firefox","mobile firefox","mobile focus"].includes(i),m=i&&["safari","mobile safari"].includes(i),g=i&&["edge"].includes(i);if((h||g)&&!p&&n>=111)return"Chrome111";if(h&&!p&&n>=74||g&&!p&&n>=88)return"Chrome74";if(h&&!p&&n>=70)return"Chrome70";if(h&&!p&&n>=67)return"Chrome67";if(h&&!p&&n>=55)return"Chrome55";if(f&&!p&&n>=120)return"Firefox120";if(f&&!p&&n>=60)return"Firefox60";if(f&&p&&d>=14.3)return"Safari12";if(m&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(m&&n>=11)return"Safari11";if(g&&!p&&n>=11&&n<=18)return"Edge11";if("webkit"===o&&p&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if("blink"===o){const t=e.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(t){const e=Number(t[1]);return e>=111?"Chrome111":e>=74?"Chrome74":e>=70?"Chrome70":e>=67?"Chrome67":"Chrome55"}return"Chrome111"}return void dp.warn("detectDevice() | browser not supported [name:%s, version:%s]",i,n)}dp.warn("detectDevice() | unknown device")}Xn.Device=class{constructor({handlerName:e,handlerFactory:t}={}){if(this._loaded=!1,this._observer=new Hu.EnhancedEventEmitter,dp.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)dp.debug("constructor() | handler given: %s",e);else{if(!(e=lp()))throw new Wu.UnsupportedError("device not supported");dp.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=Yu.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=Xu.Chrome74.createFactory();break;case"Chrome70":this._handlerFactory=Zu.Chrome70.createFactory();break;case"Chrome67":this._handlerFactory=ep.Chrome67.createFactory();break;case"Chrome55":this._handlerFactory=tp.Chrome55.createFactory();break;case"Firefox120":this._handlerFactory=rp.Firefox120.createFactory();break;case"Firefox60":this._handlerFactory=ip.Firefox60.createFactory();break;case"Safari12":this._handlerFactory=np.Safari12.createFactory();break;case"Safari11":this._handlerFactory=sp.Safari11.createFactory();break;case"Edge11":this._handlerFactory=op.Edge11.createFactory();break;case"ReactNativeUnifiedPlan":this._handlerFactory=ap.ReactNativeUnifiedPlan.createFactory();break;case"ReactNative":this._handlerFactory=cp.ReactNative.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const r=this._handlerFactory();this._handlerName=r.name,r.close(),this._extendedRtpCapabilities=void 0,this._recvRtpCapabilities=void 0,this._canProduceByKind={audio:!1,video:!1},this._sctpCapabilities=void 0}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e}){let t;dp.debug("load() [routerRtpCapabilities:%o]",e);try{if(this._loaded)throw new Wu.InvalidStateError("already loaded");const r=Ku.clone(e);Ju.validateRtpCapabilities(r),t=this._handlerFactory();const i=await t.getNativeRtpCapabilities();dp.debug("load() | got native RTP capabilities:%o",i);const n=Ku.clone(i);Ju.validateRtpCapabilities(n),this._extendedRtpCapabilities=Ju.getExtendedRtpCapabilities(n,r),dp.debug("load() | got extended RTP capabilities:%o",this._extendedRtpCapabilities),this._canProduceByKind.audio=Ju.canSend("audio",this._extendedRtpCapabilities),this._canProduceByKind.video=Ju.canSend("video",this._extendedRtpCapabilities),this._recvRtpCapabilities=Ju.getRecvRtpCapabilities(this._extendedRtpCapabilities),Ju.validateRtpCapabilities(this._recvRtpCapabilities),dp.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._sctpCapabilities=await t.getNativeSctpCapabilities(),dp.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),Ju.validateSctpCapabilities(this._sctpCapabilities),dp.debug("load() succeeded"),this._loaded=!0,t.close()}catch(e){throw t&&t.close(),e}}canProduce(e){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return dp.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return dp.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l}){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(i))throw new TypeError("missing iceCandidates");if("object"!=typeof n)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(l&&"object"!=typeof l)throw new TypeError("if given, appData must be an object");const u=new Qu.Transport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:this._handlerFactory,extendedRtpCapabilities:this._extendedRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}};var up={},pp={};Object.defineProperty(pp,"__esModule",{value:!0});var hp={};Object.defineProperty(hp,"__esModule",{value:!0}),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__exportStar||function(e,r){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(r,i)||t(r,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(Xn,e),r(Co,e),r(Ao,e),r(Vo,e),r(Ho,e),r(Yo,e),r(pp,e),r(hp,e),r(Ia,e),r(Ps,e)}(up),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(i){if(i&&i.__esModule)return i;var n={};if(null!=i)for(var s=e(i),o=0;o<s.length;o++)"default"!==s[o]&&t(n,i,s[o]);return r(n,i),n}}(),n=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.parseScalabilityMode=e.detectDevice=e.Device=e.version=e.types=void 0;const s=n(Yn);e.debug=s.default;const o=Xn;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return o.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return o.detectDevice}});const c=i(up);e.types=c,e.version="3.7.18";var d=Xa;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return d.parse}})}(Wn);var fp={exports:{}};!function(e,t){!function(r,i){var n="function",s="undefined",o="object",a="string",c="major",d="model",l="name",u="type",p="vendor",h="version",f="architecture",m="console",g="mobile",v="tablet",b="smarttv",y="wearable",w="embedded",_="Amazon",S="Apple",C="ASUS",R="BlackBerry",k="Browser",T="Chrome",P="Firefox",O="Google",E="Huawei",D="LG",x="Microsoft",I="Motorola",M="Opera",j="Samsung",L="Sharp",A="Sony",N="Xiaomi",B="Zebra",F="Facebook",z="Chromium OS",V="Mac OS",U=" Browser",$=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},G=function(e,t){return typeof e===a&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},H=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,500)},W=function(e,t){for(var r,s,a,c,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=s=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(a=0;a<h.length;a++)l=d[++s],typeof(c=h[a])===o&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):i:this[c[0]]=l?c[1].call(this,l,c[2]):i:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):i):this[c]=l||i;u+=2}},K=function(e,t){for(var r in t)if(typeof t[r]===o&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(G(t[r][n],e))return"?"===r?i:r}else if(G(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Q={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,h],[/opios[\/ ]+([\w\.]+)/i],[h,[l,M+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[l,M+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[l,M]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[l,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[l,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[l,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[l,"UC"+k]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[l,"Smart Lenovo "+k]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+k],h],[/\bfocus\/([\w\.]+)/i],[h,[l,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[l,M+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[l,M+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[l,"MIUI"+U]],[/fxios\/([\w\.-]+)/i],[h,[l,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[l,"360"]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+U],h],[/samsungbrowser\/([\w\.]+)/i],[h,[l,j+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[l,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[l,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[l,T+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,T+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[l,"Android "+k]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[h,K,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[l,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[l,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,q]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,q]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[p,j],[u,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[d,[p,j],[u,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[p,S],[u,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[p,S],[u,v]],[/(macintosh);/i],[d,[p,S]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[p,L],[u,g]],[/(?:honor)([-\w ]+)[;\)]/i],[d,[p,"Honor"],[u,g]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[p,E],[u,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[p,E],[u,g]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,g]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[p,"OPPO"],[u,g]],[/\b(opd2\d{3}a?) bui/i],[d,[p,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[p,"Vivo"],[u,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[d,[p,"Realme"],[u,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[p,I],[u,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[p,I],[u,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[p,D],[u,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[p,D],[u,g]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[p,"Lenovo"],[u,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[p,"Nokia"],[u,g]],[/(pixel c)\b/i],[d,[p,O],[u,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[p,O],[u,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[p,A],[u,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[p,A],[u,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[p,"OnePlus"],[u,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[p,_],[u,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[p,_],[u,g]],[/(playbook);[-\w\),; ]+(rim)/i],[d,p,[u,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[p,R],[u,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[p,C],[u,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[p,C],[u,g]],[/(nexus 9)/i],[d,[p,"HTC"],[u,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[d,/_/g," "],[u,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[d,[p,"TCL"],[u,v]],[/(itel) ((\w+))/i],[[p,q],d,[u,K,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[p,"Acer"],[u,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[p,"Meizu"],[u,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[d,[p,"Ulefone"],[u,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[d,[p,"Energizer"],[u,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[d,[p,"Cat"],[u,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[d,[p,"Smartfren"],[u,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[d,[p,"Nothing"],[u,g]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,d,[u,g]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,d,[u,v]],[/(surface duo)/i],[d,[p,x],[u,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[p,"Fairphone"],[u,g]],[/(u304aa)/i],[d,[p,"AT&T"],[u,g]],[/\bsie-(\w*)/i],[d,[p,"Siemens"],[u,g]],[/\b(rct\w+) b/i],[d,[p,"RCA"],[u,v]],[/\b(venue[\d ]{2,7}) b/i],[d,[p,"Dell"],[u,v]],[/\b(q(?:mv|ta)\w+) b/i],[d,[p,"Verizon"],[u,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[p,"Barnes & Noble"],[u,v]],[/\b(tm\d{3}\w+) b/i],[d,[p,"NuVision"],[u,v]],[/\b(k88) b/i],[d,[p,"ZTE"],[u,v]],[/\b(nx\d{3}j) b/i],[d,[p,"ZTE"],[u,g]],[/\b(gen\d{3}) b.+49h/i],[d,[p,"Swiss"],[u,g]],[/\b(zur\d{3}) b/i],[d,[p,"Swiss"],[u,v]],[/\b((zeki)?tb.*\b) b/i],[d,[p,"Zeki"],[u,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],d,[u,v]],[/\b(ns-?\w{0,9}) b/i],[d,[p,"Insignia"],[u,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[p,"NextBook"],[u,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],d,[u,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],d,[u,g]],[/\b(ph-1) /i],[d,[p,"Essential"],[u,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[p,"Envizen"],[u,v]],[/\b(trio[-\w\. ]+) b/i],[d,[p,"MachSpeed"],[u,v]],[/\btu_(1491) b/i],[d,[p,"Rotor"],[u,v]],[/(shield[\w ]+) b/i],[d,[p,"Nvidia"],[u,v]],[/(sprint) (\w+)/i],[p,d,[u,g]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[p,x],[u,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[p,B],[u,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[p,B],[u,g]],[/smart-tv.+(samsung)/i],[p,[u,b]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[p,j],[u,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,D],[u,b]],[/(apple) ?tv/i],[p,[d,S+" TV"],[u,b]],[/crkey/i],[[d,T+"cast"],[p,O],[u,b]],[/droid.+aft(\w+)( bui|\))/i],[d,[p,_],[u,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[p,L],[u,b]],[/(bravia[\w ]+)( bui|\))/i],[d,[p,A],[u,b]],[/(mitv-\w{5}) bui/i],[d,[p,N],[u,b]],[/Hbbtv.*(technisat) (.*);/i],[p,d,[u,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,H],[d,H],[u,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,d,[u,m]],[/droid.+; (shield) bui/i],[d,[p,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[d,[p,A],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[p,x],[u,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[d,[p,j],[u,y]],[/((pebble))app/i],[p,d,[u,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[p,S],[u,y]],[/droid.+; (glass) \d/i],[d,[p,O],[u,y]],[/droid.+; (wt63?0{2,3})\)/i],[d,[p,B],[u,y]],[/droid.+; (glass) \d/i],[d,[p,O],[u,y]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,d,[u,y]],[/; (quest( \d| pro)?)/i],[d,[p,F],[u,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[u,w]],[/(aeobc)\b/i],[d,[p,_],[u,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[d,[u,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,g]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[l,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[l,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[l,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[h,K,J]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,K,J],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,V],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,h],[/\(bb(10);/i],[h,[l,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[l,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[l,T+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,z],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,h],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,h]]},Y=function(e,t){if(typeof e===o&&(t=e,e=i),!(this instanceof Y))return new Y(e,t).getResult();var m=typeof r!==s&&r.navigator?r.navigator:i,b=e||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:i,w=t?function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r}(Q,t):Q,_=m&&m.userAgent==b;return this.getBrowser=function(){var e,t={};return t[l]=i,t[h]=i,W.call(t,b,w.browser),t[c]=typeof(e=t[h])===a?e.replace(/[^\d\.]/g,"").split(".")[0]:i,_&&m&&m.brave&&typeof m.brave.isBrave==n&&(t[l]="Brave"),t},this.getCPU=function(){var e={};return e[f]=i,W.call(e,b,w.cpu),e},this.getDevice=function(){var e={};return e[p]=i,e[d]=i,e[u]=i,W.call(e,b,w.device),_&&!e[u]&&y&&y.mobile&&(e[u]=g),_&&"Macintosh"==e[d]&&m&&typeof m.standalone!==s&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[d]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.engine),e},this.getOS=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.os),_&&!e[l]&&y&&y.platform&&"Unknown"!=y.platform&&(e[l]=y.platform.replace(/chrome os/i,z).replace(/macos/i,V)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===a&&e.length>500?H(e,500):e,this},this.setUA(b),this};Y.VERSION="1.0.40",Y.BROWSER=$([l,h,c]),Y.CPU=$([f]),Y.DEVICE=$([d,p,u,m,g,b,v,y,w]),Y.ENGINE=Y.OS=$([l,h]),e.exports&&(t=e.exports=Y),t.UAParser=Y;var X=typeof r!==s&&(r.jQuery||r.Zepto);if(X&&!X.ua){var Z=new Y;X.ua=Z.getResult(),X.ua.get=function(){return Z.getUA()},X.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var r in t)X.ua[r]=t[r]}}}("object"==typeof window?window:a)}(fp,fp.exports);var mp,gp=fp.exports;function vp(){}function bp(){bp.init.call(this)}function yp(e){return void 0===e._maxListeners?bp.defaultMaxListeners:e._maxListeners}function wp(e,t,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new vp,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(n=yp(e))&&n>0&&o.length>n){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function _p(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function Sp(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Cp(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}vp.prototype=Object.create(null),bp.EventEmitter=bp,bp.usingDomains=!1,bp.prototype.domain=void 0,bp.prototype._events=void 0,bp.prototype._maxListeners=void 0,bp.defaultMaxListeners=10,bp.init=function(){this.domain=null,bp.usingDomains&&(!mp.active||this instanceof mp.Domain||(this.domain=mp.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new vp,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},bp.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},bp.prototype.getMaxListeners=function(){return yp(this)},bp.prototype.emit=function(e){var t,r,i,n,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,n=Cp(e,i),s=0;s<i;++s)n[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,i){if(t)e.call(r,i);else for(var n=e.length,s=Cp(e,n),o=0;o<n;++o)s[o].call(r,i)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,i,n){if(t)e.call(r,i,n);else for(var s=e.length,o=Cp(e,s),a=0;a<s;++a)o[a].call(r,i,n)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,i,n,s){if(t)e.call(r,i,n,s);else for(var o=e.length,a=Cp(e,o),c=0;c<o;++c)a[c].call(r,i,n,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),s=1;s<i;s++)n[s-1]=arguments[s];!function(e,t,r,i){if(t)e.apply(r,i);else for(var n=e.length,s=Cp(e,n),o=0;o<n;++o)s[o].apply(r,i)}(r,l,this,n)}return!0},bp.prototype.addListener=function(e,t){return wp(this,e,t,!1)},bp.prototype.on=bp.prototype.addListener,bp.prototype.prependListener=function(e,t){return wp(this,e,t,!0)},bp.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,_p(this,e,t)),this},bp.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,_p(this,e,t)),this},bp.prototype.removeListener=function(e,t){var r,i,n,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0===--this._eventsCount?this._events=new vp:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new vp,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i<n;r+=1,i+=1)e[r]=e[i];e.pop()}(r,n);i.removeListener&&this.emit("removeListener",e,o||t)}return this},bp.prototype.off=function(e,t){return this.removeListener(e,t)},bp.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new vp,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new vp:delete r[e]),this;if(0===arguments.length){for(var i,n=Object.keys(r),s=0;s<n.length;++s)"removeListener"!==(i=n[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new vp,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},bp.prototype.listeners=function(e){var t,r,i=this._events;return r=i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[],r},bp.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Sp.call(e,t)},bp.prototype.listenerCount=Sp,bp.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const Rp=Object.create(null);Rp.open="0",Rp.close="1",Rp.ping="2",Rp.pong="3",Rp.message="4",Rp.upgrade="5",Rp.noop="6";const kp=Object.create(null);Object.keys(Rp).forEach(e=>{kp[Rp[e]]=e});const Tp={type:"error",data:"parser error"},Pp="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Op="function"==typeof ArrayBuffer,Ep=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Dp=({type:e,data:t},r,i)=>Pp&&t instanceof Blob?r?i(t):xp(t,i):Op&&(t instanceof ArrayBuffer||Ep(t))?r?i(t):xp(new Blob([t]),i):i(Rp[e]+(t||"")),xp=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Ip(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Mp;const jp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Lp="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let ID=0;ID<64;ID++)Lp[jp.charCodeAt(ID)]=ID;const Ap="function"==typeof ArrayBuffer,Np=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Fp(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Bp(e.substring(1),t)};return kp[r]?e.length>1?{type:kp[r],data:e.substring(1)}:{type:kp[r]}:Tp},Bp=(e,t)=>{if(Ap){const r=(e=>{let t,r,i,n,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=Lp[e.charCodeAt(t)],i=Lp[e.charCodeAt(t+1)],n=Lp[e.charCodeAt(t+2)],s=Lp[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|n>>2,l[c++]=(3&n)<<6|63&s;return d})(e);return Fp(r,t)}return{base64:!0,data:e}},Fp=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,zp=String.fromCharCode(30);function Vp(){return new TransformStream({transform(e,t){!function(e,t){Pp&&e.data instanceof Blob?e.data.arrayBuffer().then(Ip).then(t):Op&&(e.data instanceof ArrayBuffer||Ep(e.data))?t(Ip(e.data)):Dp(e,!1,e=>{Mp||(Mp=new TextEncoder),t(Mp.encode(e))})}(e,r=>{const i=r.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}let Up;function $p(e){return e.reduce((e,t)=>e+t.length,0)}function Gp(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let n=0;n<t;n++)r[n]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function qp(e){if(e)return function(e){for(var t in qp.prototype)e[t]=qp.prototype[t];return e}(e)}qp.prototype.on=qp.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},qp.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},qp.prototype.off=qp.prototype.removeListener=qp.prototype.removeAllListeners=qp.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<i.length;n++)if((r=i[n])===t||r.fn===t){i.splice(n,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},qp.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var n=(r=r.slice(0)).length;i<n;++i)r[i].apply(this,t)}return this},qp.prototype.emitReserved=qp.prototype.emit,qp.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},qp.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Hp="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Wp(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const Kp=Hp.setTimeout,Jp=Hp.clearTimeout;function Qp(e,t){t.useNativeTimers?(e.setTimeoutFn=Kp.bind(Hp),e.clearTimeoutFn=Jp.bind(Hp)):(e.setTimeoutFn=Hp.setTimeout.bind(Hp),e.clearTimeoutFn=Hp.clearTimeout.bind(Hp))}function Yp(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,n=e.length;i<n;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}class Xp extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class Zp extends qp{constructor(e){super(),this.writable=!1,Qp(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Xp(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Np(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const eh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),th={};let rh,ih=0,nh=0;function sh(e){let t="";do{t=eh[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function oh(){const e=sh(+new Date);return e!==rh?(ih=0,rh=e):e+"."+sh(ih++)}for(;nh<64;nh++)th[eh[nh]]=nh;let ah=!1;try{ah="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(MD){}const ch=ah;function dh(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||ch))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Hp[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function lh(){}const uh=null!=new dh({xdomain:!1}).responseType;let ph=class e extends qp{constructor(e,t){super(),Qp(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var t;const r=Wp(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this.opts.xd;const i=this.xhr=new dh(r);try{i.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{i.setRequestHeader("Accept","*/*")}catch(e){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(i.timeout=this.opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(i)),4===i.readyState&&(200===i.status||1223===i.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof i.status?i.status:0)},0))},i.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=e.requestsCount++,e.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=lh,t)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete e.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};if(ph.requestsCount=0,ph.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",hh);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Hp?"pagehide":"unload",hh,!1)}function hh(){for(let e in ph.requests)ph.requests.hasOwnProperty(e)&&ph.requests[e].abort()}const fh="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),mh=Hp.WebSocket||Hp.MozWebSocket,gh="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const vh={websocket:class extends Zp{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=gh?{}:Wp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=gh?new mh(e,t,r):t?new mh(e,t):new mh(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;Dp(r,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}i&&fh(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=oh()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!mh}},webtransport:class extends Zp{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){Up||(Up=new TextDecoder);const r=[];let i=0,n=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===i){if($p(r)<1)break;const e=Gp(r,1);s=!(128&~e[0]),n=127&e[0],i=n<126?3:126===n?1:2}else if(1===i){if($p(r)<2)break;const e=Gp(r,2);n=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if($p(r)<8)break;const e=Gp(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Tp);break}n=s*Math.pow(2,32)+t.getUint32(4),i=3}else{if($p(r)<n)break;const e=Gp(r,n);a.enqueue(Np(s?e:Up.decode(e),t)),i=0}if(0===n||n>e){a.enqueue(Tp);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=Vp();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const n=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),n())}).catch(e=>{})};n();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this.writer.write(r).then(()=>{i&&fh(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends Zp{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=uh&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(zp),i=[];for(let e=0;e<r.length;e++){const n=Np(r[e],t);if(i.push(n),"error"===n.type)break}return i})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let n=0;e.forEach((e,s)=>{Dp(e,!1,e=>{i[s]=e,++n===r&&t(i.join(zp))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=oh()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new ph(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},bh=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,yh=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function wh(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let n=bh.exec(e||""),s={},o=14;for(;o--;)s[yh[o]]=n[o]||"";return-1!=r&&-1!=i&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,s.query),s}let _h=class e extends qp{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=wh(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=wh(t.host).host),Qp(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,i=r.length;e<i;e++){let i=r[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new vh[e](r)}open(){let t;if(this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(e){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(t){let r=this.createTransport(t),i=!1;e.priorWebsocketSuccess=!1;const n=()=>{i||(r.send([{type:"ping",data:"probe"}]),r.once("packet",t=>{if(!i)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;e.priorWebsocketSuccess="websocket"===r.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=r.name,this.emitReserved("upgradeError",e)}}))};function s(){i||(i=!0,l(),r.close(),r=null)}const o=e=>{const t=new Error("probe error: "+e);t.transport=r.name,s(),this.emitReserved("upgradeError",t)};function a(){o("transport closed")}function c(){o("socket closed")}function d(e){r&&e.name!==r.name&&s()}const l=()=>{r.removeListener("open",n),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",n),r.once("error",o),r.once("close",a),this.once("close",c),this.once("upgrading",d),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{i||r.open()},200):r.open()}onOpen(){if(this.readyState="open",e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=Yp(r)),t>0&&e>this.maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const n={type:e,data:t,options:r};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}onError(t){e.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};_h.protocol=4;const Sh="function"==typeof ArrayBuffer,Ch=Object.prototype.toString,Rh="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ch.call(Blob),kh="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ch.call(File);function Th(e){return Sh&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Rh&&e instanceof Blob||kh&&e instanceof File}function Ph(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ph(e[t]))return!0;return!1}if(Th(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ph(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ph(e[t]))return!0;return!1}function Oh(e){const t=[],r=e.data,i=e;return i.data=Eh(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Eh(e,t){if(!e)return e;if(Th(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Eh(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Eh(e[i],t));return r}return e}function Dh(e,t){return e.data=xh(e.data,t),delete e.attachments,e}function xh(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=xh(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=xh(e[r],t));return e}const Ih=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Mh;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Mh||(Mh={}));function jh(e){return"[object Object]"===Object.prototype.toString.call(e)}class Lh extends qp{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Mh.BINARY_EVENT;r||t.type===Mh.BINARY_ACK?(t.type=r?Mh.EVENT:Mh.ACK,this.reconstructor=new Ah(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Th(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Mh[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Mh.BINARY_EVENT||r.type===Mh.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(i,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(n)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!Lh.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Mh.CONNECT:return jh(t);case Mh.DISCONNECT:return void 0===t;case Mh.CONNECT_ERROR:return"string"==typeof t||jh(t);case Mh.EVENT:case Mh.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ih.indexOf(t[0]));case Mh.ACK:case Mh.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ah{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Dh(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Nh=Object.freeze({__proto__:null,Decoder:Lh,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Mh.EVENT&&e.type!==Mh.ACK||!Ph(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Mh.EVENT?Mh.BINARY_EVENT:Mh.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Mh.BINARY_EVENT&&e.type!==Mh.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Oh(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Mh},protocol:5});function Bh(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Fh=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class zh extends qp{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Bh(e,"open",this.onopen.bind(this)),Bh(e,"packet",this.onpacket.bind(this)),Bh(e,"error",this.onerror.bind(this)),Bh(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Fh.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Mh.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((i,n)=>{t.push((e,t)=>r?e?n(e):i(t):i(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Mh.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Mh.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Mh.EVENT:case Mh.BINARY_EVENT:this.onevent(e);break;case Mh.ACK:case Mh.BINARY_ACK:this.onack(e);break;case Mh.DISCONNECT:this.ondisconnect();break;case Mh.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Mh.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Mh.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function Vh(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Vh.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},Vh.prototype.reset=function(){this.attempts=0},Vh.prototype.setMin=function(e){this.ms=e},Vh.prototype.setMax=function(e){this.max=e},Vh.prototype.setJitter=function(e){this.jitter=e};class Uh extends qp{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Qp(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new Vh({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Nh;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new _h(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Bh(t,"open",function(){r.onopen(),e&&e()}),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=Bh(t,"error",n);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(i),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Bh(e,"ping",this.onping.bind(this)),Bh(e,"data",this.ondata.bind(this)),Bh(e,"error",this.onerror.bind(this)),Bh(e,"close",this.onclose.bind(this)),Bh(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){fh(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new zh(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const $h={};function Gh(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=wh(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+t,i.href=i.protocol+"://"+n+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,n=r.id,s=r.path,o=$h[n]&&s in $h[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Uh(i,t):($h[n]||($h[n]=new Uh(i,t)),a=$h[n]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(Gh,{Manager:Uh,Socket:zh,io:Gh,connect:Gh});const qh=new URLSearchParams(window.location.search).has("debug");class Hh{constructor(){this._isEnabled=!1,this._isEnabled=qh}isEnabled(){return this._isEnabled}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}info(...e){if(this._isEnabled)return console.info(...e)}warn(...e){if(this._isEnabled)return console.warn(...e)}error(...e){if(this._isEnabled)return console.error(...e)}withDebugLogger(e){return this._debugger=e,this}debug(...e){if(!this._isEnabled||!this._debugger)return;const t=[];e.forEach(e=>{if("function"==typeof e){const r=e();t.push(r)}else t.push(e)}),this._debugger.print(...t)}}function Wh(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,oi.default;const Kh={id:mi(),connectionNumber:0},Jh=()=>{};let Qh=Jh;const Yh=function(e,t=console){const r=[];let i,n,s,o,a,c,d,l,u,p,h,f,m=0,g=!1,v=0;const b={connected:!1,trace:(...e)=>{if(e.push(Date.now()),"customEvent"===e[0]&&"roomSessionId"===e[2].type){const t=c&&c[2].value.roomSessionId,r=e[2].value.roomSessionId;c=e,g&&r&&r!==t&&(null==i||i.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?n=e:"customEvent"===e[0]&&"displayName"===e[2].type?o=e:"customEvent"===e[0]&&"userRole"===e[2].type?a=e:"customEvent"===e[0]&&"deviceId"===e[2].type?l=e:"customEvent"===e[0]&&"roomProduct"===e[2].type?u=e:"customEvent"===e[0]&&"roomMode"===e[2].type?p=e:"customEvent"===e[0]&&"sfuServer"===e[2].type?h=e:"customEvent"===e[0]&&"featureFlags"===e[2].type&&(f=e);(null==i?void 0:i.readyState)===WebSocket.OPEN?(m=0,i.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==i?void 0:i.readyState)===WebSocket.CLOSED&&d&&setTimeout(()=>{i.readyState===WebSocket.CLOSED&&d&&b.connect()},1e3*m)},close:()=>{d=!1,null==i||i.close()},connect:()=>{d=!0,m+=1,null==i||i.close(),b.connected=!0,i=new WebSocket(e+window.location.pathname,"1.0"),i.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},i.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),Qh()},i.onopen=()=>{for(Kh.connectionNumber++,i.send(JSON.stringify(["clientInfo",null,Kh])),n&&i.send(JSON.stringify(n)),s&&i.send(JSON.stringify(s)),c&&i.send(JSON.stringify(c)),o&&i.send(JSON.stringify(o)),a&&i.send(JSON.stringify(a)),l&&i.send(JSON.stringify(l)),p&&i.send(JSON.stringify(p)),u&&i.send(JSON.stringify(u)),h&&i.send(JSON.stringify(h)),f&&i.send(JSON.stringify(f));r.length;)i.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),Xh=di(Yh.trace,1e4,[""]);Qh=(null==Xh?void 0:Xh.resetDelta)||Jh;const Zh={sendEvent:(e,t)=>{Yh.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{Zh.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{Zh.sendEvent("video_muted",{muted:e})},server:Yh};let ef=[],tf=0;const rf=new WeakMap,nf=e=>{ef=ef.filter(t=>t!==e)};if(window.RTCPeerConnection){const jD=window.RTCPeerConnection;function LD(e){const t=new jD(e);ef.push(t),rf.set(t,{index:tf++});const r=()=>{"closed"===t.connectionState&&(nf(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}LD.prototype=jD.prototype,window.RTCPeerConnection=LD}const sf=new WeakMap;const of=()=>Promise.all(ef.map(e=>Wh(void 0,void 0,void 0,function*(){let t=sf.get(e);t||(t={ssrcToTrackId:{}},sf.set(e,t));try{const r=yield e.getStats();let i=null;if(r.forEach(e=>{if(!("inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||e.trackIdentifier||t.ssrcToTrackId[e.ssrc])){if(e.mediaSourceId){const i=r.get(e.mediaSourceId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}if(!t.ssrcToTrackId[e.ssrc]&&e.trackId){const i=r.get(e.trackId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}t.ssrcToTrackId[e.ssrc]||(i||(i=[]),i.push(e.ssrc))}}),i){const r=[...e.getSenders(),...e.getReceivers()];(yield Promise.all(r.map(e=>e.getStats()))).forEach((e,i)=>{e.forEach(e=>{"inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||(t.ssrcToTrackId[e.ssrc]=r[i].track.id)})}),i.forEach(e=>{t.ssrcToTrackId[e]||(t.ssrcToTrackId[e]="?"+e)})}return[e,r,t]}catch(r){return Zh.sendEvent("trackSsrcLookupFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message}),[e,[],t]}})));function af(e,t,r){return Wh(this,arguments,void 0,function*(e,{logger:t,interval:r},i){const n=af.bind(null,e,{interval:r,logger:t});try{const t=e.getClients(),a=t.find(e=>e.isLocalClient&&!e.isPresentation)||{id:"unknown"};let c=e.statsByView[a.id];c||(c={tracks:{},candidatePairs:{},pressure:null},e.statsByView[a.id]=c),c.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return i?e.statsByView:(e.subscriptions.forEach(r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)}),void(e.nextTimeout=setTimeout(n,r)));if(e.lastUpdateTime=Date.now(),(yield of()).forEach(([i,n,s])=>{const o=(e=>{var t;return null===(t=rf.get(e))||void 0===t?void 0:t.index})(i);"closed"===i.connectionState&&(n=new Map,nf(i)),s.previousSSRCs=s.currentSSRCs||{},s.currentSSRCs={},n.forEach(i=>{var d,l,u;if("candidate-pair"===i.type&&/inprogress|succeeded/.test(i.state)){const t=null===(d=s._oldReport)||void 0===d?void 0:d.get(i.id),a=t?i.timestamp-t.timestamp:r,l=o+":"+i.id;let u=c.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},c.candidatePairs[l]=u),function(e,t,r,i,n){const s=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0),o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.bitrateIn=8e3*s/i,e.bitrateOut=8e3*o/i,e.state=t.state,e.roundTripTime=t.currentRoundTripTime,e.requestsSent=t.requestsSent,e.responsesReceived=t.responsesReceived,e.requestsReceived=t.requestsReceived,e.responsesSent=t.responsesSent,e.availableOutgoingBitrate=t.availableOutgoingBitrate,e.availableIncomingBitrate=t.availableIncomingBitrate;const a=n.get(t.remoteCandidateId),c=n.get(t.localCandidateId);e.usingTurn=!1,c&&/relay/i.test(c.candidateType||"")&&(e.usingTurn=!0,e.turnProtocol=c.relayProtocol),a&&c&&(e.localEp=`${c.protocol}:${c.address||c.ip}:${c.port} ${c.candidateType} (${c.networkType})`,e.remoteEp=`${a.protocol}:${a.address||a.ip}:${a.port} ${a.candidateType}`)}(u,i,t,a,n),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===i.type||"outbound-rtp"===i.type){const c=i.mediaType||i.kind,d=i.ssrc;let p=i.trackIdentifier||s.ssrcToTrackId[d],h=null===(l=s._oldReport)||void 0===l?void 0:l.get(i.id);if(h&&h.mediaSourceId!==i.mediaSourceId){const e=n.get(i.mediaSourceId);e&&e.trackIdentifier&&(p=e.trackIdentifier,s.ssrcToTrackId[d]=p)}const f=t.find(e=>{var t;return(null===(t=e[c].track)||void 0===t?void 0:t.id)===p})||a;if(!i.trackIdentifier&&s.ssrcToTrackId[d]&&(null===(u=f[c].track)||void 0===u?void 0:u.id)&&f[c].track.id!==s.ssrcToTrackId[d]&&(p=f[c].track.id,s.ssrcToTrackId[d]=f[c].track.id),s.currentSSRCs[d]=f.id,h){const e=n.get(i.transportId),t=s._oldReport.get(h.transportId);(t&&(null==e?void 0:e.selectedCandidatePairId)!==t.selectedCandidatePairId||i.bytesReceived<h.bytesReceived||i.bytesSent<h.bytesSent)&&(h=null)}const m=h?i.timestamp-h.timestamp:r,g=((e,t,r,i,n,s)=>{let o=e[i];o||(o={tracks:{},startTime:t,updated:t},e[i]=o),o.updated=t;let a=o.tracks[n];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[n]=a),a.updated=t;let c=a.ssrcs[s];return c||(c={startTime:t,updated:t,pcIndex:r},a.ssrcs[s]=c),c.updated=t,c})(e.statsByView,e.lastUpdateTime,o,f.id,p,d);!function(e,t,r,i,n){if(e.codec)return;e.kind=t.kind||t.mediaType,e.ssrc=t.ssrc,e.direction="inbound-rtp"===t.type?"in":"out";const s=t.codecId&&n.get(t.codecId);e.codec=s&&[s.mimeType,s.channels&&`${s.channels}ch`,s.clockRate,s.payloadType,t.encoderImplementation||t.decoderImplementation,s.sdpFmtpLine].filter(Boolean).join(" "),e.mid=t.mid,e.rid=t.rid}(g,i,0,0,n),function(e,t,r,i,n){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/i,"in"===e.direction){const n=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+n,e.packetRate=1e3*n/i;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/i,e.lossRatio=s/(s+n)*1e3/i;const o=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesReceived&&(a=t.headerBytesReceived-((null==r?void 0:r.headerBytesReceived)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;if(e.bitrate=8e3*c/i,e.mediaRatio=o/c,"audio"===t.kind){const i=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=i/o}const d=(t.jitterBufferDelay||0)-((null==r?void 0:r.jitterBufferDelay)||0),l=(t.jitterBufferEmittedCount||0)-((null==r?void 0:r.jitterBufferEmittedCount)||0);e.jitter=l?d/l:0}else{const s=t.packetsSent-((null==r?void 0:r.packetsSent)||0);e.packetCount=(e.packetCount||0)+s,e.packetRate=1e3*s/i;const o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesSent&&(a=t.headerBytesSent-((null==r?void 0:r.headerBytesSent)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;e.bitrate=8e3*c/i,e.mediaRatio=o/c;const d=t.totalPacketSendDelay-((null==r?void 0:r.totalPacketSendDelay)||0);e.sendDelay=d/s;const l=t.retransmittedPacketsSent-((null==r?void 0:r.retransmittedPacketsSent)||0);if(e.retransRatio=l/s*1e3/i,t.remoteId){const r=n.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,i,h,m,n),"video"===c&&function(e,t,r,i,n){e.width=t.frameWidth,e.height=t.frameHeight,e.qualityLimitationReason=t.qualityLimitationReason||"";const s=t.pliCount-((null==r?void 0:r.pliCount)||0);e.pliCount=(e.pliCount||0)+s,e.pliRate=1e3*s/i;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/i,"in"===e.direction){const n=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+n,e.kfRate=1e3*n/i;const s=t.framesDecoded-((null==r?void 0:r.framesDecoded)||0);e.frameCount=(e.frameCount||0)+s;const o=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=o/s,e.fps=1e3*s/i}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/i;const o=t.framesEncoded-((null==r?void 0:r.framesEncoded)||0);e.frameCount=(e.frameCount||0)+o;const a=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=a/o,e.fps=1e3*o/i;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=n.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,i,h,m,n),"audio"===c&&function(e,t,r){const i=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+i,"in"===e.direction){const i=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),n=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(i/n);const s=t.totalSamplesReceived||0,o=t.concealmentEvents||0,a=s-((null==r?void 0:r.totalSamplesReceived)||0),c=t.concealedSamples||0,d=c-((null==r?void 0:r.concealedSamples)||0),l=(t.silentConcealedSamples||0)-((null==r?void 0:r.silentConcealedSamples)||0),u=(t.insertedSamplesForDeceleration||0)-((null==r?void 0:r.insertedSamplesForDeceleration)||0),p=(t.removedSamplesForAcceleration||0)-((null==r?void 0:r.removedSamplesForAcceleration)||0);e.audioSamples=s,e.audioConcealmentEvents=o,e.audioConcealedSamples=c,e.audioConcealment=d?d/a:0,e.audioSilentConcealment=l?l/a:0,e.audioAcceleration=p?p/a:0,e.audioDeceleration=u?u/a:0}}(g,i,h)}}),s._oldReport=n,Object.keys(s.previousSSRCs).filter(e=>!s.currentSSRCs[e]).forEach(t=>{const r=s.previousSSRCs[t];if(r){const i=e.statsByView[r];i&&Object.values(i.tracks).forEach(e=>{e.ssrcs[t]&&delete e.ssrcs[t]})}})}),s=e.statsByView,o=e.lastUpdateTime,Object.entries(s).forEach(([e,t])=>{t.updated<o?delete s[e]:Object.entries(t.tracks).forEach(([e,r])=>{r.updated<o?delete t.tracks[e]:Object.entries(r.ssrcs).forEach(([e,t])=>{t.updated<o&&delete r.ssrcs[e]})})}),Object.entries((null==c?void 0:c.candidatePairs)||{}).forEach(([t,r])=>{const i=r.lastRtcStatsTime===e.lastUpdateTime;r.active=i,i||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete c.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)}),i)return e.statsByView;e.subscriptions.forEach(r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)})}catch(r){t.warn(r),e.numFailedStatsReports++,Zh.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}var s,o;e.nextTimeout=setTimeout(n,r)})}const cf={};function df(e,t=cf,r=window.document){e.forEach(({hostnamePattern:e,token:i})=>{const n=`${e}-${i}`;if(!t[n]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=i,r.head.append(e),t[n]=!0}})}const lf={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const uf={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},pf={interval:2e3,logger:new Hh},hf=()=>{var e;return null===(e=uf.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function ff(e,{interval:t,logger:r}){const i=af.bind(null,e,{interval:t,logger:r});let n;try{n=function(e,{sampleRate:t,originTrials:r}=lf,i=globalThis.window){let n;if(df(r),"PressureObserver"in i)return n=new i.PressureObserver(e,{sampleRate:t}),n.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{n.unobserve("cpu")}}}(t=>e.lastPressureObserverRecord=t.pop())}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(i,t),{getUpdatedStats:()=>i(!0),stop:()=>{clearTimeout(e.nextTimeout),n&&n.stop()}}}var mf;const gf=null!==(mf=oi.default)&&void 0!==mf?mf:oi,vf=new Hh,bf=gf.browserDetails.browser,yf=gf.browserDetails.version;function wf(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),i=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);r||(r=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),i=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<r.length;e++)t=t.replace(new RegExp(i[e],"g"),r[e]);return t}function _f(e){return"firefox"!==bf?e:Jr.splitLines(e.trim()).map(e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e).join("\r\n")+"\r\n"}function Sf(e){return function(e,t,r=!1,i=!1){var n,s;try{const o=xi(e);if((null===(n=null==o?void 0:o.ext)||void 0===n?void 0:n.length)&&o.ext.length>0)return e;if((null==o?void 0:o.media.length)<1)return e;const a=null==o?void 0:o.media.flatMap(e=>e.ext||[]),c=(null===(s=a.find(e=>e.uri===t))||void 0===s?void 0:s.value)||[...new Set([0,15,...a.map(e=>e.value)])].sort((e,t)=>e-t).find((e,t,r)=>e+1!==r[t+1])+1;return o.media.forEach(e=>{var n;(r&&"audio"===e.type||i&&"video"===e.type)&&((null===(n=e.ext)||void 0===n?void 0:n.find(e=>e.uri===t))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))}),Di(o)}catch(e){console.error("Error during addAbsCaptureTimeExtMap: ",e)}return e}(e,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",!0,!0)}function Cf(e,t,r=console){const i=e.getSenders().find(e=>e.track&&"video"===e.track.kind);if(!i)return Promise.resolve();const n=i.getParameters();return n.encodings&&0===n.encodings.length?Promise.resolve():(n.encodings||(n.encodings=[{}]),0===t?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=1e3*t,i.setParameters(n).catch(e=>{r.error("setParameters err: ",e)}))}const Rf=400;var kf;const Tf=null!==(kf=oi.default)&&void 0!==kf?kf:oi,Pf=new Hh;class Of{constructor({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:r,deprioritizeH264Encoding:i}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.serverReflexiveCandidateSeen=!1,this.publicHostCandidateSeen=!1,this.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.maximumTurnBandwidth=r,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise(e=>{this.registerConnected=e}),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=i}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:i}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=i,this.clientId=e,this.pc=new RTCPeerConnection(r),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}}),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach(t=>{this.pc.addTrack(t,e)}),e.getVideoTracks().forEach(t=>{this.pc.addTrack(t,e)})):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),null==t||t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach(e=>{const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return Jr.splitSections(e).map(e=>{if("video"!==Jr.getKind(e))return e;const t=Jr.matchPrefix(e,"a=rtpmap:").map(e=>Jr.parseRtpMap(e)).filter(e=>/h264/i.test(e.name)).map(e=>""+e.payloadType);if(!t.length)return e;const r=Jr.matchPrefix(e,"m=video")[0],i=/(\s\d+)+$/i.exec(r),n=i?i[0]:"",s=[...n.split(" ").filter(e=>e&&!t.includes(e)),...t].join(" "),o=r.replace(n," "+s);return e.replace(r,o)}).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then(()=>{this.earlyIceCandidates.forEach(e=>this.pc.addIceCandidate(e)),this.earlyIceCandidates=[]})}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise(t=>{this.pending.push(()=>this.handleOffer(e).then(t))});this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==bf&&("firefox"!==bf||yf&&yf>=63||60===yf)?e:Jr.splitLines(e.trim()).filter(e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==Jr.parseExtmap(e).uri).join("\r\n")+"\r\n"}(t),t=_f(t);const r={type:e.type,sdp:t};let i;return this._setRemoteDescription(r).then(()=>this.pc.createAnswer()).then(e=>(i=e,this.pc.setLocalDescription(e))).then(()=>Cf(this.pc,this.bandwidth)).then(()=>i)}handleAnswer(e){const t=_f(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then(()=>Cf(this.pc,this.bandwidth),e=>{Pf.warn("Could not set remote description from remote answer: ",e)})}addIceCandidate(e){this.srdComplete?this.srdComplete.then(()=>{"closed"!==this.pc.signalingState&&("safari"===Tf.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch(t=>{Pf.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)}))}):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){Pf.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const r=this.pc;if(!r)return!1;const i=r.getSenders();if(e||(e=(i.find(e=>e.track&&e.track.kind===t.kind)||{}).track),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const r=()=>{for(let r=0;r<i.length;r++){const n=i[r].track;if((null==n?void 0:n.id)===t.id)return Promise.resolve(t);if((null==n?void 0:n.id)===e.id)return i[r].replaceTrack(t)}return null};let n=r();if(n)return n;let s=null,o=null;n=new Promise((e,t)=>{s=e,o=t});let a=0,c=setInterval(()=>Wh(this,void 0,void 0,function*(){const e=r();if(!e)return void(3<++a&&(clearInterval(c),c=null,o("No sender track to replace")));clearInterval(c),c=null;const t=yield e;s(t)}),1e3);return n}const n=this.streams.find(e=>e.getTracks().find(e=>e.id===t.id))||this.streams[0];return n?r.addTrack(t,n):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push(()=>{this.replaceTrack(e,t)});this.isOperationPending=!0;const n=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout(()=>{r.onnegotiationneeded=n},0),"offer"===r.localDescription.type?r.createOffer().then(e=>(e.sdp=wf(r.localDescription.sdp,e.sdp),r.setLocalDescription(e))).then(()=>this._setRemoteDescription(r.remoteDescription)):this._setRemoteDescription(r.remoteDescription).then(()=>r.createAnswer()).then(e=>(e.sdp=wf(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))}maybeRestrictRelayBandwidth(){var e;-1!==this.maximumTurnBandwidth&&(this.pc.getStats&&(e=this.pc,e.getStats(null).then(e=>{let t,r;return e.forEach(i=>{if("transport"===i.type&&i.selectedCandidatePairId){const n=e.get(i.selectedCandidatePairId);if(!n)return;return t=e.get(n.localCandidateId).candidateType,void(r=e.get(n.remoteCandidateId).candidateType)}"candidate-pair"===i.type&&i.selected&&(t=e.get(i.localCandidateId).candidateType,r=e.get(i.remoteCandidateId).candidateType)}),"relay"===t||"relayed"===t||"relay"===r||"relayed"===r})).then(e=>{e&&0===this.bandwidth&&this.changeBandwidth(this.maximumTurnBandwidth)}))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&Cf(this.pc,this.bandwidth)):this.pending.push(()=>this.changeBandwidth(e)))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter(e=>{var r,i,n,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(i=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===i?void 0:i.kind)&&!t.includes(null===(s=null===(n=null==e?void 0:e.receiver)||void 0===n?void 0:n.track)||void 0===s?void 0:s.id)&&!t.includes(null===(a=null===(o=null==e?void 0:e.sender)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)}).forEach(t=>{t.direction=e?"sendonly":"sendrecv"})}}var Ef;const Df=null!==(Ef=oi.default)&&void 0!==Ef?Ef:oi;const xf="fetch_mediaserver_config",If="start_screenshare",Mf="stop_screenshare",jf="audio_enabled",Lf="client_left",Af="mediaserver_config",Nf="new_client",Bf="screenshare_started",Ff="screenshare_stopped",zf="room_joined",Vf="video_enabled",Uf="ice_candidate",$f="ice_endofcandidates",Gf="ready_to_receive_offer",qf="sdp_answer",Hf="sdp_offer",Wf="pending_client_left",Kf="media_quality_changed",Jf="client_connection_status_changed",Qf="stream_added",Yf="rtc_manager_created",Xf="rtc_manager_destroyed",Zf="local_stream_track_added",em="local_stream_track_removed",tm="connecting",rm="connection_failed",im="connection_successful",nm="connection_disconnected",sm="camera",om="screen_share";const am="[a-fA-F\\d:]",cm=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${am})|(?<=${am})(?=\\s|$))`:"",dm="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",lm="[a-fA-F\\d]{1,4}",um=`\n(?:\n(?:${lm}:){7}(?:${lm}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${lm}:){6}(?:${dm}|:${lm}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${lm}:){5}(?::${dm}|(?::${lm}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${lm}:){4}(?:(?::${lm}){0,1}:${dm}|(?::${lm}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${lm}:){3}(?:(?::${lm}){0,2}:${dm}|(?::${lm}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${lm}:){2}(?:(?::${lm}){0,3}:${dm}|(?::${lm}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${lm}:){1}(?:(?::${lm}){0,4}:${dm}|(?::${lm}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${lm}){0,5}:${dm}|(?::${lm}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),pm=new RegExp(`(?:^${dm}$)|(?:^${um}$)`),hm=new RegExp(`^${dm}$`),fm=new RegExp(`^${um}$`),mm=e=>e&&e.exact?pm:new RegExp(`(?:${cm(e)}${dm}${cm(e)})|(?:${cm(e)}${um}${cm(e)})`,"g");mm.v4=e=>e&&e.exact?hm:new RegExp(`${cm(e)}${dm}${cm(e)}`,"g"),mm.v6=e=>e&&e.exact?fm:new RegExp(`${cm(e)}${um}${cm(e)}`,"g");var gm="connection_blocked_by_network",vm="ice_ipv6_seen",bm="ice_mdns_seen",ym="ice_no_public_ip_gathered",wm="ice_no_public_ip_gathered_3sec",_m="ice_restart",Sm="microphone_not_working",Cm="microphone_stopped_working",Rm="camera_stopped_working",km="new_pc",Tm="sfu_connection_open",Pm="sfu_connection_closed",Om="sfu_connection_info",Em="dominant_speaker",Dm="pc_sld_failure",xm="pc_on_answer_failure",Im="pc_on_offer_failure";class Mm extends Error{constructor(e){super(e.message),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,Error.captureStackTrace&&Error.captureStackTrace(this,e.stackStartFn)}}function jm(e){if(e.message instanceof Error)throw e.message;throw new Mm(e)}function Lm(...e){!function(e,t,r,i){if(!r){let n=!1;if(0===t)n=!0,i="No value argument passed to `assert.ok()`";else if(i instanceof Error)throw i;const s=new Mm({actual:r,expected:!0,message:i,operator:"==",stackStartFn:e});throw s.generatedMessage=n,s}}(Lm,e.length,...e)}const Am={fail:e=>{jm({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:Am.fail})},ok:Lm,notEqual:function e(t,r,i){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&jm({actual:t,expected:r,message:i,operator:"!=",stackStartFn:e})}};Am.ok=Lm;const Nm=new is("Safari17"),Bm={OS:1024,MIS:1024};class Fm extends Ma{static createFactory(){return()=>new Fm}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari17"}close(){if(Nm.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}getNativeRtpCapabilities(){return Wh(this,void 0,void 0,function*(){Nm.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=yield e.createOffer();try{e.close()}catch(e){}const r=xi(t.sdp),i=Ra({sdpObject:r});return xa(i),i}catch(t){try{e.close()}catch(e){}throw t}})}getNativeSctpCapabilities(){return Wh(this,void 0,void 0,function*(){return Nm.debug("getNativeSctpCapabilities()"),{numStreams:Bm}})}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Nm.debug("run()"),this._direction=e,this._remoteSdp=new Ka({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:io("audio",d),video:io("video",d)},this._sendingRemoteRtpParametersByKind={audio:no("audio",d),video:no("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection(Object.assign({iceServers:null!=s?s:[],iceTransportPolicy:null!=o?o:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},a),c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Nm.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}updateIceServers(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),Nm.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)})}restartIce(e){return Wh(this,void 0,void 0,function*(){if(this.assertNotClosed(),Nm.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=yield this._pc.createOffer({iceRestart:!0});Nm.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();Nm.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t)}})}getTransportStats(){return Wh(this,void 0,void 0,function*(){return this.assertNotClosed(),this._pc.getStats()})}send(e){return Wh(this,arguments,void 0,function*({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){var s;this.assertNotClosed(),this.assertSendDirection(),Nm.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const o=Is(this._sendingRtpParametersByKind[e.kind]);o.codecs=so(o.codecs,i),t&&t.length>1&&t.every(({rid:e})=>!e)&&(t=t.map((e,t)=>(e.rid=`r${t}`,e))),t&&(o.encodings||(o.encodings=[]),Object.assign(o.encodings,t));const a=Za((null!=t?t:[{}])[0].scalabilityMode);if(o.encodings&&o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${a.temporalLayers}`:e.scalabilityMode="L1T3";const c=Is(this._sendingRemoteRtpParametersByKind[e.kind]);c.codecs=so(c.codecs,i);const d=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:"video"===e.kind?t:void 0});n&&n(l.sender);const u=yield this._pc.createOffer(),p=xi(u.sdp);let h=p.media[d.idx];this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:p})),Nm.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),yield this._pc.setLocalDescription(u);const f=l.mid;o.mid=f,h=p.media[d.idx],o.rtcp.cname=Ta({offerMediaObject:h}),this._remoteSdp.send({offerMediaObject:h,reuseMid:d.reuseMid,offerRtpParameters:o,answerRtpParameters:c,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Nm.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),yield this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(f,l),{localId:f,rtpParameters:o,rtpSender:l.sender}})}stopSending(e){return Wh(this,void 0,void 0,function*(){if(this.assertSendDirection(),this._closed)return;Nm.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=yield this._pc.createOffer();Nm.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)})}pauseSending(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=yield this._pc.createOffer();Nm.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)})}resumeSending(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=yield this._pc.createOffer();Nm.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)})}replaceTrack(e,t){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),t?Nm.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Nm.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");yield r.sender.replaceTrack(t)})}setMaxSpatialLayer(e,t){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();Nm.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)})}setRtpEncodingParameters(e,t){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]=Object.assign(Object.assign({},e),t)}),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();Nm.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)})}getSenderStats(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()})}sendDataChannel(e){return Wh(this,arguments,void 0,function*({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){var s;this.assertNotClosed(),this.assertSendDirection();const o={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Nm.debug("sendDataChannel() [options:%o]",o);const a=this._pc.createDataChannel(i,o);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Bm.MIS,!this._hasDataChannelMediaSection){const e=yield this._pc.createOffer(),t=xi(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:t})),Nm.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:a,sctpStreamParameters:{streamId:o.id,ordered:o.ordered,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits}}})}receive(e){return Wh(this,void 0,void 0,function*(){var t,r;this.assertNotClosed(),this.assertRecvDirection();const i=[],n=new Map;for(const r of e){const{trackId:e,kind:i,rtpParameters:s,streamId:o}=r;Nm.debug("receive() [trackId:%s, kind:%s]",e,i);const a=null!==(t=s.mid)&&void 0!==t?t:String(this._mapMidTransceiver.size);n.set(e,a),this._remoteSdp.receive({mid:a,kind:i,offerRtpParameters:s,streamId:null!=o?o:s.rtcp.cname,trackId:e})}const s={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),yield this._pc.setRemoteDescription(s);for(const t of e){const{trackId:e,onRtpReceiver:r}=t;if(r){const t=n.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");r(i.receiver)}}let o=yield this._pc.createAnswer();const a=xi(o.sdp);for(const t of e){const{trackId:e,rtpParameters:r}=t,i=n.get(e),s=a.media.find(e=>String(e.mid)===i);Pa({offerRtpParameters:r,answerMediaObject:s})}o={type:"answer",sdp:Di(a)},this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:a})),Nm.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),yield this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,r=n.get(e),s=this._pc.getTransceivers().find(e=>e.mid===r);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(r,s),i.push({localId:r,track:s.receiver.track,rtpReceiver:s.receiver})}return i})}stopReceiving(e){return Wh(this,void 0,void 0,function*(){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Nm.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();Nm.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)})}pauseReceiving(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Nm.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();Nm.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)})}resumeReceiving(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Nm.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();Nm.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)})}getReceiverStats(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()})}receiveDataChannel(e){return Wh(this,arguments,void 0,function*({sctpStreamParameters:e,label:t,protocol:r}){var i;this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a}=e,c={negotiated:!0,id:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a,protocol:r};Nm.debug("receiveDataChannel() [options:%o]",c);const d=this._pc.createDataChannel(t,c);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();if(!this._transportReady){const e=xi(t.sdp);yield this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:e})}Nm.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}})}setupTransport(e){return Wh(this,arguments,void 0,function*({localDtlsRole:e,localSdpObject:t}){t||(t=xi(this._pc.localDescription.sdp));const r=ka({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),yield new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0})}assertNotClosed(){if(this._closed)throw new Os("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}const zm={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},Vm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},Um={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},$m={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2",maxBitrate:1e6}]},Gm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2_KEY",maxBitrate:125e4}]},qm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2",maxBitrate:5e5}]},Hm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2_KEY",maxBitrate:65e4}]},Wm={encodings:[{}]},Km={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},Jm={encodings:[{scaleResolutionDownBy:4,dtx:!0,maxBitrate:15e4},{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},Qm={encodings:[{scalabilityMode:"L2T2_KEY",dtx:!0,maxBitrate:15e5}]},Ym={encodings:[{dtx:!0}]},Xm=(e,t,r,i=!1)=>{const{lowDataModeEnabled:n,simulcastScreenshareOn:s,vp9On:o,svcKeyScalabilityModeOn:a}=r;if("audio"===e)return zm;const c="chrome"===oi.browserDetails.browser&&o;return t?eg({isVp9Available:c,isSomeoneAlreadyPresenting:i,simulcastScreenshareOn:s}):Zm({lowBandwidth:n,isVp9Available:c,svcKeyScalabilityModeOn:a})},Zm=({lowBandwidth:e,isVp9Available:t,svcKeyScalabilityModeOn:r})=>e?t?r?Hm:qm:Um:t?r?Gm:$m:Vm,eg=({isVp9Available:e,isSomeoneAlreadyPresenting:t,simulcastScreenshareOn:r})=>t?e?Qm:Jm:e?Ym:r?Km:Wm;var tg;!function(e){e.H264="video/h264",e.VP9="video/vp9"}(tg||(tg={}));function rg(e,t){const r=e.find(({mimeType:e})=>e.toLowerCase()===t);return r?[...e].sort((e,i)=>e.mimeType.toLowerCase()===t?-1:"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===r.preferredPayloadType?i.mimeType.toLowerCase()===t?1:-1:0):e}function ig(e){return Wh(this,void 0,void 0,function*(){const t=yield Promise.all(e.map(({mimeType:e})=>function(e){return Wh(this,void 0,void 0,function*(){const{powerEfficient:t}=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{width:1280,height:720,bitrate:2580,framerate:24,contentType:e}});return t})}(e).then(t=>[e,t]))),r=Object.fromEntries(t);return e.sort((e,t)=>{const i=r[e.mimeType];return i===r[t.mimeType]?0:i?-1:1})})}function ng(e,t){return Wh(this,void 0,void 0,function*(){return e=function(e,t){const r=e.map(({mimeType:e})=>e).filter((e,t,r)=>r.indexOf(e)===t),i=function(e,{vp9On:t,av1On:r}){return t&&e.unshift("video/vp9"),r&&e.unshift("video/av1"),e}(r,t);return e.sort((e,t)=>{const r=i.indexOf(e.mimeType.toLowerCase()),n=i.indexOf(t.mimeType.toLowerCase());return(r>=0?r:Number.MAX_VALUE)-(n>=0?n:Number.MAX_VALUE)})}(e,t),t.preferHardwareDecodingOn&&(e=yield ig(e)),e})}const sg=new Hh;class og extends bp{constructor(e){super(),this.reconnectThresholdInMs=0,this._socket=e,this._clients={},this._signalDisconnectTime=void 0,this.rtcManager=void 0,this.metrics={roomJoinedLate:0,pendingClientCanceled:0,evaluationFailed:0,roomJoined:0},e.on("disconnect",()=>{this._signalDisconnectTime=Date.now()}),e.on(zf,e=>this._onRoomJoined(e)),e.on(Nf,e=>this._onNewClient(e)),e.on(Lf,e=>this._onClientLeft(e)),e.on(Wf,e=>this._onPendingClientLeft(e)),e.on(jf,e=>this._onAudioEnabled(e)),e.on(Vf,e=>this._onVideoEnabled(e)),e.on(Bf,e=>this._onScreenshareChanged(e,!0)),e.on(Ff,e=>this._onScreenshareChanged(e,!1))}_onRoomJoined(e){return Wh(this,void 0,void 0,function*(){var t;if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),null==e?void 0:e.error)return void this.emit(zf,e);if(!e.selfId)return void this.emit(zf,e);const r=null===(t=e.room.clients.find(t=>e.selfId===t.id))||void 0===t?void 0:t.deviceId;if(!r)return void this.emit(zf,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave)),void this.emit(zf,e);const i=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>i)return this._resetClientState(e),this.emit(zf,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave));const n=yield hf();e.room.clients.forEach(t=>{var r;try{if(t.id===e.selfId)return;if(!this._clients[t.id])return void this._addClientToState(t);if(!(null===(r=this.rtcManager)||void 0===r?void 0:r.hasClient(t.id)))return;if(this._hasClientStateChanged({clientId:t.id,webcam:t.isVideoEnabled,mic:t.isAudioEnabled,screenShare:t.streams.length>1}))return;if(this._wasClientSendingMedia(t.id)&&!this._isClientMediaActive(n,t.id))return;t.mergeWithOldClientState=!0}catch(e){sg.error("Failed to evaluate if we should merge client state %o",e),this.metrics.evaluationFailed++}}),e.room.clients.forEach(e=>{e.isPendingToLeave&&this._onPendingClientLeft({clientId:e.id})}),this.metrics.roomJoined++,this.emit(zf,e)})}_onClientLeft(e){var t;const{clientId:r}=e,i=this._clients[r];i&&(clearTimeout(i.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(Lf,e)}_onPendingClientLeft(e){const{clientId:t}=e,r=this._clients[t];r?r.isPendingToLeave||(r.isPendingToLeave=!0,this._wasClientSendingMedia(t)&&(r.checkActiveMediaAttempts=0,this._abortIfNotActive(e))):sg.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,i=this._clients[t];if(i&&i.isPendingToLeave)return clearTimeout(i.timeoutHandler),i.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach(e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(Lf,{clientId:e.clientId})}),this._addClientToState(e.client),this.emit(Nf,e)}_abortIfNotActive(e){return Wh(this,void 0,void 0,function*(){const{clientId:t}=e;let r=this._clients[t];if(!(null==r?void 0:r.isPendingToLeave))return;if(r.checkActiveMediaAttempts++,r.checkActiveMediaAttempts>3)return;(yield this._checkIsActive(t))?r.timeoutHandler=setTimeout(()=>this._abortIfNotActive(e),500):(r=this._clients[t],(null==r?void 0:r.isPendingToLeave)&&(clearTimeout(r.timeoutHandler),delete this._clients[t],this.emit(Lf,e)))})}_checkIsActive(e){return Wh(this,void 0,void 0,function*(){const t=yield hf();return this._isClientMediaActive(t,e)})}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let i=!1;return r&&Object.entries(r.tracks).forEach(([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach(e=>{(e.bitrate||0)>0&&(i=!0)})}),i}_onAudioEnabled(e){const{clientId:t,isAudioEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isAudioEnabled:r})}_onVideoEnabled(e){const{clientId:t,isVideoEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isVideoEnabled:r})}_onScreenshareChanged(e,t){const{clientId:r}=e;this._clients[r]=Object.assign(Object.assign({},this._clients[r]||{}),{isScreenshareEnabled:t})}_hasClientStateChanged({clientId:e,webcam:t,mic:r,screenShare:i}){const n=this._clients[e];if(!n)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==n.isVideoEnabled||(r!==n.isAudioEnabled||i!==n.isScreenshareEnabled)}_addClientToState(e){this._clients[e.id]=Object.assign(Object.assign({},this._clients[e.id]||{}),{isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled,isScreenshareEnabled:e.streams.length>1,deviceId:e.deviceId,isPendingToLeave:e.isPendingToLeave,clientId:e.id})}_wasClientSendingMedia(e){const t=this._clients[e];if(!t)throw new Error(`Client ${e} not found in ReconnectManager state`);return t.isAudioEnabled||t.isVideoEnabled||t.isScreenshareEnabled}_getPendingClientsByDeviceId(e){return Object.values(this._clients).filter(t=>t.deviceId===e&&t.isPendingToLeave)}_resetClientState(e){this._clients={},e.room.clients.forEach(t=>{t.id!==e.selfId&&this._addClientToState(t)})}}var ag;const cg=null!==(ag=oi.default)&&void 0!==ag?ag:oi;class dg{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=Gh(e,Object.assign({path:"/protocol/socket.io/v4",randomizationFactor:.5,reconnectionDelay:250,reconnectionDelayMax:5e3,timeout:5e3,transports:["websocket"],withCredentials:!0},t)),this._socket.io.on("reconnect",()=>{this._socket.sendBuffer=[]}),this._socket.io.on("reconnect_attempt",()=>{this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==cg.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]}),r&&(this._reconnectManager=new og(this._socket)),this._socket.on("connect",()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0,this.noopKeepaliveInterval||(this.noopKeepaliveInterval=setInterval(()=>{try{this._socket.connected&&this._socket.io.engine.sendPacket("noop")}catch(e){}},2e3)))}),this._socket.on("disconnect",()=>{this.disconnectTimestamp=Date.now(),this.noopKeepaliveInterval&&(clearInterval(this.noopKeepaliveInterval),this.noopKeepaliveInterval=null)})}setRtcManager(e){this._reconnectManager&&(this._reconnectManager.rtcManager=e)}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}disconnectOnConnect(){this._socket.once("connect",()=>{this._socket.disconnect()})}emit(e,...t){this._socket.emit.apply(this._socket,arguments)}emitIfConnected(e,t){this.isConnected()&&this.emit(e,t)}getTransport(){return this._socket&&this._socket.io&&this._socket.io.engine&&this._socket.io.engine.transport&&this._socket.io.engine.transport.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){const r=[zf,Lf,Nf];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.off(e,t)})}onEngineEvent(e,t){var r;return null===(r=this._socket.io)||void 0===r||r.on(e,t),()=>{var r;null===(r=this._socket.io)||void 0===r||r.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}_interceptEvent(e,t){return this._reconnectManager&&this._reconnectManager.on(e,t),()=>{this._reconnectManager&&this._reconnectManager.removeListener(e,t)}}getGlitchFreeMetrics(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.metrics}getReconnectThreshold(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.reconnectThresholdInMs}}const lg=(e,t)=>{if(!t.useOnlyTURN)return;e.iceTransportPolicy="relay";const r={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[t.useOnlyTURN];r&&(e.iceServers=e.iceServers.filter(e=>e.url&&e.url.match(r)||e.urls&&(e.urls=(e.urls.some?e.urls:[e.urls]).filter(e=>e.match(r)),e.urls.length>0)?e:void 0))},ug=(e,t)=>{if(t&&e){const r=t,i=r.indexOf(":")>0?"":":443",n=":"+r+i;return e.map(e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,n)),t.urls&&(t.urls=t.urls.map(e=>e.replace(/:[^?]*/,n))),t})}return e},pg=[{pattern:/^(?:([^.]+)[.])?(server:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?(localhost:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?((\d+[.]){3}:?\d*)$/,separator:"."},{pattern:/^(?:([^.]+)-)?(ip-[^.]*[.](?:hereby[.]dev|rfc1918[.]disappear[.]at)(?::\d+|))$/,separator:"-"},{pattern:/^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/,separator:"."}];function hg({host:e="whereby.com",protocol:t="https:"}={}){let r="",i=e,n=".";for(const{separator:t,pattern:s}of pg){const o=s.exec(e);if(o){r=o[1]||"",i=o[2],n=t;break}}const s=r?`${r}${n}${i}`:i;return{domain:i,domainWithSeparator:`${n}${i}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${i}`,subdomain:r}}var fg,mg;hg(window&&window.location);const gg=null!==(fg=oi.default)&&void 0!==fg?fg:oi,vg=new Hh,bg=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=tm,this.stream=null,this.streamId=null}setup(e){return this.stream=e,this.streamId=e.id,this.setVideoEnabled(this.isVideoEnabled&&e.getVideoTracks().length>0),this.setAudioEnabled(this.isAudioEnabled&&e.getAudioTracks().length>0),this}setStatus(e){return this.status=e,this}setVideoEnabled(e){this.isVideoEnabled=e,this.stream&&this.stream.getVideoTracks().forEach(t=>{t.enabled=e})}setAudioEnabled(e){this.isAudioEnabled=e,this.stream&&this.stream.getAudioTracks().forEach(t=>{t.enabled=e})}static getCameraId(){return"0"}static getTypeFromId(e){return"0"===""+e?sm:om}}.getCameraId(),yg=gg.browserDetails.browser,wg=gg.browserDetails.version;"firefox"===yg&&gg.browserShim&&"shimGetDisplayMedia"in gg.browserShim&&(null===(mg=gg.browserShim)||void 0===mg||mg.shimGetDisplayMedia(window,"screen"));let _g=!1;"chrome"===yg&&window.document.addEventListener("beforeunload",()=>{_g=!0});class Sg{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s}){const{name:o,session:a,iceServers:c,turnServers:d,sfuServer:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._roomName=o,this._roomSessionId=a&&a.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._screenshareVideoTrackIds=[],this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction=null,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._isAudioOnlyMode=!1,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{Zh.sendEvent("audio_ended",{unloading:_g}),this._emit(Cm,{})},this._videoTrackOnEnded=()=>{Zh.sendEvent("video_ended",{unloading:_g}),this._emit(Rm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:u}),this.totalSessionsCreated=0}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._roomName===t&&r===!!this._sfuServer}supportsScreenShareAudio(){return!0}maybeRestrictRelayBandwidth(e){e.maybeRestrictRelayBandwidth()}addNewStream(e,t,r,i,n=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===bg){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=n.find(e=>"audio"===e.kind);t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=n.find(e=>"video"===e.kind);e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const i=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",i),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",i)})}this._screenshareVideoTrackIds.push(t.getVideoTracks()[0].id),this._shareScreen(e,t)}}replaceTrack(e,t){return"audio"!==t.kind||t.effectTrack||this._monitorAudioTrack(t),"video"!==t.kind||t.effectTrack||this._monitorVideoTrack(t),this._replaceTrackToPeerConnections(e,t)}disconnectAll(){Object.keys(this.peerConnections).forEach(e=>{this.disconnect(e)}),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null)}fixChromeAudio(e){if("chrome"!==yg)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then(e=>{const i=e.getAudioTracks()[0];return i.enabled=r.enabled,t.removeTrack(r),t.addTrack(i),this.replaceTrack(r,i)}):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(Af,e=>{e.error?vg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(Gf,e=>{this._connect(e.clientId)}),this._serverSocket.on(Uf,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):vg.warn("No RTCPeerConnection on ICE_CANDIDATE",e)}),this._serverSocket.on($f,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):vg.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)}),this._serverSocket.on(Hf,e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void vg.warn("No RTCPeerConnection on SDP_OFFER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=(t=i.handleOffer(n).then(t=>{this._emitServerEvent(qf,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})})).catch)||void 0===r||r.call(t,e=>{this._emit(Im,e)})}),this._serverSocket.on(qf,e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void vg.warn("No RTCPeerConnection on SDP_ANSWER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=null===(t=i.handleAnswer(n))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,e=>{this._emit(xm,e)})}),this._serverSocket.on(zf,e=>{var t,r;if(null==e?void 0:e.error)return;if(null!==(r=null===(t=null==e?void 0:e.room)||void 0===t?void 0:t.sfuServer)&&void 0!==r&&r||!this._wasScreenSharing)return;const i=Object.keys(this.localStreams).find(e=>e!==bg);if(!i)return;const n=this.localStreams[i];if(!n)return void vg.warn("screenshare stream %s not found",i);const s=n.getAudioTracks().length>0;this._emitServerEvent(If,{streamId:i,hasAudioTrack:s})})]}sendAudioMutedStats(e){Zh.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){Zh.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){Zh.sendEvent(e,t)}rtcStatsDisconnect(){Zh.server.close()}rtcStatsReconnect(){Zh.server.connected||Zh.server.connect()}setAudioOnly(e){this._isAudioOnlyMode=e,this._forEachPeerConnection(e=>{e.hasConnectedPeerConnection()&&this._withForcedRenegotiation(e,()=>e.setAudioOnly(this._isAudioOnlyMode,this._screenshareVideoTrackIds))})}setRemoteScreenshareVideoTrackIds(e=[]){const t=this._getFirstLocalNonCameraStream();this._screenshareVideoTrackIds=[...(null==t?void 0:t.track)?[t.track.id]:[],...e]}setRoomSessionId(e){this._roomSessionId=e}_setConnectionStatus(e,t,r){const i=e.connectionStatus;i!==t&&e.peerConnectionId!==this._selfId&&(i===nm&&t===tm||(e.connectionStatus=t,setTimeout(()=>{this._emit(Jf,{streamIds:e.streamIds,clientId:r,status:t,previous:i})},0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach(e=>{e.jitterBufferTarget=Rf,e.playoutDelayHint=.4})}catch(e){vg.error("Error during setting jitter buffer target:",e)}}_emitServerEvent(e,t,r){this._serverSocket.emit(e,t,r)}_emit(e,t){this._emitter.emit(e,t)}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let r=this.peerConnections[e];if(void 0===r){const i="safari"===yg&&wg&&wg>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new Of({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:this._features.unlimitedBandwidthWhenUsingRelayP2POn?-1:1280,deprioritizeH264Encoding:i}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[bg]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter(e=>e!==bg)}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e,t){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:r,peerConnectionId:i,shouldAddLocalVideo:n}){if(!i)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(i,t),o={optional:[]};"chrome"===yg&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:i}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};var c,d;a.iceServers=ug(a.iceServers,this._features.turnServerOverrideHost),c=a,(d=this._features).addGoogleStunServers&&(c.iceServers=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"},...c.iceServers]),d.addCloudflareStunServers&&(c.iceServers=[{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"},...c.iceServers]),lg(a,this._features),"chrome"===yg&&(a.sdpSemantics="unified-plan");const l=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:n,clientId:e});setTimeout(()=>this._emit(km),0),l.ontrack=t=>{const r=t.streams[0];"default"===r.id&&0===r.getAudioTracks().length||-1===s.streamIds.indexOf(r.id)&&(s.streamIds.push(r.id),this._emit(Qf,{clientId:e,stream:r}),s.connectionStatus===im&&setTimeout(()=>{this._emit(Jf,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:tm})},0))},l.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(l.iceConnectionState){case"checking":t=tm;break;case"connected":case"completed":t=im,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach(e=>{"function"==typeof e&&e()}),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(l.iceConnectionState.match(/connected|completed/)||"chrome"===yg&&l.localDescription&&"answer"===l.localDescription.type)&&(s.wasEverConnected=!0,"false"!==this._features.bandwidth&&this.maybeRestrictRelayBandwidth(s)),this._isAudioOnlyMode&&s.setAudioOnly(!0,this._screenshareVideoTrackIds),s.registerConnected();break;case"disconnected":t=nm,setTimeout(()=>{"disconnected"===l.iceConnectionState&&this._maybeRestartIce(e,s)},2e3);break;case"failed":t=rm,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(gm);break;default:return}this._setConnectionStatus(s,t,e)},l.onconnectionstate=()=>{switch(l.connectionState){case"connected":setTimeout(()=>{(function(e){if("chrome"!==Df.browserDetails.browser||Df.browserDetails.browser<58||"closed"===e.signalingState)return Promise.resolve(!1);const t=e.getSenders().some(e=>e.track&&"audio"===e.track.kind),r=e.getReceivers().some(e=>e.track&&"audio"===e.track.kind);return e.getStats(null).then(e=>{let i=!1;return e.forEach(e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!t?"inbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!r||0===e.bytesReceived&&(i="inbound"):0===e.bytesSent&&(i="outbound")}),i})})(s.pc).then(t=>{!1!==t&&this._emit(Sm,{failureDirection:t,clientId:e})})},3e3),s.registerConnected();break;case"failed":const t=rm;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(gm),this._setConnectionStatus(s,t,e)}};const u=this.localStreams[bg];return n&&u&&s.addStream(u),n&&Object.keys(this.localStreams).forEach(e=>{if(e===bg)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then(()=>{this._emitServerEvent(If,{receiverId:s.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(s,()=>s.addStream(t))})}),s}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):vg.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.values(this.peerConnections).forEach(t=>{e(t)})}_addStreamToPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.addStream(e))})}_addTrackToPeerConnections(e,t){this._forEachPeerConnection(r=>{this._withForcedRenegotiation(r,()=>r.addTrack(e,t))})}_replaceTrackToPeerConnections(e,t){const r=[];return this._forEachPeerConnection(i=>{if(!i.hasConnectedPeerConnection()){vg.info("Session doesn't have a connected PeerConnection, adding pending action!");const n=this._pendingActionsForConnectedPeerConnections;if(!n)return void vg.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise((r,s)=>{n.push(()=>{const n=i.replaceTrack(e,t);if(!n)return vg.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");n.then(e=>r(e)).catch(e=>s(e))})});return void r.push(s)}const n=i.replaceTrack(e,t);n?r.push(n):vg.error("replaceTrack returned false!")}),Promise.all(r)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeStream(e))})}_removeTrackFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeTrack(e))})}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,mediaserverConfigTtlSeconds:i}){this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._mediaserverConfigTtlSeconds=i,this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitServerEvent(xf),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_connect(e){let t=this._getSession(e),r=t&&t.bandwidth||0;return t?(vg.warn("Replacing peer session",e),this._cleanup(e)):r=this._changeBandwidthForAllClients(!0),t=this._createP2pSession({clientId:e,initialBandwidth:r,shouldAddLocalVideo:!0,isOfferer:!0}),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const r=t.pc;"disconnected"!==r.iceConnectionState&&"failed"!==r.iceConnectionState||"offer"===r.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,t.serverReflexiveCandidateSeen=!1,t.publicHostCandidateSeen=!1,t.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this._emit(_m),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e){return Wh(this,void 0,void 0,function*(){const{p2pVp9On:t,p2pAv1On:r,redOn:i,preferP2pHardwareDecodingOn:n}=this._features;if(t||r||i||n)try{const s=e.getTransceivers().filter(e=>{var t,r;return"audio"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});s.forEach(e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(i&&"audio/red"===t.codecs[e].mimeType.toLowerCase()){t.codecs.unshift(t.codecs.splice(e,1)[0]);break}void 0!==e.setCodecPreferences&&e.setCodecPreferences(t.codecs)});const o=e.getTransceivers().filter(e=>{var t,r;return"video"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});yield Promise.all(o.map(e=>Wh(this,void 0,void 0,function*(){if(void 0===RTCRtpReceiver.getCapabilities)return;if(void 0===e.setCodecPreferences)return;const i=RTCRtpReceiver.getCapabilities("video");(t||r||n)&&(i.codecs=yield ng(i.codecs,{vp9On:t,av1On:r,preferHardwareDecodingOn:t||n})),e.setCodecPreferences(i.codecs)})))}catch(e){vg.error("Error during setting setCodecPreferences:",e)}})}_negotiatePeerConnection(e,t,r){if(!t)return void vg.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const i=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push(()=>{this._negotiatePeerConnection(e,t,r)});t.isOperationPending=!0;const{p2pVp9On:n,redOn:s,rtpAbsCaptureTimeOn:o,cleanSdpOn:a}=this._features;this._setCodecPreferences(i).then(()=>i.createOffer(r||this.offerOptions).then(t=>{o&&(t.sdp=Sf(t.sdp)),(n||s)&&"firefox"===yg&&(t.sdp=function(e,t,r){var i,n;try{const s=xi(e);if(Array.isArray(null==s?void 0:s.media)){const e=s.media.find(e=>"audio"===e.type);if(Array.isArray(null==e?void 0:e.rtp)){const t=e.rtp;for(let n=0;n<t.length;n++)if(r&&"red"===t[n].codec){const r=null===(i=e.payloads)||void 0===i?void 0:i.split(" "),s=null==r?void 0:r.indexOf(""+t[n].payload);s&&-1!==s&&s>=0&&(null==r||r.unshift(r.splice(s,1)[0]),e.payloads=null==r?void 0:r.join(" "))}}const o=s.media.find(e=>"video"===e.type);if(Array.isArray(null==o?void 0:o.rtp)){const e=o.rtp;for(let r=0;r<e.length;r++)if(t&&"VP9"===e[r].codec){const t=null===(n=o.payloads)||void 0===n?void 0:n.split(" "),i=null==t?void 0:t.indexOf(""+e[r].payload);i&&-1!==i&&i>=0&&(null==t||t.unshift(t.splice(i,1)[0]),o.payloads=null==t?void 0:t.join(" "))}}}return Di(s)}catch(e){vf.error("setCodecPreferenceSDP error:",e)}}(t.sdp,n,s)),a&&(t.sdp=function(e){try{const t=xi(e);return t.media.forEach(e=>{const t={};e.payloads&&(e.payloads=(""+e.payloads).split(" ").filter(e=>!t[e]&&(t[e]=!0)).join(" "));const r={};e.rtp=e.rtp.filter(e=>!e.payload||t[e.payload]&&!r[e.payload]&&(r[e.payload]=!0));const i={};e.fmtp&&(e.fmtp=e.fmtp.filter(e=>!e.payload||t[e.payload]&&!i[e.payload]&&(i[e.payload]=!0)));const n={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter(e=>!e.payload||t[e.payload]&&!n[e.payload+e.type+e.subtype]&&(n[e.payload+e.type+e.subtype]=!0)))}),Di(t)}catch(e){}return e}(t.sdp)),i.setLocalDescription(t).catch(e=>{throw vg.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(Dm,e),e}).then(()=>{this._emitServerEvent(Hf,{receiverId:e,message:this._transformOutgoingSdp(t)})})}).catch(e=>{vg.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,i=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout(()=>r.onnegotiationneeded=i,0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);const r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:0,2:384,3:256,4:192,5:128,6:128,7:64}[t];return void 0===r?0:(this._forEachPeerConnection(e=>{e.changeBandwidth(r)}),r)}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:i=!1}){const n=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:i}),s=n.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[bg];return r&&o&&!o.getVideoTracks().length&&this._stoppedVideoTrack&&s.addTrack(this._stoppedVideoTrack,o),s.onicegatheringstatechange=e=>{switch(e.target.iceGatheringState){case"gathering":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=setTimeout(()=>{n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(wm)},3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,i;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(i=null==t?void 0:t.candidate)||void 0===i?void 0:i.address;try{if(mm.v4({exact:!0}).test(e)){Bn(e).isPublicIp&&(n.publicHostCandidateSeen=!0)}else if(mm.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new Ii.Address6(e.replace(/^\[(.*)\]/,"$1"));n.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(n.publicHostCandidateSeen=!0),t.isTeredo()&&(n.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(n.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&Hn(t,4)&&(n.mdnsHostCandidateSeen=!0)}}catch(e){vg.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":n.serverReflexiveCandidateSeen||(n.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":n.relayCandidateSeen||(n.relayCandidateSeen=!0)}this._emitServerEvent(Uf,{receiverId:e,message:t.candidate})}else this._emitServerEvent($f,{receiverId:e}),n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(ym),n.ipv6HostCandidateSeen&&this._emit(vm,{teredoSeen:n.ipv6HostCandidateTeredoSeen,sixtofourSeen:n.ipv6HostCandidate6to4Seen}),n.mdnsHostCandidateSeen&&this._emit(bm)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&n.connectionStatus&&this._negotiatePeerConnection(e,n)},n}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let i=this._getSession(t);if(i&&e!==t)return i;let n=i&&i.bandwidth||0;return i?(vg.warn("Replacing peer session",t),this._cleanup(t)):n=this._changeBandwidthForAllClients(!0),i=this._createP2pSession({clientId:t,initialBandwidth:n,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(Gf,{receiverId:t}),i}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout(()=>{0===this.numberOfPeerconnections()&&this.rtcStatsDisconnect()},6e4)}updateStreamResolution(){}stopOrResumeAudio(){}_handleStopOrResumeVideo({enable:e,track:t}){e?this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(t):this._stoppedVideoTrack=t}stopOrResumeVideo(e,t){var r;if(["chrome","safari"].includes(yg))if(!1===t){const i="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emit(em,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},i)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emit(Zf,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})})}}_shareScreen(e,t){this._emitServerEvent(If,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._wasScreenSharing=!0,this._addStreamToPeerConnections(t)}removeStream(e,t,r){this._removeLocalStream(e),this._removeStreamFromPeerConnections(t),this._wasScreenSharing=!1,this._emitServerEvent(Mf,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}var Cg=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:i=1,C:n=1.2}={R:.01,Q:2,A:1.1,B:1,C:1.2}){this.R=e,this.Q=t,this.A=r,this.C=n,this.B=i,this.cov=NaN,this.x=NaN}filter(e,t=0){if(isNaN(this.x))this.x=1/this.C*e,this.cov=1/this.C*this.Q*(1/this.C);else{const r=this.predict(t),i=this.uncertainty(),n=i*this.C*(1/(this.C*i*this.C+this.Q));this.x=r+n*(e-this.C*r),this.cov=i-n*this.C*i}return this.x}predict(e=0){return this.A*this.x+this.B*e}uncertainty(){return this.A*this.cov*this.A+this.R}lastMeasurement(){return this.x}setMeasurementNoise(e){this.Q=e}setProcessNoise(e){this.R=e}},calculateStd:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,r)=>e.concat(Math.pow(r-t,2)),[]).reduce((e,t)=>e+t,0)/e.length},createACFCalculator:()=>{let e=-1,t=0,r=0;return i=>{const n=i.reduce((e,t)=>e+t,0)/i.length;if(e=e<0?n:.95*e+.05*n,++r<2)return t=n,0;const s=(n-e)*(t-e);return t=n,s}},standardDeviation:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return{mean:t,SD:Math.sqrt(e.reduce((e,r)=>e+Math.pow(r-t,2),0)/e.length)}},variance:(e,t=!1)=>{const r=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,t)=>e.concat(Math.pow(t-r,2)),[]).reduce((e,t)=>e+t,0)/(e.length-(t?0:1))}});const Rg={minDecibels:-80,maxDecibels:-10,smoothingTimeConstant:.8,aggSize:1,sampleRate:10,reportRate:2,bins:32,bands:[[0,1,2,3],[4,5,6,7]],separateTrack:{autoGainControl:!1,noiseSupression:!1},binFormula:"bin",scoreFormula:"300 * bands[1].avg / Math.max(bands[1].avg + bands[0].avg, 0.01)",outFormula:"score"},kg=new Hh;const Tg=new Hh,Pg=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class Og extends bp{constructor(){super(),this._clients={},this._producers={},this._startMonitor()}close(){clearInterval(this._intervalHandle),delete this._intervalHandle,this._producers={},this._clients={}}_startMonitor(){this._intervalHandle=setInterval(()=>{Object.entries(this._producers).forEach(([e,t])=>{this._evaluateClient(e,t)})},600)}_evaluateClient(e,t){this._clients[e]||(this._clients[e]={audio:{currentQuality:Pg.ok,trend:[]},video:{currentQuality:Pg.ok,trend:[]}}),this._evaluateProducer(e,Object.values(t).filter(e=>"audio"===e.kind),"audio"),this._evaluateProducer(e,Object.values(t).filter(e=>"video"===e.kind),"video")}_evaluateProducer(e,t,r){if(0===t.length)return;const i=t.reduce((e,t)=>e+t.score,0)/t.length,n=this._evaluateScore(i);this._updateTrend(n,this._clients[e][r])&&this.emit(Kf,{clientId:e,kind:r,quality:n})}_updateTrend(e,t){return t.trend.push(e),t.trend.length>3&&t.trend.shift(),!(e===t.currentQuality||!t.trend.every(e=>e!==t.currentQuality))&&(t.currentQuality=e,!0)}addProducer(e,t){e&&t&&"string"==typeof e&&"string"==typeof t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Tg.warn("Missing clientId or producerId")}removeProducer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addConsumer(e,t){e&&t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Tg.warn("Missing clientId or consumerId")}removeConsumer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addProducerScore(e,t,r,i){Array.isArray(i)&&0!==i.length&&!i.some(e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.map(e=>e.score))}:Tg.warn("Unexpected producer score format")}addConsumerScore(e,t,r,i){i&&i.hasOwnProperty("producerScores")&&Array.isArray(i.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.producerScores)}:Tg.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?Pg.warning:e<=7&&e>0?Pg.critical:Pg.ok}_calcAvgProducerScore(e){try{if(!Array.isArray(e)||0===e.length)return 0;let t=0,r=0;return e.forEach(e=>{e>0&&(t+=e,r++)}),0===t||0===r?0:t/r}catch(e){return Tg.error(e),0}}}class Eg{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?Eg._handleRequest(t):t.response?Eg._handleResponse(t):t.message?Eg._handleMessage(t):void 0}static _handleRequest(e){const t={request:!0};if("string"==typeof e.method&&"number"==typeof e.id)return t.id=e.id,t.method=e.method,t.data=e.data||{},t}static _handleResponse(e){const t={response:!0};if("number"==typeof e.id)return t.id=e.id,e.ok?(t.ok=!0,t.data=e.data||{}):(t.ok=!1,t.errorCode=e.errorCode,t.errorReason=e.errorReason),t}static _handleMessage(e){const t={message:!0};if("string"==typeof e.method)return t.method=e.method,t.data=e.data||{},t}static createRequest(e,t){return{request:!0,id:Math.round(1e7*Math.random()),method:e,data:t||{}}}static createSuccessResponse(e,t){return{response:!0,id:e.id,ok:!0,data:t||{}}}static createErrorResponse(e,t,r){return{response:!0,id:e.id,errorCode:t,errorReason:r}}static createMessage(e,t){return{message:!0,method:e,data:t||{}}}}const Dg=new Hh;class xg extends bp{constructor(e,t="whereby-sfu#v4"){super(),this.socket=null,this.wsUrl=e,this.protocol=t,this.sents=new Map,this._setupSocket()}_setupSocket(){this.socket=new WebSocket(this.wsUrl,this.protocol),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=this._onClose.bind(this),this.socket.onerror=this._onError.bind(this)}_tearDown(){null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket=null,this.sents.forEach(e=>e.close()),this.emit("close"))}close(){var e;null===(e=this.socket)||void 0===e||e.close()}_onOpen(){Dg.info("Connected"),this.emit("open")}_onMessage(e){const t=Eg.parse(e.data);Dg.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){Dg.info("Disconnected"),this._tearDown()}_onError(e){Dg.info("Error",e)}_handleResponse(e){const t=this.sents.get(e.id);if(e.ok)t.resolve(e.data);else{const r=new Error(e.errorReason);t.reject(r)}}send(e){try{this.socket&&this.socket.send(JSON.stringify(e))}catch(e){}}message(e,t={}){const r=Eg.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const i=Eg.createRequest(e,t);return this.send(i),new Promise((e,t)=>{const n={id:i.id,method:i.method,resolve:t=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),e(t))},reject:e=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),t(e))},timer:setTimeout(()=>{this.sents.delete(i.id)&&t(new Error("request timeout"))},r),close:()=>{clearTimeout(n.timer),t(new Error("transport closed"))}};this.sents.set(i.id,n)})}}function Ig(e){let t,r,i,n,s=[];const o=e=>{s=function(e){return"string"==typeof e?e.split(",").filter(Boolean).map(e=>{const[t,r]=/\|/.test(e)?e.split("|"):["",e];return{host:r,dc:t}}):e.filter(e=>e.host).map(e=>({host:e.host,dc:e.dc||""}))}(e)};let a=!1,c=!1;const d=()=>{if(a)return void(c=!0);a=!0,c=!1;let o=s;if(t){const e=Date.now();e-3e3>(r||0)&&((!n||(i||0)>n)&&e-3e3>(i||0))||(o=[{host:t.host,dc:t.dc}])}const l={};let u=0;o.forEach(({dc:e})=>{void 0===l[e]&&(l[e]=u++)});let p=0;const h={};let f,m=o.length,g=!1,v=!1;const b=n,y=()=>{var t;m--,0!==m||g||(a=!1,c?setTimeout(d,0):null===(t=e.onFailed)||void 0===t||t.call(e))},w=[];o.forEach(({host:i,dc:s},d)=>{if(d>0){p+=500;const e=(h[s]||0)+2e3;p=Math.max(p,e)}h[s]=p,w.push(setTimeout(()=>{var u;if(w.shift(),v)return;if(b!==n)return y(),void w.forEach(e=>{clearTimeout(e),y()});const p=new xg((null===(u=e.getUrlForHost)||void 0===u?void 0:u.call(e,i))||i);let h=!1;p.on("open",()=>{setTimeout(()=>{var r;if(!h)if(f||v)p.close();else{f=p,v=!0;const n=[...new Set(o.slice(0,d).filter(e=>e.host!==i).map(e=>e.host))],u=[...new Set(o.slice(0,d).filter(e=>e.dc!==s).map(e=>e.dc))];t=t?Object.assign(Object.assign({},t),{host:i,dc:s,failedHosts:[...new Set([...n,...t.failedHosts])].filter(e=>e!==i&&!t.usedHosts.includes(e)),failedDCs:[...new Set([...u,...t.failedDCs])].filter(e=>e!==s&&!t.usedDCs.includes(e)),usedHosts:[...new Set([...t.usedHosts,i])],usedDCs:[...new Set([...t.usedDCs,s])],numConnections:t.numConnections+1}):{host:i,dc:s,initialHost:i,initialDC:s,initialHostIndex:d,initialDCIndex:l[s],failedHosts:n,failedDCs:u,usedHosts:[i],usedDCs:[s],numConnections:1,numUsedDCs:1,numUsedHosts:1,numFailedDCs:0,numFailedHosts:0},t.numUsedDCs=t.usedDCs.length,t.numUsedHosts=t.usedHosts.length,t.numFailedDCs=t.failedDCs.length,t.numFailedHosts=t.failedHosts.length,c=!1,a=!1,null===(r=e.onConnected)||void 0===r||r.call(e,p,t)}},100)}),p.on("close",()=>{var t;h=!0,p===f&&(f=void 0,r=Date.now(),g=!0,null===(t=e.onDisconnected)||void 0===t||t.call(e)),y()})},p))})};o(e.initialHostList);return{connect:d,updateHostList:o,networkIsUp:()=>{i=Math.max(Date.now(),i||0)},networkIsPossiblyDown:()=>{n=Date.now()}}}var Mg;const jg=null!==(Mg=oi.default)&&void 0!==Mg?Mg:oi,Lg=new Hh,Ag=jg.browserDetails.browser;let Ng=!1;const Bg=mi(),Fg=mi();"chrome"===Ag&&window.document.addEventListener("beforeunload",()=>Ng=!0);class zg{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s,eventClaim:o}){const{session:a,iceServers:c,turnServers:d,sfuServer:l,sfuServers:u,mediaserverConfigTtlSeconds:p}=t;this._selfId=e,this._room=t,this._roomSessionId=null==a?void 0:a.id,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDevice=(e=>{var t;if(e.isNodeSdk)return new Wn.Device({handlerFactory:fl.createFactory()});let r=Wn.detectDevice()||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);if("Safari12"===r&&"object"==typeof navigator&&"string"==typeof navigator.userAgent){const i=new gp.UAParser(navigator.userAgent).getBrowser();parseInt(null!==(t=i.major)&&void 0!==t?t:"0")>=17&&e.safari17HandlerOn&&(r="Safari17")}return/iphone|ipad/i.test(navigator.userAgent)&&(r=e.safari17HandlerOn?"Safari17":"Safari12"),"Safari17"===r?new Wn.Device({handlerFactory:Fm.createFactory()}):new Wn.Device({handlerName:r})})(s),this._routerRtpCapabilities=null,this._sendTransport=null,this._receiveTransport=null,this._clientStates=new Map,this._streamIdToVideoConsumerId=new Map,this._streamIdToVideoResolution=new Map,this._consumers=new Map,this._dataConsumers=new Map,this._localStreamDeregisterFunction=null,this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._micProducer=null,this._micProducerPromise=null,this._micPaused=!1,this._micScoreProducer=null,this._micScoreProducerPromise=null,this._webcamProducer=null,this._webcamProducerPromise=null,this._webcamPaused=!1,this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._sndTransportIceRestartPromise=null,this._rcvTransportIceRestartPromise=null,this._colocation=null,this._stopCameraTimeout=null,this._audioTrackOnEnded=()=>{Zh.sendEvent("audio_ended",{unloading:Ng}),this._emitToPWA(Cm,{})},this._videoTrackOnEnded=()=>{Zh.sendEvent("video_ended",{unloading:Ng}),this._emitToPWA(Rm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,sfuServers:u,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:p}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._isConnectingOrConnected=!1,this._qualityMonitor=new Og,this._qualityMonitor.on(Kf,e=>{this._emitToPWA(Kf,e)}),this._networkIsDetectedUpBySignal=!1}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,sfuServers:i,mediaserverConfigTtlSeconds:n}){var s,o,a;this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._sfuServers=i,!i&&(null==r?void 0:r.fallbackServers)&&(this._sfuServers=r.fallbackServers.map(e=>({host:e.host||e.fqdn,dc:e.dc}))),this._mediaserverConfigTtlSeconds=n,null===(s=this._vegaConnectionManager)||void 0===s||s.updateHostList(this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||r.url);const c={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};c.iceServers=ug(c.iceServers,this._features.turnServerOverrideHost),null===(o=this._sendTransport)||void 0===o||o.updateIceServers(c),null===(a=this._receiveTransport)||void 0===a||a.updateIceServers(c),this._clearMediaServersRefresh(),n&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitToSignal(xf),1e3*n))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_onNetworkIsDetectedUpBySignal(){var e;this._networkIsDetectedUpBySignal||(this._networkIsDetectedUpBySignal=!0,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsUp())}_onNetworkIsDetectedPossiblyDownBySignal(){var e;this._networkIsDetectedUpBySignal&&(this._networkIsDetectedUpBySignal=!1,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsPossiblyDown())}setupSocketListeners(){this._socketListenerDeregisterFunctions.push(()=>this._clearMediaServersRefresh(),this._serverSocket.on(Af,e=>{e.error?Lg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(zf,e=>{(null==e?void 0:e.error)||(this._screenVideoTrack&&this._emitScreenshareStarted(),this._features.sfuReconnectV2On&&this._reconnect&&this._connect())}),this._serverSocket.on("connect",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.onEngineEvent("packet",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.on("disconnect",()=>this._onNetworkIsDetectedPossiblyDownBySignal())),this._connect()}_emitScreenshareStarted(){this._emitToSignal(If,{streamId:Fg,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(this._features.sfuReconnectV2On){if(this._isConnectingOrConnected)return;if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut)}if(!this._vegaConnectionManager){const e=this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||this._sfuServer.url;this._vegaConnectionManager=Ig({initialHostList:e,getUrlForHost:e=>{const t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter(e=>this._features[e]&&/^sfu/.test(e)).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]}),{})));return`wss://${e}?${t.toString()}`},onConnected:(e,t)=>{this._vegaConnection=e,this._vegaConnection.on("message",e=>this._onMessage(e)),this._emitToPWA(Om,t),this._join()},onDisconnected:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()},onFailed:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()}})}this._vegaConnectionManager.connect(),this._isConnectingOrConnected=!0}_onClose(){var e,t;Lg.info("_onClose()"),null===(e=this._sendTransport)||void 0===e||e.close(),null===(t=this._receiveTransport)||void 0===t||t.close(),this._sendTransport=null,this._receiveTransport=null,this._streamIdToVideoConsumerId.clear(),this._streamIdToVideoResolution.clear(),this._reconnect&&(this._reconnectTimeOut=setTimeout(()=>this._connect(),1e3)),this._qualityMonitor.close(),this._emitToPWA(Pm)}_join(){return Wh(this,void 0,void 0,function*(){var e,t;Lg.info("join()"),this._emitToPWA(Tm);try{const{routerRtpCapabilities:r}=yield this._vegaConnection.request("getCapabilities");if(!this._routerRtpCapabilities){const t=((e,t)=>{const{vp9On:r,h264On:i}=t,n="chrome"===oi.browserDetails.browser;if(!(null==e?void 0:e.codecs))return e;if(r&&n){const t=rg(e.codecs,tg.VP9);return Object.assign(Object.assign({},e),{codecs:t})}if(i){const t=rg(e.codecs,tg.H264);return Object.assign(Object.assign({},e),{codecs:t})}return e})(r,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}));this._routerRtpCapabilities=t,yield null===(e=this._mediasoupDevice)||void 0===e?void 0:e.load({routerRtpCapabilities:t})}this._vegaConnection.message("setCapabilities",{rtpCapabilities:null===(t=this._mediasoupDevice)||void 0===t?void 0:t.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const i=[];!this._micTrack||this._micProducer||this._micProducerPromise||i.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||i.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||i.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||i.push(this._internalSendScreenAudio()),yield Promise.all(i)}catch(e){Lg.error("_join() [error:%o]",e)}})}_createTransport(e){return Wh(this,void 0,void 0,function*(){var t;const r=e?"createSendTransport":"createRecvTransport",i=yield this._vegaConnection.request("createTransport",{producing:e,consuming:!e,enableTcp:!0,enableUdp:!0,preferUdp:!0,sctpParameters:{enableSctp:!0,numSctpStreams:{OS:1024,MIS:1024},maxSctpMessageSize:262144,sctpSendBufferSize:262144}});i.iceServers=ug(this._features.turnServersOn?this._turnServers:this._iceServers,this._features.turnServerOverrideHost),lg(i,this._features);const n=null===(t=this._mediasoupDevice)||void 0===t?void 0:t[r](i),s=t=>Wh(this,void 0,void 0,function*(){if(Lg.info(`Transport ConnectionStateChanged ${t}`),"disconnected"===t||"failed"===t)if(e){if(this._sndTransportIceRestartPromise)return;this._sndTransportIceRestartPromise=this._restartIce(n).finally(()=>{this._sndTransportIceRestartPromise=null})}else{if(this._rcvTransportIceRestartPromise)return;this._rcvTransportIceRestartPromise=this._restartIce(n).finally(()=>{this._rcvTransportIceRestartPromise=null})}});null==n||n.on("connect",({dtlsParameters:e},t)=>{var r;null===(r=this._vegaConnection)||void 0===r||r.message("connectTransport",{transportId:n.id,dtlsParameters:e}),t()}).on("connectionstatechange",s),null==n||n.observer.once("close",()=>{n.removeListener("connectionstatechange",s)}),e?(null==n||n.on("produce",(e,t,r)=>Wh(this,[e,t,r],void 0,function*({kind:e,rtpParameters:t,appData:r},i,s){var o;try{const{paused:s}=r,{id:a}=yield null===(o=this._vegaConnection)||void 0===o?void 0:o.request("produce",{transportId:n.id,kind:e,rtpParameters:t,paused:s,appData:r});i({id:a})}catch(e){s(e)}})),null==n||n.on("producedata",(e,t,r)=>Wh(this,[e,t,r],void 0,function*({appData:e,sctpStreamParameters:t},r,i){var s;try{const{id:i}=yield null===(s=this._vegaConnection)||void 0===s?void 0:s.request("produceData",{transportId:n.id,sctpStreamParameters:t,appData:e});r({id:i})}catch(e){i(e)}})),this._sendTransport=n):this._receiveTransport=n})}_restartIce(e){return Wh(this,arguments,void 0,function*(e,t=0){if(!e||!("closed"in e)||!("connectionState"in e))return void Lg.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void Lg.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void Lg.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,i=Date.now();if(Number.isFinite(r)&&i-r<3500)return;if(e.appData.iceRestartStarted=i,5<=t)return void Lg.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void Lg.info("_restartIce: Connection is undefined");const{iceParameters:n}=yield this._vegaConnection.request("restartIce",{transportId:e.id});Lg.info("_restartIce: ICE restart iceParameters received from SFU: ",n);const s=yield e.restartIce({iceParameters:n}).then(()=>null).catch(e=>e);if(s)switch(Lg.error(`_restartIce: ICE restart failed: ${s}`),s.message){case"missing transportId":case"no such transport":break;default:yield new Promise(e=>{setTimeout(()=>{e(void 0)},Math.min(3500*Math.pow(2,t),6e4))}),yield this._restartIce(e,t+1)}else yield new Promise(e=>{setTimeout(()=>{e(void 0)},6e4*Math.min(8,t+1))}),"failed"!==e.connectionState&&"disconnected"!==e.connectionState||(yield this._restartIce(e,t+1))})}_internalSendMic(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSendMic()"),this._micProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._micTrack||!this._sendTransport||this._micProducer)return void(this._micProducerPromise=null);const e=this._micPaused,t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._micTrack,disableTrackOnPause:!1,stopTracks:!1},Xm("audio",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:Bg,sourceClientId:this._selfId,screenShare:!1,source:"mic",paused:e}}));e?t.pause():t.resume(),this._micProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",()=>{var e;Lg.info('micProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._micProducer=null,this._micProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)}),this._micTrack!==this._micProducer.track&&(yield this._replaceMicTrack()),this._micPaused!==this._micProducer.paused&&this._pauseResumeMic()}catch(e){Lg.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}}))()})}_internalSetupMicScore(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._micProducer||!this._colocation||this._micScoreProducer)return void(this._micScoreProducerPromise=null);const e=yield this._sendTransport.produceData({ordered:!1,maxPacketLifeTime:3e3,label:"micscore",appData:{producerId:this._micProducer.id,clientId:this._selfId}});this._micScoreProducer=e,e.observer.once("close",()=>{var t;Lg.info('micScoreProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeDataProducers",{dataProducerIds:[e.id]})),this._micScoreProducer=null,this._micScoreProducerPromise=null})}catch(e){Lg.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}}))()})}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){return Wh(this,void 0,void 0,function*(){var e;Lg.info("_replaceMicTrack()"),this._micTrack&&this._micProducer&&!this._micProducer.closed&&this._micProducer.track!==this._micTrack&&(yield this._micProducer.replaceTrack({track:this._micTrack}),null===(e=this._micAnalyser)||void 0===e||e.setTrack(this._micTrack),yield this._replaceMicTrack())})}_pauseResumeMic(){var e,t;Lg.info("_pauseResumeMic()"),this._micProducer&&!this._micProducer.closed&&this._micPaused!==this._micProducer.paused&&(this._micPaused?(this._micProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._micProducer.id]})):(this._micProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._micProducer.id]})),this._pauseResumeMic())}_sendMic(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendMic() [track:%o]",e),this._micTrack=e,this._micProducer?yield this._replaceMicTrack():this._micProducerPromise?void 0:this._sendTransport?yield this._internalSendMic():void 0})}_sendMicScore(e){if(!isNaN(e)&&isFinite(e))if(this._micScoreProducer){if(this._micScoreProducer.closed)return void this._stopMicScoreProducer();try{this._micScoreProducer.send(JSON.stringify({score:e}))}catch(e){Lg.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_internalSendWebcam(){return Wh(this,void 0,void 0,function*(){var e;Lg.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>Wh(this,void 0,void 0,function*(){var e;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},Xm("video",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:Bg,sourceClientId:this._selfId,screenShare:!1,source:"webcam",paused:t}}));t?r.pause():r.resume(),this._webcamProducer=r,this._qualityMonitor.addProducer(this._selfId,r.id),r.observer.once("close",()=>{var e;Lg.info('webcamProducer "close" event'),r.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[r.id]})),this._webcamProducer=null,this._webcamProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,r.id)}),this._webcamTrack&&this._webcamTrack!==(null===(e=this._webcamProducer)||void 0===e?void 0:e.track)&&(this._webcamProducerPromise=null,this._replaceWebcamTrack()),this._webcamPaused!==this._webcamProducer.paused&&this._pauseResumeWebcam()}catch(e){Lg.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null)}}))())})}_replaceWebcamTrack(){return Wh(this,void 0,void 0,function*(){Lg.info("_replaceWebcamTrack()"),this._sendTransport&&this._webcamTrack&&!this._webcamProducerPromise&&(this._webcamProducer||!this._webcamTrack.enabled?this._webcamProducer.track!==this._webcamTrack&&(yield this._webcamProducer.replaceTrack({track:this._webcamTrack}),yield this._replaceWebcamTrack()):yield this._internalSendWebcam())})}_pauseResumeWebcam(){var e,t;Lg.info("_pauseResumeWebcam()"),this._webcamProducer&&!this._webcamProducer.closed&&this._webcamPaused!==this._webcamProducer.paused&&(this._webcamPaused?(this._webcamProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._webcamProducer.id]})):(this._webcamProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._webcamProducer.id]})),this._pauseResumeWebcam())}_sendWebcam(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendWebcam() [track:%o]",e),this._webcamTrack=e,this._webcamProducer?yield this._replaceWebcamTrack():this._webcamProducerPromise?void 0:this._sendTransport?yield this._internalSendWebcam():void 0})}_internalSendScreenVideo(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1},Xm("video",!0,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}),this._getIsSomeoneAlreadyPresenting())),{appData:{streamId:Fg,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",()=>{var t;Lg.info('screenVideoProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)}),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack())}catch(e){Lg.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null)}}))()})}_replaceScreenVideoTrack(){return Wh(this,void 0,void 0,function*(){Lg.info("_replaceScreenVideoTrack()"),this._screenVideoTrack&&this._screenVideoProducer&&!this._screenVideoProducer.closed&&this._screenVideoProducer.track!==this._screenVideoTrack&&(yield this._screenVideoProducer.replaceTrack({track:this._screenVideoTrack}),yield this._replaceScreenVideoTrack())})}_sendScreenVideo(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendScreenVideo() [track:%o]",e),this._screenVideoTrack=e,this._screenVideoProducer?yield this._replaceScreenVideoTrack():this._screenVideoProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenVideo():void 0})}_internalSendScreenAudio(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._screenAudioTrack||!this._sendTransport||this._screenAudioProducer)return void(this._screenAudioProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenAudioTrack,disableTrackOnPause:!1,stopTracks:!1},Xm("audio",!0,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:Fg,sourceClientId:this._selfId,screenShare:!0,source:"screenaudio",paused:!1}}));this._screenAudioProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",()=>{var t;Lg.info('screenAudioProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)}),this._screenAudioTrack!==this._screenAudioProducer.track&&(yield this._replaceScreenAudioTrack())}catch(e){Lg.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}}))()})}_replaceScreenAudioTrack(){return Wh(this,void 0,void 0,function*(){Lg.info("_replaceScreenAudioTrack()"),this._screenAudioTrack&&this._screenAudioProducer&&!this._screenAudioProducer.closed&&this._screenAudioProducer.track!==this._screenAudioTrack&&(yield this._screenAudioProducer.replaceTrack({track:this._screenAudioTrack}),yield this._replaceScreenAudioTrack())})}_sendScreenAudio(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendScreenAudio() [track:%o]",e),this._screenAudioTrack=e,this._screenAudioProducer?yield this._replaceScreenAudioTrack():this._screenAudioProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenAudio():void 0})}_stopProducer(e){Lg.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}_getIsSomeoneAlreadyPresenting(){return!![...this._clientStates.values()].find(e=>e.hasAcceptedScreenStream&&e.screenStream)}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._room.name===t&&Boolean(r)}setEventClaim(e){var t;this._eventClaim=e,null===(t=this._vegaConnection)||void 0===t||t.message("eventClaim",{eventClaim:e})}setColocation(e){var t;this._colocation=e,null===(t=this._vegaConnection)||void 0===t||t.message("setColocation",{colocation:e}),e||!this._micScoreProducer||this._micScoreProducerPromise||this._stopMicScoreProducer(),this._syncMicAnalyser(),Zh.sendEvent("colocation_changed",{colocation:e})}setAudioOnly(e){var t;null===(t=this._vegaConnection)||void 0===t||t.message(e?"enableAudioOnly":"disableAudioOnly")}setRemoteScreenshareVideoTrackIds(){}setRoomSessionId(e){this._roomSessionId=e}disconnect(e,t,r){var i;Lg.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r);const n=this._clientStates.get(e);n&&(n.hasAcceptedWebcamStream=!1,n.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)),r&&(this._eventClaim=r,null===(i=this._vegaConnection)||void 0===i||i.message("eventClaim",{eventClaim:r}))}replaceTrack(e,t){"audio"===t.kind&&(t.effectTrack||this._monitorAudioTrack(t),this._micTrack=t,this._replaceMicTrack()),"video"===t.kind&&(t.effectTrack||this._monitorVideoTrack(t),this._webcamTrack=t,this._replaceWebcamTrack())}removeStream(e,t,r){Lg.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(Mf,{streamId:Fg,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null}_onMicAnalyserScoreUpdated(e){var t,r;null===(r=null===(t=this._micAnalyserDebugger)||void 0===t?void 0:t.onScoreUpdated)||void 0===r||r.call(t,e),this._sendMicScore(this._micPaused?0:e.out)}addNewStream(e,t,r,i,n=[]){if("0"===e){this._micPaused=r,this._webcamPaused=i;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=n.find(e=>"video"===e.kind);t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=n.find(e=>"audio"===e.kind);e&&this._monitorAudioTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const o=e=>{const{enable:t,track:r}=e.detail;this._webcamPaused=!t,this._pauseResumeWebcam(),this._handleStopOrResumeVideo({enable:t,track:r})};t.addEventListener("stopresumevideo",o),this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",o)}}else{const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];e&&this._sendScreenVideo(e),r&&this._sendScreenAudio(r),this._emitScreenshareStarted()}}_syncMicAnalyser(){if(!this._micTrack||!this._colocation||this._micAnalyser)return this._micAnalyser&&!this._colocation?(this._micAnalyser.close(),void(this._micAnalyser=null)):void 0;this._micAnalyser=function({micTrack:e,params:t,onScoreUpdated:r}){const i=new AudioContext;let n=null,s=null,o=null,a=!1;const c=e=>Wh(this,void 0,void 0,function*(){if(o&&a&&o.stop(),a=!1,e&&t.separateTrack)try{const r=yield navigator.mediaDevices.getUserMedia({audio:Object.assign({deviceId:null==o?void 0:o.getSettings().deviceId},t.separateTrack),video:!1});e=r.getAudioTracks()[0],a=!0}catch(e){kg.warn("unable to fetch new track for colocation speaker analysis, using current",e)}if(o=e,s&&(s.disconnect(),s=null),e){const t=new MediaStream([e]);s=i.createMediaStreamSource(t),s.connect(n)}});let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},Rg),e),!n||n.fftSize!==2*t.bins){let e=null;n&&(e=o,c(null)),n=i.createAnalyser(),n.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(n.frequencyBinCount),a=[];n.minDecibels=t.minDecibels,n.maxDecibels=t.maxDecibels,n.smoothingTimeConstant=t.smoothingTimeConstant;const l=t.initScript&&new Function("f","setTrack","lastTrack",t.initScript.join("\n")),u=t.scoreScript&&new Function("bins","g","f",t.scoreScript.join("\n")),p=t.scoreFormula&&new Function("bands",`return ${t.scoreFormula}`),h=t.outFormula&&new Function("score","avg","max","scores",`return ${t.outFormula}`),f=t.binFormula&&new Function("bin","index",`return ${t.binFormula}`);let m=0;const g=l&&l(Cg,c,o);d=setInterval(()=>{n.getByteFrequencyData(s);let e=0;if(p){const r=t.bands.map(e=>{const t=e.map(e=>f(s[e]/255,e));return{avg:t.reduce((e,t)=>e+t,0)/e.length,min:t.reduce((e,t)=>Math.min(e,t/255),Number.MAX_VALUE),max:t.reduce((e,t)=>Math.max(e,t/255),0)}});e=p(r)||0}else u&&(e=u(s,g,Cg),isNaN(e)&&(e=0));if(a.push(e),a.length>t.aggSize&&a.shift(),m++,m>=t.reportRate){m=0;const t=a.reduce((e,t)=>Math.max(e,t),0),i=a.reduce((e,t)=>e+t,0)/a.length,n=h(e,i,t,a);r({bins:s,score:e,max:t,avg:i,out:n})}},1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),i.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){Lg.info("stopOrResumeAudio() [enabled:%s]",t),this._micPaused=!t,this._pauseResumeMic()}_handleStopOrResumeVideo({enable:e,track:t}){e?this._sendWebcam(t):this._webcamProducer&&!this._webcamProducer.closed&&this._webcamProducer.track===t&&(this._stopProducer(this._webcamProducer),this._webcamProducer=null,this._webcamTrack=null)}stopOrResumeVideo(e,t){var r;if(Lg.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(Ag))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emitToPWA(Zf,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})})}}else{clearTimeout(this._stopCameraTimeout);const i="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;this._stopCameraTimeout=setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emitToPWA(em,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},i)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){Lg.info("acceptNewStream()",{streamId:e,clientId:t});const r=this._getOrCreateClientState(t);e!==t?(r.hasAcceptedScreenStream=!0,r.hasEmittedScreenStream=!1):(r.hasAcceptedWebcamStream=!0,r.hasEmittedWebcamStream=!1),this._syncIncomingStreamsWithPWA(t)}updateStreamResolution(e,t,{width:r,height:i}){var n,s;Lg.info("updateStreamResolution()",{streamId:e,width:r,height:i});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:i});const c=function(e){let t=0;return e.forEach(e=>{var r,i;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(i=e._appData)||void 0===i?void 0:i.source)||t++}),t}(this._consumers),d=function(e){var t,r,i;return/T3/.test((null===(i=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===i?void 0:i.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:i,uncappedSingleRemoteVideoOn:n}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=i-1;return s<100&&(a=Math.max(i-2,0)),r>8&&0===o&&(a=Math.max(i-2,0)),r<4&&s>300&&0===o&&(o=1),n&&1===r&&(o=2,a=i-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:i},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(n=this._features)||void 0===n?void 0:n.uncappedSingleRemoteVideoOn});a.appData.spatialLayer===l&&a.appData.temporalLayer===u||(a.appData.spatialLayer=l,a.appData.temporalLayer=u,null===(s=this._vegaConnection)||void 0===s||s.message("setConsumersPreferredLayers",{consumerIds:[o],spatialLayer:l,temporalLayer:u}))}disconnectAll(){var e,t,r,i;this._reconnect=!1,this._reconnectTimeOut&&(clearTimeout(this._reconnectTimeOut),this._reconnectTimeOut=null),this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null),this._socketListenerDeregisterFunctions=[],null===(e=this._vegaConnection)||void 0===e||e.removeAllListeners(),null===(t=this._vegaConnection)||void 0===t||t.close(),null===(r=this._sendTransport)||void 0===r||r.close(),null===(i=this._receiveTransport)||void 0===i||i.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDevice=null}sendAudioMutedStats(e){Zh.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){Zh.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){Zh.sendEvent(e,t)}rtcStatsDisconnect(){Zh.server.close()}rtcStatsReconnect(){Zh.server.connected||Zh.server.connect()}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_onMessage(e){return Wh(this,void 0,void 0,function*(){const{method:t,data:r}=e;return Promise.resolve().then(()=>{switch(t){case"consumerReady":return this._onConsumerReady(r);case"consumerClosed":return this._onConsumerClosed(r);case"consumerPaused":return this._onConsumerPaused(r);case"consumerResumed":return this._onConsumerResumed(r);case"dataConsumerReady":return this._onDataConsumerReady(r);case"dataConsumerClosed":return this._onDataConsumerClosed(r);case"dominantSpeaker":return this._onDominantSpeaker(r);case"consumerScore":return this._onConsumerScore(r);case"producerScore":return this._onProducerScore(r);default:return void Lg.info(`unknown message method "${t}"`)}}).catch(e=>{Lg.error('"message" failed [error:%o]',e)})})}_onConsumerReady(e){return Wh(this,void 0,void 0,function*(){Lg.info("_onConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consume(e);if(t.pause(),t.appData.localPaused=!0,t.appData.spatialLayer=2,this._consumers.set(t.id,t),this._qualityMonitor.addConsumer(t.appData.sourceClientId,t.id),t.observer.once("close",()=>{this._consumers.delete(t.id),this._qualityMonitor.removeConsumer(t.appData.sourceClientId,t.id),this._consumerClosedCleanup(t)}),this._features.increaseIncomingMediaBufferOn&&t.rtpReceiver)try{t.rtpReceiver.jitterBufferTarget=Rf,t.rtpReceiver.playoutDelayHint=.4}catch(e){Lg.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:i,streamId:n}=t.appData,s=this._getOrCreateClientState(r);i?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=n):(s.hasEmittedWebcamStream=!1,s.camStreamId=n);let o=i?s.screenStream:s.webcamStream;o&&o.inboundId===n||(o=new MediaStream,o.inboundId=n,i?s.screenStream=o:s.webcamStream=o),"video"===t.kind&&this._streamIdToVideoConsumerId.set(o.id,t.id),o.addTrack(t.track),this._syncIncomingStreamsWithPWA(r);const a=this._streamIdToVideoResolution.get(o.id);a&&(this.updateStreamResolution(o.id,null,a),this._streamIdToVideoResolution.delete(o.id))})}_onConsumerClosed(e){return Wh(this,arguments,void 0,function*({consumerId:e,reason:t}){var r;Lg.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()})}_onConsumerPaused({consumerId:e}){Lg.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){Lg.info("_onConsumerResumed()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!1,t.appData.localPaused||t.resume())}_onConsumerScore({consumerId:e,kind:t,score:r}){Lg.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:i}}=this._consumers.get(e)||{appData:{}};i&&this._qualityMonitor.addConsumerScore(i,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){Lg.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach(i=>{(null==i?void 0:i.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)})}_onDataConsumerReady(e){return Wh(this,void 0,void 0,function*(){Lg.info("_onDataConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consumeData(e);this._dataConsumers.set(t.id,t),t.once("close",()=>{this._dataConsumers.delete(t.id)});const{clientId:r}=t.appData;t.on("message",e=>{var r;if(!this._micAnalyserDebugger)return;if("string"!=typeof e)return;const{score:i}=JSON.parse(e);i&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,i))}),this._syncIncomingStreamsWithPWA(r)})}_onDataConsumerClosed(e){return Wh(this,arguments,void 0,function*({dataConsumerId:e,reason:t}){Lg.info("_onDataConsumerClosed()",{dataConsumerId:e,reason:t});const r=this._dataConsumers.get(e);null==r||r.close()})}_onDominantSpeaker({consumerId:e}){const t=this._consumers.get(e);if(!t)return;const{sourceClientId:r}=t.appData;this._emitToPWA(Em,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,i=this._getOrCreateClientState(t),n=r?i.screenStream:i.webcamStream;n&&(n.removeTrack(e.track),0===n.getTracks().length&&(this._streamIdToVideoConsumerId.delete(n.id),this._streamIdToVideoResolution.delete(n.id),r?(i.screenStream=void 0,i.hasEmittedScreenStream=!1,i.screenShareStreamId=void 0):(i.hasEmittedWebcamStream=!1,i.camStreamId=void 0)))}_syncIncomingStreamsWithPWA(e){var t,r;const i=this._getOrCreateClientState(e),{webcamStream:n,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=i,p=[],h=[];this._consumers.forEach(t=>{if(t.appData.sourceClientId!==e)return;const r=t.appData.screenShare?d:c;!t.appData.localPaused!==r&&(r?(t.appData.remotePaused||t.resume(),t.appData.localPaused=!1,h.push(t.id)):(t.pause(),t.appData.localPaused=!0,p.push(t.id)))}),p.length>0&&(null===(t=this._vegaConnection)||void 0===t||t.message("pauseConsumers",{consumerIds:p})),h.length>0&&(null===(r=this._vegaConnection)||void 0===r||r.message("resumeConsumers",{consumerIds:h})),n&&!o&&c&&(this._emitToPWA(Qf,{clientId:e,stream:n,streamId:u,streamType:"webcam"}),i.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(Qf,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),i.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1},this._clientStates.set(e,t)),t}_emitToPWA(e,t){this._emitter.emit(e,t)}_emitToSignal(e,t,r){this._serverSocket.emit(e,t,r)}shouldAcceptStreamsFromBothSides(){return!0}setMicAnalyserDebugger(e){this._micAnalyserDebugger=e}setMicAnalyserParams(e){var t;null===(t=this._micAnalyser)||void 0===t||t.setParams(e)}hasClient(e){return this._clientStates.has(e)}}class Vg{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:i}){this.emitter=e,this.currentManager=null,t.on(zf,({room:n,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:n,emitter:e,serverSocket:t,webrtcProvider:r,features:i,eventClaim:a},d=!!n.sfuServer;if(Ug=d?"group":"normal",this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:n.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(Xf)}let l=null;l=d?new zg(c):new Sg(c),l.rtcStatsReconnect(),l.setupSocketListeners(),e.emit(Yf,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)})}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(Xf))}}let Ug="";const $g=()=>Ug,Gg=new Hh,qg={print:(...e)=>console.debug(e[0],...e.slice(1))};Gg.withDebugLogger(qg);const Hg=new class{constructor(){this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD=.04,this.END_PACKET_LOSS_PERIOD_THRESHOLD=.005,this.INTERVAL_DIFF_THRESHOLD_MS=4e3,this.STALE_MEASUREMENT_TIMEOUT_MS=1e4,this.MINIMUM_INTERVAL_MS=3e4,this.ssrcsHistory=new Map,this.staleMeasurementTimeouts=new Map}addPacketLossMeasurement(e,t,r){this.handleStaleMeasurements(e);const i=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let n=this.ssrcsHistory.get(e);if(!n)return n={id:e,hasActivePacketLoss:i,currPeriod:i?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,n);n.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(n,r),n.prevIntervalInMs&&n.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):i&&(n.hasActivePacketLoss=!0,n.currPeriod={begin:r})}hasPeriodicPacketLoss(e,t){const r=this.ssrcsHistory.get(e);return r&&this.prevIntervalExceeded(r,t)?(this.ssrcsHistory.delete(r.id),!1):(null==r?void 0:r.hasPeriodicPacketLoss)||!1}prevIntervalExceeded(e,t){if(e.prevPeriod&&e.prevIntervalInMs){return t>this.calculatePeriodCenterTimestamp(e.prevPeriod)+e.prevIntervalInMs+this.INTERVAL_DIFF_THRESHOLD_MS}return!1}handleStaleMeasurements(e){const t=this.staleMeasurementTimeouts.get(e);t&&clearTimeout(t),this.staleMeasurementTimeouts.set(e,setTimeout(()=>{Gg.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)},this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(Gg.debug("endPacketLossPeriod() [ssrcId: %s, timestamp: %s]",e.id,t),!e.currPeriod)throw new Error("No packet loss period for "+e.id);e.prevPeriod?(e.currPeriod.end=t,this.addNewPacketLossInterval(e)):e.prevPeriod=Object.assign(Object.assign({},e.currPeriod),{end:t}),delete e.currPeriod,e.hasActivePacketLoss=!1}addNewPacketLossInterval(e){if(Gg.debug("addNewPacketLossInterval() [ssrcId: %s, prevIntervalInMs: %s]",e.id,e.prevIntervalInMs),!e.currPeriod||!e.prevPeriod)throw new Error("missing period timestamps");const t=this.calculatePeriodCenterTimestamp(e.prevPeriod),r=this.calculatePeriodCenterTimestamp(e.currPeriod)-t;if(e.prevIntervalInMs){const t=Math.abs(e.prevIntervalInMs-r);e.hasPeriodicPacketLoss=t<this.INTERVAL_DIFF_THRESHOLD_MS,Gg.debug("addNewPacketLossInterval() [hasPeriodicPacketLoss: %s, intervalDiffInMs: %s]",t<this.INTERVAL_DIFF_THRESHOLD_MS,t)}e.prevIntervalInMs=r,e.prevPeriod=e.currPeriod}calculatePeriodCenterTimestamp(e){if(!e.end)throw new Error("Missing period end timestamp");return e.begin+(e.end-e.begin)/2}},Wg=[{id:"desync",enabled:({client:e,track:t,stats:r})=>!e.isLocalClient&&"audio"===(null==t?void 0:t.kind)&&"object"==typeof(null==r?void 0:r.tracks)&&Object.keys(r.tracks).length>1,check:({stats:e})=>{if(!e)return!1;const t={audio:0,video:0};Object.values(e.tracks).flatMap(e=>Object.values(e.ssrcs)).forEach(e=>{"audio"===e.kind&&e.jitter&&e.jitter>t.audio&&(t.audio=e.jitter),"video"===e.kind&&e.jitter&&e.jitter>t.video&&(t.video=e.jitter)});return Math.abs(1e3*t.audio-1e3*t.video)>500}},{id:"no-track",enabled:()=>!0,check:({client:e,clients:t,kind:r,track:i})=>{if(!i&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return!i}},{id:"ended-track",enabled:({track:e})=>!!e,check:({track:e})=>"ended"===(null==e?void 0:e.readyState)},{id:"no-track-stats",enabled:({hasLiveTrack:e})=>e,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(0===i.length&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return 0===i.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let i=!1;if(r.forEach(e=>{i=i||((null==e?void 0:e.bitrate)||0)>0}),!i&&e.isLocalClient){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}return!i}},{id:"denoiser-context-suspended",enabled:({client:e,kind:t})=>{var r,i;return e.isLocalClient&&"audio"===t&&!!(null===(i=null===(r=e.audio)||void 0===r?void 0:r.track)||void 0===i?void 0:i._denoiserCtx)},check:({track:e})=>{var t;return!(!e||!("_denoiserCtx"in e))&&"suspended"===(null===(t=e._denoiserCtx)||void 0===t?void 0:t.state)}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!i.isPresentation,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&(((null==e?void 0:e.height)||0)<200&&e.bitrate<3e4)},{id:"quality-limitation-bw",enabled:({hasLiveTrack:e,stats:t,client:r,clients:i,kind:n})=>{if("normal"===$g()){if(i.filter(e=>!e.isLocalClient).some(e=>e.isAudioOnlyModeEnabled))return!1}return e&&r.isLocalClient&&"video"===n&&!!t},check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"bandwidth"===e.qualityLimitationReason))},{id:"quality-limitation-cpu",enabled:({hasLiveTrack:e,stats:t,client:r,kind:i})=>e&&r.isLocalClient&&"video"===i&&!!t,check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"cpu"===e.qualityLimitationReason))},{id:"high-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>2},{id:"extreme-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>5},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.1},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.1},{id:"fps-below-20",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.height)||0)>180&&((null==e?void 0:e.fps)||0)<20},{id:"fps-below-10",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.fps)||0)<10},{id:"bad-network",enabled:({hasLiveTrack:e,ssrcs:t})=>e&&t.length>0,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(!i.some(e=>((null==e?void 0:e.bitrate)||0)>0)&&e.isLocalClient&&"video"===r){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}const n=i[0];return!!n&&(0===n.bitrate||(n.lossRatio||0)>.03||(n.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==n?void 0:n.bitrate)&&n.bitrate<3e4||"in"===n.direction&&!!n.pliRate&&n.pliRate>2)}},{id:"periodic-packet-loss",enabled:({client:e,hasLiveTrack:t,ssrc0:r})=>e.isLocalClient&&t&&!!(null==r?void 0:r.ssrc)&&"out"===(null==r?void 0:r.direction)&&((null==r?void 0:r.bitrate)||0)>0,check:({ssrc0:e})=>!(!e||!e.ssrc)&&(Hg.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),Hg.hasPeriodicPacketLoss(e.ssrc,Date.now()))},{id:"cpu-pressure-serious",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"serious"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"cpu-pressure-critical",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"critical"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"concealed",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===(null==e?void 0:e.direction)&&((null==e?void 0:e.audioLevel)||0)>=.001&&((null==e?void 0:e.audioConcealment)||0)>=.1},{id:"decelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&((null==e?void 0:e.audioDeceleration)||0)>=.1},{id:"accelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&(e.audioAcceleration||0)>=.1}];let Kg=[],Jg=null;const Qg=[{id:"bitrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&!!t&&!!r,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+((null==t?void 0:t.bitrate)||0),0)},{id:"pixelrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.fps||0)*(t.width||0)*(t.height||0),0)},{id:"height",enabled:({hasLiveTrack:e,track:t,trackStats:r,ssrc0:i,kind:n})=>e&&"video"===n&&!!r&&!!t&&!!i&&!!i.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>Math.max(e,t.fps>0?t.height:0),0)},{id:"sourceHeight",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.sourceHeight&&"out"===r.direction,value:({ssrc0:e})=>null==e?void 0:e.sourceHeight},{id:"packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate,value:({ssrc0:e})=>("in"===(null==e?void 0:e.direction)?e.lossRatio:null==e?void 0:e.fractionLost)||0},{id:"jitter",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"in"===t.direction,value:({ssrc0:e})=>null==e?void 0:e.jitter},{id:"mos",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"out"===t.direction,value:({ssrc0:e})=>{const t=((null==e?void 0:e.roundTripTime)||0)+2*((null==e?void 0:e.jitter)||0)+10;let r=t<160?93.2-t/40:93.2-(t-120)/10;r-=2.5*(100*((null==e?void 0:e.fractionLost)||0));return 1+.035*r+7e-6*r*(r-60)*(100-r)}},{id:"rendered",value:()=>1},{id:"active",value:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&t&&r?1:0},{id:"cpu-pressure",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},value:({stats:e})=>{var t;return{nominal:.25,fair:.5,serious:.75,critical:1}[(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)||""]||0}},{id:"turn-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>e.usingTurn)},{id:"turn-tls-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>"tls"===e.turnProtocol)},{id:"concealment",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioConcealment},{id:"deceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioDeceleration},{id:"acceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioAcceleration},{id:"qpf",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.qpf||0),0)}];let Yg,Xg,Zg;const ev=()=>{Yg={},Xg={},Zg={aggregated:{issues:Xg,metrics:Yg}}};function tv(e,t){Object.values(Yg).forEach(e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0}),Object.values(Xg).forEach(e=>{e.curTicks=0,e.curRegistered=0,e.active=!1}),t.find(e=>!e.isLocalClient)&&(t.forEach(r=>{const i=e[r.id];["video","audio","global"].forEach(e=>{var n,s;if(("global"!==e||r.isPresentation)&&!(null===(n=r[e])||void 0===n?void 0:n.enabled))return;if("global"===e&&!r.isLocalClient)return;let o=Zg[r.id];o||(o={issues:{},metrics:{}},Zg[r.id]=o);const a=null===(s=r[e])||void 0===s?void 0:s.track,c=!!a&&"ended"!==a.readyState,d=a&&i&&i.tracks[a.id],l=d?Object.values(d.ssrcs).sort((e,t)=>(e.height||Number.MAX_SAFE_INTEGER)-(t.height||Number.MAX_SAFE_INTEGER)):[],u=l[0],p={client:r,clients:t,kind:e,track:a,trackStats:d,stats:i,hasLiveTrack:c,ssrc0:u,ssrcs:l,issues:o.issues,metrics:o.metrics},h="global"===e?"global":`${r.isLocalClient?"loc":"rem"}-${r.isPresentation?"pres":"cam"}-${e}`;Qg.forEach(t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;if(!t.enabled||t.enabled(p)){const e=`${h}-${t.id}`;let r=o.metrics[e];const i=t.value(p);r||(r={ticks:0,sum:0,avg:0,min:i,max:i},o.metrics[e]=r),r.ticks++,r.sum+=i,r.min=Math.min(r.min,i),r.max=Math.max(r.max,i),r.avg=r.sum/r.ticks;let n=Yg[e];n||(n={ticks:0,sum:0,min:i,max:i,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},Yg[e]=n),n.ticks++,n.sum+=i,n.min=Math.min(n.min,i),n.max=Math.max(n.max,i),n.avg=n.sum/n.ticks,0===n.curTicks?(n.curMax=i,n.curMin=i,n.curSum=i):(n.curMax=Math.max(n.curMax,i),n.curMin=Math.min(n.curMin,i),n.curSum+=i),n.curTicks++}}),Wg.forEach(t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;const r=`${h}-${t.id}`,i=t.enabled(p);let n=o.issues[r],s=Xg[r];if(i){n||(n={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},o.issues[r]=n),n.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},Xg[r]=s),s.ticks++,s.curTicks++;t.check(p)?(n.registered++,n.current++,n.active||(n.active=!0,n.periods++),n.ticks===n.initial+1&&(n.initial++,s.initial++),n.current>n.longest&&(n.longest=n.current),s.active=!0,s.registered++,s.curRegistered++):(n.active=!1,n.current=0)}else n&&(n.active=!1,n.current=0)})})}),Object.values(Yg).forEach(e=>{e.curTicks&&(e.curAvg=e.curSum/e.curTicks,0===e.totTicks&&(e.totMin=e.curSum,e.totMax=e.curSum),e.totTicks++,e.totSum+=e.curSum,e.totMin=Math.min(e.totMin,e.curSum),e.totMax=Math.max(e.totMax,e.curSum),e.totAvg=e.totSum/e.totTicks)}),Object.values(Xg).forEach(e=>{e.curTicks}),Kg.forEach(r=>{var i;return null===(i=r.onUpdatedIssues)||void 0===i?void 0:i.call(r,Zg,e,t)}))}function rv(e){return Kg.push(e),Jg||(Jg=function(e,t=pf,r=uf){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=ff(r,t)),{stop(){var t;r.subscriptions=r.subscriptions.filter(t=>t!==e),r.subscriptions.length||(null===(t=r.currentMonitor)||void 0===t||t.stop(),r.currentMonitor=null)}}}({onUpdatedStats:tv}).stop),{stop(){Kg=Kg.filter(t=>t!==e),Kg.length||(null==Jg||Jg(),Jg=null,ev())}}}var iv;ev();const nv="safari"===(null!==(iv=oi.default)&&void 0!==iv?iv:oi).browserDetails.browser;function sv({disableAEC:e,disableAGC:t,hd:r,lax:i,lowDataMode:n,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=i||nv?720:{min:360,ideal:720}),a&&(!1===r?(u=360,p=270):p=360);const h={audio:Object.assign({},s.audioId&&{deviceId:s.audioId}),video:Object.assign(Object.assign({},s.videoId?{deviceId:s.videoId}:{facingMode:"user"}),{height:n?p:u,frameRate:n&&!a?15:24})};if(i)return(null===(d=h.audio)||void 0===d?void 0:d.deviceId)||(h.audio=!0),null===(l=h.video)||void 0===l||delete l.facingMode,h;if(o){const[e,t,r]=o.split(/[^\d]/g).map(e=>parseInt(e,10));e&&(h.video.width={exact:e}),t&&(h.video.height={exact:t}),r&&(h.video.frameRate={exact:r}),delete h.video.facingMode}else h.video.aspectRatio=c?16/9:4/3;return t&&(h.audio.autoGainControl=!1),e&&(h.audio.echoCancellation=!1),h}function ov({devices:e,videoId:t,audioId:r,options:i,type:n="ideal"}){const s=e.filter(e=>"audioinput"===e.kind),o=e.filter(e=>"videoinput"===e.kind),a=!r||!s.some(e=>e.deviceId===r),c=!t||!o.some(e=>e.deviceId===t),d=sv(Object.assign({preferredDeviceIds:{audioId:a?null:{[n]:r},videoId:c?null:{[n]:t}}},i));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const av=new Hh,cv=/mobi/i.test(navigator.userAgent);class dv extends Error{constructor(...e){super(...e),this.name="nodevices"}}function lv(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch(t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw av.error(`getUserMedia ${r}`),t}):Promise.reject(new dv("No provided devices"))}function uv(e,t,r,i){var n,s,o;let a={deviceId:null};return t?(a.label=t.label,t.getSettings&&(a=Object.assign(Object.assign({},a),t.getSettings())),a.deviceId?a:(t.getCapabilities&&(a.deviceId=t.getCapabilities().deviceId),a.deviceId?a:(t.label&&r&&(a.deviceId=null===(s=r.find(r=>t.label===r.label&&r.kind===e))||void 0===s?void 0:s.deviceId),a.deviceId||(a.deviceId=null===(o=t.getConstraints())||void 0===o?void 0:o.deviceId,a.broken=1),a))):(i&&r&&(a.deviceId=null===(n=r.find(t=>t.deviceId===i&&t.kind===e))||void 0===n?void 0:n.deviceId),a)}function pv(e,t){t&&"audio"!==t||e.getAudioTracks().forEach(e=>e.stop()),t&&"video"!==t||e.getVideoTracks().forEach(e=>e.stop())}function hv(e){return Wh(this,arguments,void 0,function*(e,{replaceStream:t,fallback:r=!0}={}){var i;let n,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=cv||"video"!==c,l=ov(e),u=(e,t)=>(e.details=Object.assign({constraints:l,constraint:e.constraint||(null==t?void 0:t.constraint),newConstraints:s,fallback:r,stopTracks:d},e!==n&&{error:String(n)}),e),p=t=>Wh(this,void 0,void 0,function*(){if(l.audio&&l.video){try{a=yield lv(ov(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){"NotFoundError"!==e.name&&u(e,t)}try{a||(a=yield lv(ov(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){u(e,t)}}});d&&t&&pv(t,c);try{a=yield lv(l)}catch(s){if(n=s,!r)throw u(s);if("OverconstrainedError"===s.name){o={deviceId:{videoId:null,audioId:null},width:{lax:!0},height:{lax:!0},"":{audioId:null,videoId:null,lax:!0}}[s.constraint||""]}else if("NotFoundError"===s.name)yield p(s);else if("NotAllowedError"===s.name||"NotReadableError"===s.name||"AbortError"===s.name)if(t&&!d&&(pv(t,c),o=e),"NotAllowedError"===s.name)yield p(s);else if("NotAllowedError"!==s.name){try{a=yield lv(ov(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){av.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(i=/(video|audio)/.exec(t))||void 0===i?void 0:i[0])||c||""];if(!a&&r)try{a=yield lv(ov(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){av.warn(`Re-tried ${r} with no constraints, but failed: ${""+e}`)}if(!a){const t=r?[r]:["videoId","audioId"];for(const r of t){try{a=yield lv(ov(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){av.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=ov(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield lv(s)}catch(e){throw u(e,n)}}if(!a)throw u(n);let h;return t&&(d||pv(t,c),h=function(e,t,r){const i=[];return r&&"audio"!==r||(i.push(...e.getAudioTracks()),t.getAudioTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),r&&"video"!==r||(i.push(...e.getVideoTracks()),t.getVideoTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),i.forEach(t=>{t.replaced=!0,e.removeTrack(t)}),i}(t,a,c),a=t),{error:n&&u(n),stream:a,replacedTracks:h}})}function fv({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:i,currentSpeakerId:n}){const s=function(e,t){const[r,i]=[e,t].map(e=>e.filter(e=>e.kind&&e.deviceId).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.kind]:Object.assign(Object.assign({},e[t.kind]),{[t.deviceId]:t})}),{})),n={};return e.forEach(e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),i[e.kind]&&i[e.kind][e.deviceId]||(n[e.kind].removed[e.deviceId]=e))}),t.forEach(e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),r[e.kind]&&r[e.kind][e.deviceId]?r[e.kind][e.deviceId].label&&r[e.kind][e.deviceId].label!==e.label&&(n[e.kind].changed[e.deviceId]=e):n[e.kind].added[e.deviceId]=e)}),n}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",i],["audiooutput",n]].forEach(([e,r])=>{const i=s[e];if(i){if(r){if(i.removed[r]&&(a[e]={deviceId:null},"audiooutput"===e)){const r=t.find(e=>"audiooutput"===e.kind);a[e]={deviceId:null==r?void 0:r.deviceId}}i.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(i.added).length>0){const[t]=Object.keys(i.added).slice(0,1),r=i.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(i.removed).length>0){const[t]=Object.keys(i.removed).slice(0,1);o[e]=i.removed[t]}}}),{addedDevices:c,changedDevices:a,removedDevices:o}}var mv;!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(mv||(mv={}));var gv={exports:{}};gv.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var vv=c(gv.exports);function bv(e,t){return function(){return e.apply(t,arguments)}}const{toString:yv}=Object.prototype,{getPrototypeOf:wv}=Object,{iterator:_v,toStringTag:Sv}=Symbol,Cv=(e=>t=>{const r=yv.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Rv=e=>(e=e.toLowerCase(),t=>Cv(t)===e),kv=e=>t=>typeof t===e,{isArray:Tv}=Array,Pv=kv("undefined");const Ov=Rv("ArrayBuffer");const Ev=kv("string"),Dv=kv("function"),xv=kv("number"),Iv=e=>null!==e&&"object"==typeof e,Mv=e=>{if("object"!==Cv(e))return!1;const t=wv(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Sv in e||_v in e)},jv=Rv("Date"),Lv=Rv("File"),Av=Rv("Blob"),Nv=Rv("FileList"),Bv=Rv("URLSearchParams"),[Fv,zv,Vv,Uv]=["ReadableStream","Request","Response","Headers"].map(Rv);function $v(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,n;if("object"!=typeof e&&(e=[e]),Tv(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{const n=r?Object.getOwnPropertyNames(e):Object.keys(e),s=n.length;let o;for(i=0;i<s;i++)o=n[i],t.call(null,e[o],o,e)}}function Gv(e,t){t=t.toLowerCase();const r=Object.keys(e);let i,n=r.length;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}const qv="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Hv=e=>!Pv(e)&&e!==qv;const Wv=(Kv="undefined"!=typeof Uint8Array&&wv(Uint8Array),e=>Kv&&e instanceof Kv);var Kv;const Jv=Rv("HTMLFormElement"),Qv=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Yv=Rv("RegExp"),Xv=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};$v(r,(r,n)=>{let s;!1!==(s=t(r,n,e))&&(i[n]=s||r)}),Object.defineProperties(e,i)};const Zv=Rv("AsyncFunction"),eb=(tb="function"==typeof setImmediate,rb=Dv(qv.postMessage),tb?setImmediate:rb?(ib=`axios@${Math.random()}`,nb=[],qv.addEventListener("message",({source:e,data:t})=>{e===qv&&t===ib&&nb.length&&nb.shift()()},!1),e=>{nb.push(e),qv.postMessage(ib,"*")}):e=>setTimeout(e));var tb,rb,ib,nb;const sb="undefined"!=typeof queueMicrotask?queueMicrotask.bind(qv):"undefined"!=typeof process&&process.nextTick||eb;var ob={isArray:Tv,isArrayBuffer:Ov,isBuffer:function(e){return null!==e&&!Pv(e)&&null!==e.constructor&&!Pv(e.constructor)&&Dv(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Dv(e.append)&&("formdata"===(t=Cv(e))||"object"===t&&Dv(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ov(e.buffer),t},isString:Ev,isNumber:xv,isBoolean:e=>!0===e||!1===e,isObject:Iv,isPlainObject:Mv,isReadableStream:Fv,isRequest:zv,isResponse:Vv,isHeaders:Uv,isUndefined:Pv,isDate:jv,isFile:Lv,isBlob:Av,isRegExp:Yv,isFunction:Dv,isStream:e=>Iv(e)&&Dv(e.pipe),isURLSearchParams:Bv,isTypedArray:Wv,isFileList:Nv,forEach:$v,merge:function e(){const{caseless:t}=Hv(this)&&this||{},r={},i=(i,n)=>{const s=t&&Gv(r,n)||n;Mv(r[s])&&Mv(i)?r[s]=e(r[s],i):Mv(i)?r[s]=e({},i):Tv(i)?r[s]=i.slice():r[s]=i};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&$v(arguments[e],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>($v(t,(t,i)=>{r&&Dv(t)?e[i]=bv(t,r):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let n,s,o;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),s=n.length;s-- >0;)o=n[s],i&&!i(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&wv(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Cv,kindOfTest:Rv,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(Tv(e))return e;let t=e.length;if(!xv(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[_v]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:Jv,hasOwnProperty:Qv,hasOwnProp:Qv,reduceDescriptors:Xv,freezeMethods:e=>{Xv(e,(t,r)=>{if(Dv(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Dv(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach(e=>{r[e]=!0})};return Tv(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Gv,global:qv,isContextDefined:Hv,isSpecCompliantForm:function(e){return!!(e&&Dv(e.append)&&"FormData"===e[Sv]&&e[_v])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Iv(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[i]=e;const n=Tv(e)?[]:{};return $v(e,(e,t)=>{const s=r(e,i+1);!Pv(s)&&(n[t]=s)}),t[i]=void 0,n}}return e};return r(e,0)},isAsyncFn:Zv,isThenable:e=>e&&(Iv(e)||Dv(e))&&Dv(e.then)&&Dv(e.catch),setImmediate:eb,asap:sb,isIterable:e=>null!=e&&Dv(e[_v])};function ab(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}ob.inherits(ab,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ob.toJSONObject(this.config),code:this.code,status:this.status}}});const cb=ab.prototype,db={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{db[e]={value:e}}),Object.defineProperties(ab,db),Object.defineProperty(cb,"isAxiosError",{value:!0}),ab.from=(e,t,r,i,n,s)=>{const o=Object.create(cb);return ob.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),ab.call(o,e.message,t,r,i,n),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function lb(e){return ob.isPlainObject(e)||ob.isArray(e)}function ub(e){return ob.endsWith(e,"[]")?e.slice(0,-2):e}function pb(e,t,r){return e?e.concat(t).map(function(e,t){return e=ub(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const hb=ob.toFlatObject(ob,{},null,function(e){return/^is[A-Z]/.test(e)});function fb(e,t,r){if(!ob.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=ob.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!ob.isUndefined(t[e])})).metaTokens,n=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ob.isSpecCompliantForm(t);if(!ob.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ob.isDate(e))return e.toISOString();if(ob.isBoolean(e))return e.toString();if(!a&&ob.isBlob(e))throw new ab("Blob is not supported. Use a Buffer instead.");return ob.isArrayBuffer(e)||ob.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(ob.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(ob.isArray(e)&&function(e){return ob.isArray(e)&&!e.some(lb)}(e)||(ob.isFileList(e)||ob.endsWith(r,"[]"))&&(a=ob.toArray(e)))return r=ub(r),a.forEach(function(e,i){!ob.isUndefined(e)&&null!==e&&t.append(!0===o?pb([r],i,s):null===o?r:r+"[]",c(e))}),!1;return!!lb(e)||(t.append(pb(n,r,s),c(e)),!1)}const l=[],u=Object.assign(hb,{defaultVisitor:d,convertValue:c,isVisitable:lb});if(!ob.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!ob.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+i.join("."));l.push(r),ob.forEach(r,function(r,s){!0===(!(ob.isUndefined(r)||null===r)&&n.call(t,r,ob.isString(s)?s.trim():s,i,u))&&e(r,i?i.concat(s):[s])}),l.pop()}}(e),t}function mb(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function gb(e,t){this._pairs=[],e&&fb(e,this,t)}const vb=gb.prototype;function bb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function yb(e,t,r){if(!t)return e;const i=r&&r.encode||bb;ob.isFunction(r)&&(r={serialize:r});const n=r&&r.serialize;let s;if(s=n?n(t,r):ob.isURLSearchParams(t)?t.toString():new gb(t,r).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}vb.append=function(e,t){this._pairs.push([e,t])},vb.toString=function(e){const t=e?function(t){return e.call(this,t,mb)}:mb;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class wb{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ob.forEach(this.handlers,function(t){null!==t&&e(t)})}}var _b={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Sb={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:gb,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const Cb="undefined"!=typeof window&&"undefined"!=typeof document,Rb="object"==typeof navigator&&navigator||void 0,kb=Cb&&(!Rb||["ReactNative","NativeScript","NS"].indexOf(Rb.product)<0),Tb="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Pb=Cb&&window.location.href||"http://localhost";var Ob={...Object.freeze({__proto__:null,hasBrowserEnv:Cb,hasStandardBrowserEnv:kb,hasStandardBrowserWebWorkerEnv:Tb,navigator:Rb,origin:Pb}),...Sb};function Eb(e){function t(e,r,i,n){let s=e[n++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=n>=e.length;if(s=!s&&ob.isArray(i)?i.length:s,a)return ob.hasOwnProp(i,s)?i[s]=[i[s],r]:i[s]=r,!o;i[s]&&ob.isObject(i[s])||(i[s]=[]);return t(e,r,i[s],n)&&ob.isArray(i[s])&&(i[s]=function(e){const t={},r=Object.keys(e);let i;const n=r.length;let s;for(i=0;i<n;i++)s=r[i],t[s]=e[s];return t}(i[s])),!o}if(ob.isFormData(e)&&ob.isFunction(e.entries)){const r={};return ob.forEachEntry(e,(e,i)=>{t(function(e){return ob.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Db={transitional:_b,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,n=ob.isObject(e);n&&ob.isHTMLForm(e)&&(e=new FormData(e));if(ob.isFormData(e))return i?JSON.stringify(Eb(e)):e;if(ob.isArrayBuffer(e)||ob.isBuffer(e)||ob.isStream(e)||ob.isFile(e)||ob.isBlob(e)||ob.isReadableStream(e))return e;if(ob.isArrayBufferView(e))return e.buffer;if(ob.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return fb(e,new Ob.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,i){return Ob.isNode&&ob.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=ob.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return fb(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||i?(t.setContentType("application/json",!1),function(e,t,r){if(ob.isString(e))try{return(t||JSON.parse)(e),ob.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Db.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(ob.isResponse(e)||ob.isReadableStream(e))return e;if(e&&ob.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw ab.from(e,ab.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ob.classes.FormData,Blob:Ob.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ob.forEach(["delete","get","head","post","put","patch"],e=>{Db.headers[e]={}});const xb=ob.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Ib=Symbol("internals");function Mb(e){return e&&String(e).trim().toLowerCase()}function jb(e){return!1===e||null==e?e:ob.isArray(e)?e.map(jb):String(e)}function Lb(e,t,r,i,n){return ob.isFunction(i)?i.call(this,t,r):(n&&(t=r),ob.isString(t)?ob.isString(i)?-1!==t.indexOf(i):ob.isRegExp(i)?i.test(t):void 0:void 0)}let Ab=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function n(e,t,r){const n=Mb(t);if(!n)throw new Error("header name must be a non-empty string");const s=ob.findKey(i,n);(!s||void 0===i[s]||!0===r||void 0===r&&!1!==i[s])&&(i[s||t]=jb(e))}const s=(e,t)=>ob.forEach(e,(e,r)=>n(e,r,t));if(ob.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(ob.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,i,n;return e&&e.split("\n").forEach(function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),i=e.substring(n+1).trim(),!r||t[r]&&xb[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t})(e),t);else if(ob.isObject(e)&&ob.isIterable(e)){let r,i,n={};for(const t of e){if(!ob.isArray(t))throw TypeError("Object iterator must return a key-value pair");n[i=t[0]]=(r=n[i])?ob.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(n,t)}else null!=e&&n(t,e,r);return this}get(e,t){if(e=Mb(e)){const r=ob.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(ob.isFunction(t))return t.call(this,e,r);if(ob.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Mb(e)){const r=ob.findKey(this,e);return!(!r||void 0===this[r]||t&&!Lb(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function n(e){if(e=Mb(e)){const n=ob.findKey(r,e);!n||t&&!Lb(0,r[n],n,t)||(delete r[n],i=!0)}}return ob.isArray(e)?e.forEach(n):n(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const n=t[r];e&&!Lb(0,this[n],n,e,!0)||(delete this[n],i=!0)}return i}normalize(e){const t=this,r={};return ob.forEach(this,(i,n)=>{const s=ob.findKey(r,n);if(s)return t[s]=jb(i),void delete t[n];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(n):String(n).trim();o!==n&&delete t[n],t[o]=jb(i),r[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ob.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&ob.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[Ib]=this[Ib]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Mb(e);t[i]||(!function(e,t){const r=ob.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,n){return this[i].call(this,t,e,r,n)},configurable:!0})})}(r,e),t[i]=!0)}return ob.isArray(e)?e.forEach(i):i(e),this}};function Nb(e,t){const r=this||Db,i=t||r,n=Ab.from(i.headers);let s=i.data;return ob.forEach(e,function(e){s=e.call(r,s,n.normalize(),t?t.status:void 0)}),n.normalize(),s}function Bb(e){return!(!e||!e.__CANCEL__)}function Fb(e,t,r){ab.call(this,null==e?"canceled":e,ab.ERR_CANCELED,t,r),this.name="CanceledError"}function zb(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new ab("Request failed with status code "+r.status,[ab.ERR_BAD_REQUEST,ab.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Ab.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ob.reduceDescriptors(Ab.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),ob.freezeMethods(Ab),ob.inherits(Fb,ab,{__CANCEL__:!0});const Vb=(e,t,r=3)=>{let i=0;const n=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let n,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];n||(n=c),r[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=r[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-n<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,i,n=0,s=1e3/t;const o=(t,s=Date.now())=>{n=s,r=null,i&&(clearTimeout(i),i=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-n;a>=s?o(e,t):(r=e,i||(i=setTimeout(()=>{i=null,o(r)},s-a)))},()=>r&&o(r)]}(r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-i,c=n(a);i=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})},r)},Ub=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},$b=e=>(...t)=>ob.asap(()=>e(...t));var Gb=Ob.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Ob.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Ob.origin),Ob.navigator&&/(msie|trident)/i.test(Ob.navigator.userAgent)):()=>!0,qb=Ob.hasStandardBrowserEnv?{write(e,t,r,i,n,s){const o=[e+"="+encodeURIComponent(t)];ob.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ob.isString(i)&&o.push("path="+i),ob.isString(n)&&o.push("domain="+n),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Hb(e,t,r){let i=!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(i||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Wb=e=>e instanceof Ab?{...e}:e;function Kb(e,t){t=t||{};const r={};function i(e,t,r,i){return ob.isPlainObject(e)&&ob.isPlainObject(t)?ob.merge.call({caseless:i},e,t):ob.isPlainObject(t)?ob.merge({},t):ob.isArray(t)?t.slice():t}function n(e,t,r,n){return ob.isUndefined(t)?ob.isUndefined(e)?void 0:i(void 0,e,0,n):i(e,t,0,n)}function s(e,t){if(!ob.isUndefined(t))return i(void 0,t)}function o(e,t){return ob.isUndefined(t)?ob.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,n,s){return s in t?i(r,n):s in e?i(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>n(Wb(e),Wb(t),0,!0)};return ob.forEach(Object.keys(Object.assign({},e,t)),function(i){const s=c[i]||n,o=s(e[i],t[i],i);ob.isUndefined(o)&&s!==a||(r[i]=o)}),r}var Jb=e=>{const t=Kb({},e);let r,{data:i,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Ab.from(a),t.url=yb(Hb(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ob.isFormData(i))if(Ob.hasStandardBrowserEnv||Ob.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Ob.hasStandardBrowserEnv&&(n&&ob.isFunction(n)&&(n=n(t)),n||!1!==n&&Gb(t.url))){const e=s&&o&&qb.read(o);e&&a.set(s,e)}return t};var Qb="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=Jb(e);let n=i.data;const s=Ab.from(i.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function f(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const i=Ab.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());zb(function(e){t(e),f()},function(e){r(e),f()},{data:u&&"text"!==u&&"json"!==u?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new ab("Request aborted",ab.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ab("Network Error",ab.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const n=i.transitional||_b;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new ab(t,n.clarifyTimeoutError?ab.ETIMEDOUT:ab.ECONNABORTED,e,m)),m=null},void 0===n&&s.setContentType(null),"setRequestHeader"in m&&ob.forEach(s.toJSON(),function(e,t){m.setRequestHeader(t,e)}),ob.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),u&&"json"!==u&&(m.responseType=i.responseType),h&&([c,l]=Vb(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=Vb(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(o=t=>{m&&(r(!t||t.type?new Fb(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(o),i.signal&&(i.signal.aborted?o():i.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);v&&-1===Ob.protocols.indexOf(v)?r(new ab("Unsupported protocol "+v+":",ab.ERR_BAD_REQUEST,e)):m.send(n||null)})};const Yb=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const n=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;i.abort(t instanceof ab?t:new Fb(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,n(new ab(`timeout ${t} of ms exceeded`,ab.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(n):e.removeEventListener("abort",n)}),e=null)};e.forEach(e=>e.addEventListener("abort",n));const{signal:a}=i;return a.unsubscribe=()=>ob.asap(o),a}},Xb=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,n=0;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},Zb=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},ey=(e,t,r,i)=>{const n=async function*(e,t){for await(const r of Zb(e))yield*Xb(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await n.next();if(t)return a(),void e.close();let s=i.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(i))}catch(e){throw a(e),e}},cancel:e=>(a(e),n.return())},{highWaterMark:2})},ty="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,ry=ty&&"function"==typeof ReadableStream,iy=ty&&("function"==typeof TextEncoder?(ny=new TextEncoder,e=>ny.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var ny;const sy=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},oy=ry&&sy(()=>{let e=!1;const t=new Request(Ob.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),ay=ry&&sy(()=>ob.isReadableStream(new Response("").body)),cy={stream:ay&&(e=>e.body)};var dy;ty&&(dy=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!cy[e]&&(cy[e]=ob.isFunction(dy[e])?t=>t[e]():(t,r)=>{throw new ab(`Response type '${e}' is not supported`,ab.ERR_NOT_SUPPORT,r)})}));const ly=async(e,t)=>{const r=ob.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(ob.isBlob(e))return e.size;if(ob.isSpecCompliantForm(e)){const t=new Request(Ob.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ob.isArrayBufferView(e)||ob.isArrayBuffer(e)?e.byteLength:(ob.isURLSearchParams(e)&&(e+=""),ob.isString(e)?(await iy(e)).byteLength:void 0)})(t):r};var uy=ty&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=Jb(e);d=d?(d+"").toLowerCase():"text";let h,f=Yb([n,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&oy&&"get"!==r&&"head"!==r&&0!==(g=await ly(l,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(ob.isFormData(i)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=Ub(g,Vb($b(c)));i=ey(r.body,65536,e,t)}}ob.isString(u)||(u=u?"include":"omit");const n="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:n?u:void 0});let s=await fetch(h,p);const o=ay&&("stream"===d||"response"===d);if(ay&&(a||o&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=ob.toFiniteNumber(s.headers.get("content-length")),[r,i]=a&&Ub(t,Vb($b(a),!0))||[];s=new Response(ey(s.body,65536,r,()=>{i&&i(),m&&m()}),e)}d=d||"text";let v=await cy[ob.findKey(cy,d)||"text"](s,e);return!o&&m&&m(),await new Promise((t,r)=>{zb(t,r,{data:v,headers:Ab.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new ab("Network Error",ab.ERR_NETWORK,e,h),{cause:t.cause||t});throw ab.from(t,t&&t.code,e,h)}});const py={http:null,xhr:Qb,fetch:uy};ob.forEach(py,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const hy=e=>`- ${e}`,fy=e=>ob.isFunction(e)||null===e||!1===e;var my=e=>{e=ob.isArray(e)?e:[e];const{length:t}=e;let r,i;const n={};for(let s=0;s<t;s++){let t;if(r=e[s],i=r,!fy(r)&&(i=py[(t=String(r)).toLowerCase()],void 0===i))throw new ab(`Unknown adapter '${t}'`);if(i)break;n[t||"#"+s]=i}if(!i){const e=Object.entries(n).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new ab("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(hy).join("\n"):" "+hy(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function gy(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Fb(null,e)}function vy(e){gy(e),e.headers=Ab.from(e.headers),e.data=Nb.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return my(e.adapter||Db.adapter)(e).then(function(t){return gy(e),t.data=Nb.call(e,e.transformResponse,t),t.headers=Ab.from(t.headers),t},function(t){return Bb(t)||(gy(e),t&&t.response&&(t.response.data=Nb.call(e,e.transformResponse,t.response),t.response.headers=Ab.from(t.response.headers))),Promise.reject(t)})}const by="1.10.0",yy={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{yy[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const wy={};yy.transitional=function(e,t,r){function i(e,t){return"[Axios v"+by+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,s)=>{if(!1===e)throw new ab(i(n," has been removed"+(t?" in "+t:"")),ab.ERR_DEPRECATED);return t&&!wy[n]&&(wy[n]=!0,console.warn(i(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,s)}},yy.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var _y={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ab("options must be an object",ab.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let n=i.length;for(;n-- >0;){const s=i[n],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new ab("option "+s+" must be "+r,ab.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new ab("Unknown option "+s,ab.ERR_BAD_OPTION)}},validators:yy};const Sy=_y.validators;let Cy=class{constructor(e){this.defaults=e||{},this.interceptors={request:new wb,response:new wb}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Kb(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:n}=t;void 0!==r&&_y.assertOptions(r,{silentJSONParsing:Sy.transitional(Sy.boolean),forcedJSONParsing:Sy.transitional(Sy.boolean),clarifyTimeoutError:Sy.transitional(Sy.boolean)},!1),null!=i&&(ob.isFunction(i)?t.paramsSerializer={serialize:i}:_y.assertOptions(i,{encode:Sy.function,serialize:Sy.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),_y.assertOptions(t,{baseUrl:Sy.spelling("baseURL"),withXsrfToken:Sy.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=n&&ob.merge(n.common,n[t.method]);n&&ob.forEach(["delete","get","head","post","put","patch","common"],e=>{delete n[e]}),t.headers=Ab.concat(s,n);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0;if(!a){const e=[vy.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=vy.call(this,p)}catch(e){return Promise.reject(e)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return yb(Hb((e=Kb(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};ob.forEach(["delete","get","head","options"],function(e){Cy.prototype[e]=function(t,r){return this.request(Kb(r||{},{method:e,url:t,data:(r||{}).data}))}}),ob.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,n){return this.request(Kb(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Cy.prototype[e]=t(),Cy.prototype[e+"Form"]=t(!0)});const Ry={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ry).forEach(([e,t])=>{Ry[t]=e});const ky=function e(t){const r=new Cy(t),i=bv(Cy.prototype.request,r);return ob.extend(i,Cy.prototype,r,{allOwnKeys:!0}),ob.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(Kb(t,r))},i}(Db);ky.Axios=Cy,ky.CanceledError=Fb,ky.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{r.subscribe(e),t=e}).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e(function(e,i,n){r.reason||(r.reason=new Fb(e,i,n),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},ky.isCancel=Bb,ky.VERSION=by,ky.toFormData=fb,ky.AxiosError=ab,ky.Cancel=ky.CanceledError,ky.all=function(e){return Promise.all(e)},ky.spread=function(e){return function(t){return e.apply(null,t)}},ky.isAxiosError=function(e){return ob.isObject(e)&&!0===e.isAxiosError},ky.mergeConfig=Kb,ky.AxiosHeaders=Ab,ky.formToJSON=e=>Eb(ob.isHTMLForm(e)?new FormData(e):e),ky.getAdapter=my,ky.HttpStatusCode=Ry,ky.default=ky;const{Axios:Ty,AxiosError:Py,CanceledError:Oy,isCancel:Ey,CancelToken:Dy,VERSION:xy,all:Iy,Cancel:My,isAxiosError:jy,spread:Ly,toFormData:Ay,AxiosHeaders:Ny,HttpStatusCode:By,formToJSON:Fy,getAdapter:zy,mergeConfig:Vy}=ky;function Uy(e,t){return vt(e,t)}function $y(e,t){return r=>(i,n,s)=>e(n())?t(r)(i,n,s):(console.warn("Not authorized to perform this action"),!1)}function Gy(e){return t=>(r,i,n)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,i,n)}function qy(e,t){return Uy(e,(e,r)=>{const{getState:i}=r;return"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),Promise.reject("Action cannot be performed outside of a connected room")):t(e,r)})}function Hy(e,t){return r=>(i,n,s)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):$y(e,t)(r)(i,n,s)}const Wy=((e={})=>{const t=new Map,{extra:r,onError:i=tr}=e;Mt(i,"onError");const n=e=>(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&Qt(e)}))(Jt(t,e)??Kt(e));Ut(n,{withTypes:()=>n});const s=e=>{const r=Jt(t,e);return r&&(r.unsubscribe(),e.cancelActive&&Qt(r)),!!r};Ut(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=Ht(n,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,Ut({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Vt(c.signal),pause:zt(c.signal),extra:r,signal:c.signal,fork:qt(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,r)=>{e!==c&&(Nt(e,Dt),r.delete(e))})},cancel:()=>{Nt(c,Dt),e.pending.delete(c)},throwIfCancelled:()=>{Bt(c.signal)}})))}catch(e){e instanceof It||Yt(i,e,{raisedBy:"effect"})}finally{await Promise.all(l),Nt(c,xt),e.pending.delete(c)}},a=(e=>()=>{e.forEach(Qt),e.clear()})(t);return{middleware:e=>r=>c=>{if(!N(c))return r(c);if(Xt.match(c))return n(c.payload);if(Zt.match(c))return void a();if(er.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===$t)throw new Error(`${Gt}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),n=Array.from(t.values());for(const t of n){let n=!1;try{n=t.predicate(c,r,d)}catch(e){n=!1,Yt(i,e,{raisedBy:"predicate"})}n&&o(t,c,e,l)}}}finally{d=$t}return u},startListening:n,stopListening:s,clearListeners:a}})(),Ky=Wy.startListening,Jy=(e,t)=>Ky({predicate:(t,r,i)=>{const n=e.map(e=>e(i)),s=e.map(e=>e(r));return n.some((e,t)=>e!==s[t])},effect:(r,{dispatch:i,getState:n,extra:s})=>{const o=e.map(e=>e(n()));t({dispatch:i,getState:n,extra:s},...o)}}),Qy=Ct({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,ignoreBreakoutGroups:!1,roomName:null,roomUrl:null,displayName:null,userAgent:"core:0.34.0",externalId:null},reducers:{doAppStart:(e,t)=>{const r=new URL(t.payload.roomUrl);return Object.assign(Object.assign(Object.assign({},e),t.payload),{roomName:r.pathname,initialConfig:Object.assign({},t.payload),isActive:!0})},doAppStop:e=>Object.assign(Object.assign({},e),{isActive:!1})}}),{doAppStop:Yy,doAppStart:Xy}=Qy.actions,Zy=e=>e.app.isActive,ew=e=>e.app.isDialIn,tw=e=>e.app.roomName,rw=e=>e.app.displayName,iw=e=>e.app.userAgent,nw=e=>e.app.externalId;function sw(e){return qe(`signalConnection/event/${e}`)}const ow={audioEnabled:sw("audioEnabled"),audioEnableRequested:sw("audioEnableRequested"),breakoutGroupJoined:sw("breakoutGroupJoined"),breakoutMoveToGroup:sw("breakoutMoveToGroup"),breakoutMoveToMain:sw("breakoutMoveToMain"),breakoutSessionUpdated:sw("breakoutSessionUpdated"),chatMessage:sw("chatMessage"),clientLeft:sw("clientLeft"),clientKicked:sw("clientKicked"),clientMetadataReceived:sw("clientMetadataReceived"),clientUnableToJoin:sw("clientUnableToJoin"),cloudRecordingStarted:sw("cloudRecordingStarted"),cloudRecordingStopped:sw("cloudRecordingStopped"),disconnect:sw("disconnect"),knockerLeft:sw("knockerLeft"),knockHandled:sw("knockHandled"),newClient:sw("newClient"),roomJoined:sw("roomJoined"),roomKnocked:sw("roomKnocked"),roomLeft:sw("roomLeft"),roomLocked:sw("roomLocked"),roomSessionEnded:sw("roomSessionEnded"),screenshareStarted:sw("screenshareStarted"),screenshareStopped:sw("screenshareStopped"),spotlightAdded:sw("spotlightAdded"),spotlightRemoved:sw("spotlightRemoved"),streamingStopped:sw("streamingStopped"),videoEnabled:sw("videoEnabled"),videoEnableRequested:sw("videoEnableRequested"),liveTranscriptionStarted:sw("liveTranscriptionStarted"),liveTranscriptionStopped:sw("liveTranscriptionStopped")},aw={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},cw=Ct({name:"authorization",initialState:{roomKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(Xy,(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey})),e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:i}=t.payload||{},n=null==r?void 0:r.clients.find(e=>e.id===i);return n?Object.assign(Object.assign({},e),{roleName:(null==n?void 0:n.role.roleName)||"none"}):e})}}),{setRoomKey:dw}=cw.actions,lw=e=>e.authorization.roomKey,uw=e=>e.authorization.roleName,pw=Be(uw,e=>aw.canLockRoom.includes(e)),hw=Be(uw,e=>aw.canRequestAudioEnable.includes(e)),fw=Be(uw,e=>aw.canRequestVideoEnable.includes(e)),mw=Be(uw,e=>aw.canKickClient.includes(e)),gw=Be(uw,e=>aw.canEndMeeting.includes(e)),vw=Be(uw,e=>aw.canAskToSpeak.includes(e)),bw=Be(uw,e=>aw.canSpotlight.includes(e));function yw(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function ww(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const _w=Ct({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(Sw.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(Sw.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload})),e.addCase(Sw.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!0}))}}),Sw=Uy("deviceCredentials/doGetDeviceCredentials",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{extra:t}){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})),Cw=e=>e.deviceCredentials,Rw=e=>{var t,r;return null===(r=null===(t=e.deviceCredentials.data)||void 0===t?void 0:t.credentials)||void 0===r?void 0:r.uuid};Jy([Be(Zy,Cw,(e,t)=>!(!e||t.isFetching||t.data))],({dispatch:e},t)=>{t&&e(Sw())});const kw=Ct({name:"signalConnection",initialState:{deviceIdentified:!1,isIdentifyingDevice:!1,status:"ready",socket:null},reducers:{socketConnecting:e=>Object.assign(Object.assign({},e),{status:"connecting"}),socketConnected:(e,t)=>Object.assign(Object.assign({},e),{socket:t.payload,status:"connected"}),socketDisconnected:e=>Object.assign(Object.assign({},e),{socket:null,deviceIdentified:!1,status:"disconnected"}),socketReconnecting:e=>Object.assign(Object.assign({},e),{status:"reconnecting"}),deviceIdentifying:e=>Object.assign(Object.assign({},e),{isIdentifyingDevice:!0}),deviceIdentified:e=>Object.assign(Object.assign({},e),{deviceIdentified:!0,isIdentifyingDevice:!1})},extraReducers:e=>{e.addCase(ow.disconnect,e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"}))}}),{deviceIdentifying:Tw,deviceIdentified:Pw,socketConnected:Ow,socketConnecting:Ew,socketDisconnected:Dw,socketReconnecting:xw}=kw.actions,Iw=()=>(e,t)=>{if(Bw(t()))return;e(Ew());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new dg(e,{autoConnect:!1})}();r.on("connect",()=>e(Ow(r))),r.on("device_identified",()=>e(Pw())),r.getManager().on("reconnect",()=>e(xw())),function(e,t){e.on("room_joined",e=>t(ow.roomJoined(e))),e.on("new_client",e=>t(ow.newClient(e))),e.on("client_left",e=>t(ow.clientLeft(e))),e.on("client_kicked",e=>t(ow.clientKicked(e))),e.on("client_unable_to_join",e=>t(ow.clientUnableToJoin(e))),e.on("audio_enabled",e=>t(ow.audioEnabled(e))),e.on("video_enabled",e=>t(ow.videoEnabled(e))),e.on("audio_enable_requested",e=>t(ow.audioEnableRequested(e))),e.on("client_metadata_received",e=>t(ow.clientMetadataReceived(e))),e.on("chat_message",e=>t(ow.chatMessage(e))),e.on("disconnect",()=>t(ow.disconnect())),e.on("room_knocked",e=>t(ow.roomKnocked(e))),e.on("room_left",()=>t(ow.roomLeft())),e.on("room_locked",e=>t(ow.roomLocked(e))),e.on("room_session_ended",e=>t(ow.roomSessionEnded(e))),e.on("knocker_left",e=>t(ow.knockerLeft(e))),e.on("knock_handled",e=>t(ow.knockHandled(e))),e.on("screenshare_started",e=>t(ow.screenshareStarted(e))),e.on("screenshare_stopped",e=>t(ow.screenshareStopped(e))),e.on("cloud_recording_started",e=>t(ow.cloudRecordingStarted(e))),e.on("cloud_recording_stopped",()=>t(ow.cloudRecordingStopped())),e.on("streaming_stopped",()=>t(ow.streamingStopped())),e.on("spotlight_added",e=>t(ow.spotlightAdded(e))),e.on("spotlight_removed",e=>t(ow.spotlightRemoved(e))),e.on("live_transcription_started",e=>t(ow.liveTranscriptionStarted(e))),e.on("live_transcription_stopped",e=>t(ow.liveTranscriptionStopped(e))),e.on("video_enable_requested",e=>t(ow.videoEnableRequested(e))),e.on("breakout_group_joined",e=>t(ow.breakoutGroupJoined(e))),e.on("breakout_session_updated",e=>t(ow.breakoutSessionUpdated(e))),e.on("breakout_move_to_group",()=>t(ow.breakoutMoveToGroup())),e.on("breakout_move_to_main",()=>t(ow.breakoutMoveToMain()))}(r,e),r.connect()},Mw=({deviceCredentials:e})=>(t,r)=>{const i=r(),n=Bw(i),s=Aw(i);n&&(s||(n.emit("identify_device",{deviceCredentials:e}),t(Tw())))},jw=()=>(e,t)=>{const r=t();if("connected"===Nw(r)){const t=Lw(r).socket;null==t||t.disconnect(),e(Dw())}},Lw=e=>e.signalConnection,Aw=e=>e.signalConnection.deviceIdentified,Nw=e=>e.signalConnection.status,Bw=e=>e.signalConnection.socket;Jy([Be(Zy,Nw,(e,t)=>!(!e||!["ready","reconnecting"].includes(t)))],({dispatch:e},t)=>{t&&e(Iw())});const Fw=Be(Cw,Nw,Aw,e=>e.signalConnection.isIdentifyingDevice,(e,t,r,i)=>!(!e.data||"connected"!==t||r||i));function zw(e,{delay:t=500,edges:r}={}){let i,n=0;return(...s)=>{n+=1,r&&1===n&&e(...s),clearTimeout(i),i=setTimeout(()=>{(!r||n>1)&&e(...s),i=void 0,n=0},t)}}Jy([Fw,Cw],({dispatch:e},t,r)=>{t&&r.data&&e(Mw({deviceCredentials:r.data}))}),Ky({actionCreator:ow.roomLeft,effect:(e,{dispatch:t})=>{t(jw())}}),Ky({actionCreator:ow.clientKicked,effect:(e,{dispatch:t})=>{t(jw())}});const Vw=Ct({name:"localMedia",initialState:{busyDeviceIds:[],cameraEnabled:!1,currentSpeakerDeviceId:"default",devices:[],isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,isSettingSpeakerDevice:!1,isTogglingCamera:!1,lowDataMode:!1,microphoneEnabled:!1,status:"inactive",stream:void 0,isSwitchingStream:!1},reducers:{deviceBusy:(e,t)=>e.busyDeviceIds.includes(t.payload.deviceId)?e:Object.assign(Object.assign({},e),{busyDeviceIds:[...e.busyDeviceIds,t.payload.deviceId]}),toggleCameraEnabled(e,t){var r;return Object.assign(Object.assign({},e),{cameraEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.cameraEnabled})},setCurrentCameraDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentCameraDeviceId:t.payload.deviceId}),toggleMicrophoneEnabled(e,t){var r;return Object.assign(Object.assign({},e),{microphoneEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.microphoneEnabled})},setCurrentMicrophoneDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentMicrophoneDeviceId:t.payload.deviceId}),setCurrentSpeakerDeviceId(e,t){var r;return Object.assign(Object.assign({},e),{currentSpeakerDeviceId:null!==(r=t.payload.deviceId)&&void 0!==r?r:"default"})},toggleLowDataModeEnabled(e,t){var r;return Object.assign(Object.assign({},e),{lowDataMode:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.lowDataMode})},setDevices:(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}),setLocalMediaStream:(e,t)=>Object.assign(Object.assign({},e),{stream:t.payload.stream}),setLocalMediaOptions:(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.options}),localMediaStopped:e=>Object.assign(Object.assign({},e),{status:"stopped",stream:void 0}),localStreamMetadataUpdated(e,t){const{audio:r,video:i}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:i.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter(e=>e!==r.deviceId&&e!==i.deviceId)})}},extraReducers:e=>{e.addCase(Xy,(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions})),e.addCase(r_.pending,(e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:i,isSettingMicrophoneDevice:r})}),e.addCase(r_.fulfilled,(e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})}),e.addCase(r_.rejected,(e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:i?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})}),e.addCase(Zw.pending,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0})),e.addCase(Zw.fulfilled,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1})),e.addCase(i_.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices})),e.addCase(s_.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(s_.fulfilled,(e,{payload:{stream:t,onDeviceChange:r}})=>{let i,n,s=!1,o=!1;const a=t.getAudioTracks()[0],c=t.getVideoTracks()[0];return a&&(n=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,i=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:i,currentMicrophoneDeviceId:n,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})}),e.addCase(s_.rejected,(e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error})),e.addCase(n_.pending,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0})),e.addCase(n_.fulfilled,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})),e.addCase(n_.rejected,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))}}),{deviceBusy:Uw,setCurrentCameraDeviceId:$w,setCurrentMicrophoneDeviceId:Gw,setCurrentSpeakerDeviceId:qw,toggleCameraEnabled:Hw,toggleMicrophoneEnabled:Ww,toggleLowDataModeEnabled:Kw,setLocalMediaOptions:Jw,setLocalMediaStream:Qw,localMediaStopped:Yw,localStreamMetadataUpdated:Xw}=Vw.actions,Zw=Uy("localMedia/doToggleCamera",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){const i=t(),n=b_(i);if(!n)return;let s=n.getVideoTracks()[0];const o=u_(i);try{if(o)if(s)s.enabled=!0;else{const e=w_(i),t=c_(i);yield hv(Object.assign(Object.assign({},e),{audioId:!1,videoId:t,type:"exact"}),{replaceStream:n}),s=n.getVideoTracks()[0]}else{if(!s)return;s.enabled=!1,s.stop(),n.removeTrack(s)}n.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:s,enable:o}}))}catch(e){return r(e)}})),e_=Uy("localMedia/doToggleMicrophone",(e,{getState:t})=>{var r;const i=t(),n=b_(i);if(!n)return;const s=p_(i),o=null===(r=n.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)}),t_=()=>(e,t)=>{const r=t();if(!b_(r))return;const i=c_(r),n=d_(r);e(n_({audioId:n,videoId:i}))},r_=Uy("localMedia/reactSetDevice",(e,t)=>ww(void 0,[e,t],void 0,function*({audio:e,video:t},{getState:r,rejectWithValue:i}){try{const i=r(),n=b_(i);if(!n)throw new Error("No stream");const s=!!e&&d_(i),o=!!t&&c_(i),a=w_(i),{replacedTracks:c}=yield hv(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:n}),d=p_(i);n.getAudioTracks().forEach(e=>e.enabled=d);const l=u_(i);return n.getVideoTracks().forEach(e=>e.enabled=l),{replacedTracks:c}}catch(e){return i(e)}})),i_=Uy("localMedia/doUpdateDeviceList",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:i}){var n,s,o,a;const c=t();let d=[],l=[];const u=b_(c);try{d=yield navigator.mediaDevices.enumerateDevices(),l=f_(c);if(!(u&&!y_(c)&&d&&l&&l.find(e=>e.deviceId)))return{devices:d};const{changedDevices:e,addedDevices:t}=fv({oldDevices:l,newDevices:d});let i=null===(n=e.audioinput)||void 0===n?void 0:n.deviceId,p=null===(s=e.videoinput)||void 0===s?void 0:s.deviceId;return void 0===i&&(i=null===(o=t.audioinput)||void 0===o?void 0:o.deviceId),void 0===p&&(p=null===(a=t.videoinput)||void 0===a?void 0:a.deviceId),void 0===i&&void 0===p||r(n_({audioId:i,videoId:p})),{devices:d}}catch(e){return i(e)}})),n_=Uy("localMedia/doSwitchLocalStream",(e,t)=>ww(void 0,[e,t],void 0,function*({audioId:e,videoId:t},{dispatch:r,getState:i,rejectWithValue:n}){const s=i(),o=b_(s),a=w_(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:i}=yield hv(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),n=e||t;return c&&n&&r(Uw({deviceId:n})),{replacedTracks:i}}catch(i){console.error(i);const s=e||t;return c&&s&&r(Uw({deviceId:s})),n(i)}})),s_=Uy("localMedia/doStartLocalMedia",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:i}){const n=zw(()=>{r(i_())},{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",n),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:n});if(!e.audio&&!e.video)return{stream:new MediaStream,onDeviceChange:n};r(Jw({options:e}));try{yield r(i_());const i=t(),s=w_(i),{stream:o}=yield hv(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:n}}catch(e){return i(e)}})),o_=()=>(e,t)=>{const r=b_(t()),i=g_(t()).onDeviceChange;null==r||r.getTracks().forEach(e=>{e.stop()}),navigator.mediaDevices&&i&&navigator.mediaDevices.removeEventListener("devicechange",i),e(Yw())},a_=e=>e.localMedia.busyDeviceIds,c_=e=>e.localMedia.currentCameraDeviceId,d_=e=>e.localMedia.currentMicrophoneDeviceId,l_=e=>e.localMedia.currentSpeakerDeviceId,u_=e=>e.localMedia.cameraEnabled,p_=e=>e.localMedia.microphoneEnabled,h_=e=>e.localMedia.lowDataMode,f_=e=>e.localMedia.devices,m_=e=>e.localMedia.options;Be(m_,e=>!!e);const g_=e=>e.localMedia,v_=e=>e.localMedia.status,b_=e=>e.localMedia.stream,y_=e=>e.localMedia.isSwitchingStream,w_=Be(f_,c_,d_,h_,(e,t,r,i)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:i,simulcast:!0,widescreen:!0}})),__=Be(v_,e=>"starting"===e),S_=Be(f_,a_,(e,t)=>e.filter(e=>"videoinput"===e.kind).filter(e=>!t.includes(e.deviceId))),C_=Be(f_,a_,(e,t)=>e.filter(e=>"audioinput"===e.kind).filter(e=>!t.includes(e.deviceId))),R_=Be(f_,e=>e.filter(e=>"audiooutput"===e.kind));Jy([Be(Zy,v_,m_,(e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r})],({dispatch:e},t)=>{t&&e(s_(t))});Jy([Be(Zy,v_,m_,(e,t,r)=>!e&&"inactive"!==t&&!!r)],({dispatch:e},t)=>{t&&e(o_())}),Ky({predicate:(e,t,r)=>{const i=p_(r),n=p_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(e_())}}),Ky({predicate:(e,t,r)=>{const i=h_(r),n=h_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(t_())}}),Ky({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const i=u_(r),n=u_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Zw())}}),Ky({predicate:(e,t,r)=>{const i=c_(r),n=c_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(r_({audio:!1,video:!0}))}}),Ky({predicate:(e,t,r)=>{const i=d_(r),n=d_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(r_({audio:!0,video:!1}))}}),Ky({matcher:lt(s_.fulfilled,i_.fulfilled,n_.fulfilled,n_.rejected),effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=b_(i),s=f_(i);if(!n)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:i,lastAudioId:n,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||i,e=o(e),{video:uv("videoinput",t,r,s),audio:uv("audioinput",e,r,n)}}({audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0],devices:s});t(Xw(o))}}),Ky({actionCreator:ow.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Ww({enabled:!1}))}}),Ky({actionCreator:ow.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Hw({enabled:!1}))}}),Ky({actionCreator:ow.breakoutSessionUpdated,effect:({payload:e},{dispatch:t})=>{var r;!1===(null===(r=e.initiatedBy)||void 0===r?void 0:r.active)&&t(Ww({enabled:!1}))}});const k_=["recorder","streamer"],T_=e=>e.localParticipant,P_=e=>e.localParticipant.id,O_=e=>e.localParticipant.displayName,E_=e=>e.localParticipant.stickyReaction,D_=Be(T_,b_,(e,t)=>{const r={id:e.id,clientId:e.id,breakoutGroup:e.breakoutGroup,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return k_.includes(e.roleName)?null:r});function x_({assignments:e,groups:t,startedAt:r,initiatedBy:i,breakoutStartedAt:n,breakoutEndedAt:s,breakoutNotification:o,breakoutTimerDuration:a,autoMoveToGroup:c,moveToGroupGracePeriod:d,autoMoveToMain:l,moveToMainGracePeriod:u,enforceAssignment:p,breakoutTimerSetting:h}={}){return{assignments:e||null,groups:t||null,startedAt:r?new Date(r):null,initiatedBy:i,breakoutStartedAt:n||null,breakoutEndedAt:s||null,breakoutNotification:o||null,breakoutTimerDuration:a||1800,autoMoveToGroup:c||!1,moveToGroupGracePeriod:d||10,autoMoveToMain:l||!1,moveToMainGracePeriod:u||30,enforceAssignment:p||!1,breakoutTimerSetting:h||!1}}const I_=Ct({name:"breakout",initialState:Object.assign(Object.assign({},x_()),{groupId:null}),reducers:{},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{breakout:r}=t.payload||{};return r?Object.assign(Object.assign({},e),x_(r)):e}),e.addCase(ow.breakoutSessionUpdated,(e,t)=>Object.assign(Object.assign({},e),x_(t.payload))),e.addCase(ow.breakoutGroupJoined,(e,t)=>{var r;return(null===(r=t.meta)||void 0===r?void 0:r.localParticipantId)!==t.payload.clientId?e:Object.assign(Object.assign({},e),{groupId:t.payload.group})})}}),M_=e=>(t,r)=>{const i=r(),{socket:n}=Lw(i);null==n||n.emit("join_breakout_group",{group:e.group})},j_=e=>e.breakout,L_=e=>!!e.breakout.startedAt,A_=e=>e.breakout.assignments,N_=Be(j_,e=>e.localParticipant.breakoutGroup,(e,t)=>e.groupId||t||""),B_=Be(j_,N_,(e,t)=>{var r;const i=null===(r=e.groups)||void 0===r?void 0:r[t];return i?{id:t,name:i}:null});Ky({actionCreator:ow.breakoutMoveToGroup,effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=T_(i).breakoutGroupAssigned;n&&t(M_({group:n}))}}),Ky({actionCreator:ow.breakoutMoveToMain,effect:(e,{dispatch:t})=>{t(M_({group:""}))}}),Ky({actionCreator:ow.breakoutSessionUpdated,effect:({payload:e},{dispatch:t,getState:r})=>{var i;const n=r(),s=j_(n).autoMoveToMain;!1===(null===(i=e.initiatedBy)||void 0===i?void 0:i.active)&&(s||t(M_({group:""})))}});const F_=Ct({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(ow.chatMessage,(e,t)=>{const r={senderId:t.payload.senderId,timestamp:t.payload.timestamp,text:t.payload.text};return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,r]})})}}),z_=Gy(e=>(t,r)=>{const i=r(),n=Lw(i).socket,s=N_(i);null==n||n.emit("chat_message",Object.assign(Object.assign({text:e.text},s&&{breakoutGroup:s}),e.isBroadcast&&{broadcast:!0}))}),V_=Ct({name:"cloudRecording",initialState:{isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{status:"requested"})},extraReducers:e=>{e.addCase(ow.cloudRecordingStopped,e=>Object.assign(Object.assign({},e),{isRecording:!1,status:void 0})),e.addCase(ow.cloudRecordingStarted,(e,t)=>{const{payload:r}=t;return r.error?Object.assign(Object.assign({},e),{isRecording:!1,status:"error",error:r.error}):e}),e.addCase(ow.newClient,(e,{payload:t})=>{var r;const{client:i}=t;return"recorder"===(null===(r=i.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:i.startedCloudRecordingAt?new Date(i.startedCloudRecordingAt).getTime():(new Date).getTime()}):e})}}),{recordingRequestStarted:U_}=V_.actions,$_=Gy(()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=q_(r);n&&["recording","requested"].includes(n)||(null==i||i.emit("start_recording",{recording:"cloud"}),e(U_()))}),G_=Gy(()=>(e,t)=>{const r=t(),i=Lw(r).socket;null==i||i.emit("stop_recording")}),q_=e=>e.cloudRecording.status,H_=e=>e.roomConnection.status;function W_(e){return qe(`rtcConnection/event/${e}`)}const K_={rtcManagerCreated:W_("rtcManagerCreated"),rtcManagerDestroyed:W_("rtcManagerDestroyed"),streamAdded:W_("streamAdded"),clientConnectionStatusChanged:W_("clientConnectionStatusChanged")};function J_(e,t=!1){const{streams:r,role:i,breakoutGroup:n}=e,s=yw(e,["streams","role","breakoutGroup"]);return Object.assign(Object.assign({},s),{stream:null,streams:r.map(e=>({id:e,state:t?"new_accept":"to_accept"})),isLocalParticipant:!1,roleName:(null==i?void 0:i.roleName)||"none",presentationStream:null,breakoutGroup:n||null,newJoiner:t})}function Q_(e,t){const r=e.remoteParticipants.findIndex(e=>e.id===t);return{index:r,participant:e.remoteParticipants[r]}}function Y_(e,t,r){const{participant:i,index:n}=Q_(e,t);return i?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,n),Object.assign(Object.assign({},i),r),...e.remoteParticipants.slice(n+1)]}):(console.error(`Did not find client for update ${t}`),e)}function X_(e,t,r,i){const{participant:n}=Q_(e,t);if(!n)return console.error(`No client ${t} found to update stream ${r} ${i}`),e;const s=n.streams.findIndex(e=>e.id===r),o=[...n.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:i}),Y_(e,t,{streams:o})}function Z_(e,t,r){const{participant:i}=Q_(e,t);return!i||i.streams.find(e=>e.id===r)?(console.warn(`No participant ${t} or stream ${r} already exists`),e):Y_(e,t,{streams:[...i.streams,{id:r,state:"to_accept"}]})}const eS=Ct({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:i,state:n}of t.payload)r=X_(r,e,i,n);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:i}=t.payload;return Y_(e,r,{stream:i})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Z_(e,r,i)}},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:i}=t.payload||{};return(null==r?void 0:r.clients)?Object.assign(Object.assign({},e),{remoteParticipants:r.clients.filter(e=>e.id!==i).map(e=>J_(e))}):e}),e.addCase(K_.streamAdded,(e,t)=>function(e,t){const{clientId:r,stream:i,streamType:n}=t;let{streamId:s}=t;const{participant:o}=Q_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=i.id);const c=a.find(e=>e.id===r);if(!c)return e;const d=c.streams.find(e=>e.id===s);return c.stream&&(c.stream.id===s||c.stream.inboundId===s)||!c.stream&&"webcam"===n||!c.stream&&!n&&!d?Y_(e,r,{stream:i}):Y_(e,r,{presentationStream:i})}(e,t.payload)),e.addCase(ow.newClient,(e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=Q_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,J_(r,!0))}),e.addCase(ow.clientLeft,(e,t)=>{const{clientId:r}=t.payload;return function(e,t){return Object.assign(Object.assign({},e),{remoteParticipants:e.remoteParticipants.filter(e=>e.id!==t)})}(e,r)}),e.addCase(ow.audioEnabled,(e,t)=>{const{clientId:r,isAudioEnabled:i}=t.payload;return Y_(e,r,{isAudioEnabled:i})}),e.addCase(ow.videoEnabled,(e,t)=>{const{clientId:r,isVideoEnabled:i}=t.payload;return Y_(e,r,{isVideoEnabled:i})}),e.addCase(ow.clientMetadataReceived,(e,t)=>{const{error:r,payload:i}=t.payload;if(r||!i)return console.warn(r||"Client metadata error received"),e;const{clientId:n,displayName:s,stickyReaction:o}=i;return Y_(e,n,{displayName:s,stickyReaction:o})}),e.addCase(ow.breakoutGroupJoined,(e,t)=>{const{clientId:r,group:i}=t.payload;return Y_(e,r,{breakoutGroup:i||null})}),e.addCase(ow.screenshareStarted,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Z_(e,r,i)}),e.addCase(ow.screenshareStopped,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return function(e,t,r){var i,n;const{participant:s}=Q_(e,t);if(!s)return console.error(`No participant ${t} found to remove stream ${r}`),e;const o=s.stream&&s.stream.id,a=(null===(i=s.presentationStream)||void 0===i?void 0:i.inboundId)||(null===(n=s.presentationStream)||void 0===n?void 0:n.id),c=s.streams.findIndex(e=>e.id===r);return Y_(e,t,Object.assign(Object.assign({streams:s.streams.filter((e,t)=>t!==c)},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,i)})}}),{participantStreamAdded:tS,participantStreamIdAdded:rS,streamStatusUpdated:iS}=eS.actions,nS=Hy(e=>hw(e),e=>(t,r)=>{const i=r(),n=vw(i);if(e.enable&&!n)return void console.warn("Not authorized to perform this action");const s=Lw(i).socket;null==s||s.emit("request_audio_enable",e)}),sS=Hy(e=>fw(e),e=>(t,r)=>{const i=r(),n=Lw(i).socket;null==n||n.emit("request_video_enable",e)}),oS=e=>e.remoteParticipants.remoteParticipants,aS=Be(oS,e=>e.filter(e=>!k_.includes(e.roleName)));Be(oS,e=>e.length+1);const cS=Be(aS,T_,(e,t)=>k_.includes(t.roleName)?e.length:e.length+1),dS=Ct({name:"localScreenshare",initialState:{status:"inactive",stream:null,error:null},reducers:{stopScreenshare:(e,t)=>Object.assign(Object.assign({},e),{status:"inactive",stream:null})},extraReducers:e=>{e.addCase(uS.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(uS.fulfilled,(e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t})),e.addCase(uS.rejected,(e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null}))}}),{stopScreenshare:lS}=dS.actions,uS=qy("localScreenshare/doStartScreenshare",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r,rejectWithValue:i}){var n;try{const e=r(),i=hS(e);if(i)return{stream:i};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t(pS())};return"oninactive"in s?s.addEventListener("inactive",o):null===(n=s.getVideoTracks()[0])||void 0===n||n.addEventListener("ended",o),{stream:s}}catch(e){return i(e)}})),pS=Gy(()=>(e,t)=>{const r=t(),i=hS(r);i&&(i.getTracks().forEach(e=>e.stop()),e(lS({stream:i})))}),hS=e=>e.localScreenshare.stream;function fS(e){return"streamer"===e.roleName}function mS(e){return"recorder"===e.roleName}Ky({actionCreator:Yw,effect:(e,{getState:t})=>{const r=t(),i=hS(r);i&&(null==i||i.getTracks().forEach(e=>{e.stop()}))}});const gS=Ct({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{isLocked:Boolean(t.payload.isLocked)}):e;const{room:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r.isLocked)})}),e.addCase(ow.roomLocked,(e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})})}}),vS=$y(e=>pw(e),e=>(t,r)=>{const i=r(),{socket:n}=Lw(i);null==n||n.emit("set_lock",{locked:e.locked})}),bS=$y(e=>mw(e),e=>(t,r)=>{const i=r(),{socket:n}=Lw(i);null==n||n.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})}),yS=$y(e=>gw(e),e=>(t,r)=>{const i=r(),n=oS(i).map(e=>e.id);if(n.length){const{socket:e}=Lw(i);null==e||e.emit("kick_client",{clientIds:n,reasonId:"end-meeting"})}e.stayBehind||t(Yy())}),wS=Be(hS,T_,aS,(e,t,r)=>{const i=[];e&&i.push({id:e.id||"local-screenshare",participantId:"local",hasAudioTrack:e.getTracks().some(e=>"audio"===e.kind),breakoutGroup:t.breakoutGroup,stream:e,isLocal:!0});for(const e of r)e.presentationStream&&i.push({id:e.presentationStream.id||`pres-${e.id}`,participantId:e.id,hasAudioTrack:e.presentationStream.getTracks().some(e=>"audio"===e.kind),breakoutGroup:e.breakoutGroup,stream:e.presentationStream,isLocal:!1});return i}),_S=Be(hS,T_,aS,N_,A_,(e,t,r,i,n)=>{const s=[];if(e){const r=!!e.getAudioTracks().length;s.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e,breakoutGroup:i||""})}for(const e of r){if(fS(e)||mS(e))continue;const{presentationStream:t}=e,r=yw(e,["presentationStream"]),i=e.displayName||"Guest",o=t&&t.active,a="pres-"+e.id,c=e.stream&&e.stream.active,d=e.isVideoEnabled;s.push(Object.assign(Object.assign(Object.assign({},r),{breakoutGroupAssigned:(null==n?void 0:n[e.deviceId])||"",clientId:e.id,displayName:i,hasActivePresentation:!!o}),e.isVideoEnabled?{isVideoEnabled:d}:{})),o&&s.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${i})`,id:a,isPresentation:!0,isVideoEnabled:!0}),c&&{isRecording:null}))}return s}),SS=Be(D_,_S,(e,t)=>[...e?[e]:[],...t]),CS=Be(SS,L_,N_,(e,t,r)=>t&&r?e.filter(e=>e.isLocalClient||e.breakoutGroup===(r||"")||e.breakoutGroupAssigned&&e.breakoutGroupAssigned===r):e),RS=Be(SS,L_,e=>e.breakout.groups,(e,t,r)=>{if(!t||!r)return[];return[{clients:e.filter(e=>!e.breakoutGroup||""===e.breakoutGroup),group:{id:"",name:""}},...Object.entries(r).map(([t,r])=>({clients:e.filter(e=>!e.isPresentation&&e.breakoutGroup===t),group:{id:t,name:r}}))]});function kS({isPresentation:e,stream:t}){var r,i;return e?null!==(i=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==i?i:null==t?void 0:t.id:"0"}function TS(e,t){return e.find(e=>e.clientId===t.clientId&&e.streamId===t.streamId)?e:e.concat(t)}const PS=Ct({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:TS(e.sorted,{clientId:r,streamId:i})})},removeSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===i))})}},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{var r;if("error"in t.payload)return e;const{room:i}=t.payload||{};return i?Object.assign(Object.assign({},e),{sorted:null!==(r=i.spotlights)&&void 0!==r?r:e.sorted}):e}),e.addCase(ow.spotlightAdded,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:TS(e.sorted,{clientId:r,streamId:i})})}),e.addCase(ow.spotlightRemoved,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===i))})}),e.addMatcher(lt(ow.clientKicked,ow.clientLeft),(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>e.clientId!==r)})})}}),{addSpotlight:OS,removeSpotlight:ES}=PS.actions,DS=$y(e=>bw(e),({id:e})=>(t,r)=>{const i=r(),n=SS(i).find(t=>t.clientId===e);if(!n)return;const{socket:s}=Lw(i),o=kS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)}),xS=$y(e=>bw(e),({id:e})=>(t,r)=>{const i=r(),n=SS(i).find(t=>t.clientId===e);if(!n)return;const{socket:s}=Lw(i),o=kS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)}),IS=e=>e.spotlights.sorted;Be(T_,IS,(e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:i}){return!!e.find(e=>{const n=kS({isPresentation:t,stream:i});return e.clientId===r&&e.streamId===n})}({clientId:e.id,stream:e.stream,spotlights:t}));const MS=Be(SS,IS,(e,t)=>function(e,t){return e.reduce((e,r)=>{const i=t.find(e=>r.clientId===e.clientId&&r.streamId===kS(e));return i&&!e.includes(i)&&e.push(i),e},[])}(t,e));Ky({actionCreator:uS.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=T_(n);s&&r(OS({clientId:s.id,streamId:i.id}))}}),Ky({actionCreator:lS,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=T_(n);s&&r(ES({clientId:s.id,streamId:i.id}))}});const jS=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(JS(r)):"stream_added"===t?e(K_.streamAdded(r)):"rtc_manager_destroyed"===t?e(VS()):"client_connection_status_changed"===t&&e(K_.clientConnectionStatusChanged(r))}}),LS={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},AS=Ct({name:"rtcConnection",initialState:LS,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:i,height:n}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:i,height:n}})})},rtcDisconnected:()=>Object.assign({},LS),rtcDispatcherCreated:(e,t)=>Object.assign(Object.assign({},e),{dispatcherCreated:!0,rtcManagerDispatcher:t.payload}),rtcManagerCreated:(e,t)=>Object.assign(Object.assign({},e),{rtcManager:t.payload,status:"ready"}),rtcManagerDestroyed:e=>Object.assign(Object.assign({},e),{rtcManager:null}),rtcManagerInitialized:e=>Object.assign(Object.assign({},e),{rtcManagerInitialized:!0}),rtcClientConnectionStatusChanged:{reducer:e=>e,prepare:e=>({payload:{},meta:{localParticipantId:e.localParticipantId}})}},extraReducers:e=>{e.addCase(xw,e=>Object.assign(Object.assign({},e),{status:"reconnecting"})),e.addCase(ow.roomJoined,(e,t)=>"error"in t.payload?e:Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status}))}}),{resolutionReported:NS,rtcDispatcherCreated:BS,rtcDisconnected:FS,rtcManagerCreated:zS,rtcManagerDestroyed:VS,rtcManagerInitialized:US,isAcceptingStreams:$S,rtcClientConnectionStatusChanged:GS}=AS.actions,qS=()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=YS(r).rtcManagerDispatcher,s=u_(r),o=p_(r),a=(e=>e.app.isNodeSdk)(r);if(n||!i)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable:e=>function({client:e,breakoutCurrentId:t}){return!(!e||(t||!e.breakoutGroup)&&(e.isAudioEnabled||e.isVideoEnabled))}({client:aS(t()).find(t=>t.id===e),breakoutCurrentId:N_(t())||""})},d=new Vg({emitter:jS(e),serverSocket:i,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,vp9On:!1,h264On:!1,simulcastScreenshareOn:!1}});e(BS(d))},HS=()=>(e,t)=>{const{rtcManager:r}=YS(t());r&&r.disconnectAll(),e(FS())},WS=e=>(t,r)=>{var i;t($S(!0));const n=r(),s=YS(n).rtcManager,o=oS(n);if(!s)throw new Error("No rtc manager");const a=L_(n),c=null===(i=s.shouldAcceptStreamsFromBothSides)||void 0===i?void 0:i.call(s),d=[];for(const{clientId:t,streamId:r,state:i}of e){if(o.find(e=>e.id===t)){if("to_accept"===i||"new_accept"===i&&c||"old_accept"===i&&!c)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:a});else if("new_accept"===i||"old_accept"===i);else if("to_unaccept"===i)null==s||s.disconnect("0"===r?t:r,a);else if("done_accept"!==i)continue;d.push({clientId:t,streamId:r,state:i.replace(/to_|new_|old_/,"done_")})}}t(iS(d)),t($S(!1))},KS=({streamId:e,width:t,height:r})=>(i,n)=>{const{reportedStreamResolutions:s,rtcManager:o}=YS(n()),a=b_(n());if(!o||(null==a?void 0:a.id)===e)return;const c=s[e];c&&c.width===t&&c.height===r||o.updateStreamResolution(e,null,{width:t||1,height:r||1}),i(NS({streamId:e,width:t,height:r}))},JS=e=>t=>{const{rtcManager:r}=e;t(zS(r))},QS=()=>(e,t)=>{const r=b_(t()),i=YS(t()).rtcManager,n=u_(t()),s=p_(t());r&&i&&i.addNewStream("0",r,!s,!n),e(US())},YS=e=>e.rtcConnection,XS=e=>e.rtcConnection.rtcManagerInitialized,ZS=e=>e.rtcConnection.rtcManager,eC=e=>e.rtcConnection.status;Ky({actionCreator:r_.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:i}=YS(t()),n=b_(t());null==r||r.forEach(e=>{((e,t)=>{const r=null==n?void 0:n.getTracks().find(t=>t.kind===e);r&&(null==i||i.replaceTrack(t,r))})(e.kind,e)})}}),Ky({actionCreator:uS.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=YS(t());null==i||i.addNewStream(r.id,r,!1,!0)}}),Ky({actionCreator:Yy,effect:(e,{getState:t})=>{const r=ZS(t());null==r||r.rtcStatsDisconnect()}}),Ky({actionCreator:lS,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=YS(t());null==i||i.removeStream(r.id,r,null)}}),Ky({actionCreator:n_.fulfilled,effect:({payload:e},{getState:t})=>{var r;const i=b_(t()),{rtcManager:n}=YS(t());if(i&&n){const t=(e,t)=>{const r=i.getTracks().find(t=>t.kind===e);return r&&n.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach(e=>{t(e.kind,e)})}}}),Ky({actionCreator:K_.clientConnectionStatusChanged,effect:(e,{dispatch:t,getState:r})=>{const i=T_(r());t(GS({localParticipantId:i.id}))}});Jy([Be(eC,Zy,e=>e.rtcConnection.dispatcherCreated,e=>e.rtcConnection.isCreatingDispatcher,Bw,(e,t,r,i,n)=>!(!t||"inactive"!==e||r||i||!n))],({dispatch:e},t)=>{t&&e(qS())});const tC=Be(ZS,XS,v_,(e,t,r)=>!("started"!==r||!e||t));Jy([tC],({dispatch:e},t)=>{t&&e(QS())});Jy([Be(eC,Zy,(e,t)=>!t&&!["inactive","disconnected"].includes(e))],({dispatch:e},t)=>{t&&e(HS())});const rC=Be(eC,oS,N_,IS,e=>e.app.ignoreBreakoutGroups,(e,t,r,i,n)=>{if("ready"!==e)return[];const s=[];for(const e of t){const{streams:t,id:o,newJoiner:a}=e,c=i.find(t=>t.clientId===e.id&&"0"===t.streamId);for(let i=0;i<t.length;i++){let d=t[i].id,l=t[i].state;if((null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===i?(d=t[1].id,l=t[1].state):1===i&&(d=t[0].id,l=t[0].state)),!e.breakoutGroup&&!r||e.breakoutGroup===r||""===e.breakoutGroup&&c||n){if("done_accept"===l)continue;s.push({clientId:o,streamId:d,state:(a&&"0"===d?"new":"to")+"_accept"})}else{if("done_unaccept"===l)continue;s.push({clientId:o,streamId:d,state:"to_unaccept"})}}}return s});Jy([rC,e=>e.rtcConnection.isAcceptingStreams],({dispatch:e},t,r)=>{0<t.length&&!r&&e(WS(t))});const iC={running:!1},nC=Ct({name:"connectionMonitor",initialState:iC,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},iC)}}),{connectionMonitorStarted:sC,connectionMonitorStopped:oC}=nC.actions,aC=()=>(e,t)=>{var r;r=()=>{const e=t(),r=SS(e).map(e=>{var t,r;return{id:e.id,clientId:e.clientId,isLocalClient:e.isLocalClient,audio:{enabled:e.isAudioEnabled,track:null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks()[0]},video:{enabled:e.isVideoEnabled,track:null===(r=e.stream)||void 0===r?void 0:r.getVideoTracks()[0]},isPresentation:e.isPresentation}});return r},uf.getClients=r;const i=rv({onUpdatedIssues:e=>{var r;const i=t(),n=ZS(i);if(!n)return;let s=0,o=0,a=0,c=0;Object.entries(e.aggregated.metrics).forEach(([e,t])=>{/loc.*packetloss/.test(e)&&(s=Math.max(s,t.curMax)),/rem.*packetloss/.test(e)&&(o=Math.max(o,t.curMax)),/loc.*bitrate/.test(e)&&(a+=t.curSum),/rem.*bitrate/.test(e)&&(c+=t.curSum)}),n.sendStatsCustomEvent("insightsStats",{ls:Math.round(1e3*s)/1e3,lr:Math.round(1e3*o)/1e3,bs:Math.round(a),br:Math.round(c),cpu:null===(r=e.aggregated.metrics["global-cpu-pressure"])||void 0===r?void 0:r.curSum,_time:Date.now()})}});e(sC({stopIssueSubscription:i.stop}))},cC=()=>(e,t)=>{const r=t(),i=lC(r);i&&i(),e(oC())},dC=e=>e.connectionMonitor.running,lC=e=>e.connectionMonitor.stopCallbackFunction,uC=Be(H_,dC,(e,t)=>!t&&"connected"===e),pC=Be(H_,dC,(e,t)=>!(!t||!["kicked","left"].includes(e)));Jy([uC],({dispatch:e},t)=>{t&&e(aC())}),Jy([pC],({dispatch:e},t)=>{t&&e(cC())});const hC=Ct({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,breakoutGroupAssigned:"",isAudioEnabled:!0,isVideoEnabled:!0,isLocalParticipant:!0,stream:void 0,isScreenSharing:!1,roleName:"none",clientClaim:void 0,stickyReaction:void 0,isDialIn:!1},reducers:{setDisplayName:(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}),setBreakoutGroupAssigned:(e,t)=>Object.assign(Object.assign({},e),{breakoutGroupAssigned:t.payload.breakoutGroupAssigned})},extraReducers:e=>{e.addCase(Xy,(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName})),e.addCase(vC.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload})),e.addCase(bC.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload})),e.addCase(yC.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload})),e.addCase(ow.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{id:t.payload.selfId}):e;const{room:i,selfId:n,clientClaim:s}=t.payload||{},o=i.clients.find(e=>e.id===n);return Object.assign(Object.assign({},e),{id:n,roleName:(null===(r=null==o?void 0:o.role)||void 0===r?void 0:r.roleName)||"none",clientClaim:s,breakoutGroup:(null==o?void 0:o.breakoutGroup)||null})}),e.addCase(ow.breakoutGroupJoined,(e,t)=>{var r,i;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(i=t.payload)||void 0===i?void 0:i.group})})}}),{setDisplayName:fC,setBreakoutGroupAssigned:mC}=hC.actions,gC=Gy(e=>(t,r)=>{const i=r(),n=Lw(i).socket;null==n||n.emit("send_client_metadata",{type:"UserData",payload:{displayName:e.displayName}}),t(fC({displayName:e.displayName}))}),vC=qy("localParticipant/doEnableAudio",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r}){const i=r(),n=Lw(i).socket;return null==n||n.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(yC({enabled:!1})),e.enabled})),bC=qy("localParticipant/doEnableVideo",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t}){const r=t(),i=Lw(r).socket;return null==i||i.emit("enable_video",{enabled:e.enabled}),e.enabled})),yC=qy("localParticipant/doSetLocalStickyReaction",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){var i;const n=t(),s=E_(n),o=Boolean(s),a=null!==(i=e.enabled)&&void 0!==i?i:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})),wC=Gy(()=>(e,t)=>{const r=t(),i=Lw(r).socket,n={displayName:O_(r),stickyReaction:E_(r)};null==i||i.emit("send_client_metadata",{type:"UserData",payload:n})});Ky({actionCreator:Hw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isVideoEnabled:n}=T_(r());"connected"===H_(r())&&t(bC({enabled:i||!n}))}}),Ky({actionCreator:Ww,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isAudioEnabled:n}=T_(r());"connected"===H_(r())&&t(vC({enabled:i||!n}))}}),Jy([O_,E_,H_],({dispatch:e},t,r,i)=>{"connected"===i&&e(wC())}),Jy([A_,Rw,T_],({dispatch:e},t,r,i)=>{const n=(null==t?void 0:t[r||""])||"";i.breakoutGroupAssigned!==n&&e(mC({breakoutGroupAssigned:n}))});function _C(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const SC=Ct({name:"notifications",initialState:{emitter:new bp,events:[]},reducers:{addNotification:(e,t)=>Object.assign(Object.assign({},e),{events:[...e.events,Object.assign({},t.payload)]}),doClearNotifications:e=>Object.assign(Object.assign({},e),{events:[]})}}),{doClearNotifications:CC}=SC.actions,RC=e=>(t,r)=>{t(SC.actions.addNotification(e));const i=r(),n=kC(i);n.emit(e.type,e),n.emit("*",e)},kC=e=>e.notifications.emitter;Ky({actionCreator:ow.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const i=r(),n=aS(i).find(({id:t})=>t===e.senderId);n?t(RC(_C({type:"chatMessageReceived",message:`${n.displayName} says: ${e.text}`,props:{client:n,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),Ky({actionCreator:ow.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=aS(s).find(({id:e})=>e===n);o?t(RC(_C({type:i?"requestAudioEnable":"requestAudioDisable",message:i?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local audio change")}}),Ky({actionCreator:ow.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=aS(s).find(({id:e})=>e===n);o?t(RC(_C({type:i?"requestVideoEnable":"requestVideoDisable",message:i?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local video change")}}),Ky({actionCreator:ow.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:i})=>{var n;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=i();if(!vw(d))return;const l=aS(d).find(({id:e})=>e===a);if(!l)return void console.warn("Could not find remote client that provided updated metadata");const u=r(),p=aS(u).find(({id:e})=>e===a);(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(n=null==p?void 0:p.stickyReaction)||void 0===n?void 0:n.timestamp)&&t(RC(_C({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),Jy([Nw],({dispatch:e,getState:t},r)=>{const i=t(),n=H_(i);["left","kicked"].includes(n)||("disconnected"===r?e(RC(_C({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(RC(_C({type:"signalOk",message:"Network connection available",props:{}}))))}),Ky({actionCreator:ow.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(RC(_C({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const TC=Ct({name:"organization",initialState:{data:null,isFetching:!1,error:null},reducers:{},extraReducers:e=>{e.addCase(PC.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(PC.fulfilled,(e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(PC.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0}))}}),PC=Uy("organization/doOrganizationFetch",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{extra:t,getState:r}){try{const e=r().app.roomUrl,i=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!i)throw new Error("Invalid room url");return i}catch(e){console.error(e)}})),OC=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};Jy([Be(Zy,e=>e.organization,Cw,(e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching))],({dispatch:e},t)=>{t&&e(PC())});const EC=Ct({name:"roomConnection",initialState:{session:null,status:"ready",error:null},reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error&&t.payload.isLocked?Object.assign(Object.assign({},e),{status:"room_locked"}):Object.assign(Object.assign({},e),{status:"disconnected",error:t.payload.error});const{room:i}=t.payload;return Object.assign(Object.assign({},e),{status:"connected",session:null!==(r=i.session)&&void 0!==r?r:null})}),e.addCase(ow.disconnect,e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"})),e.addCase(ow.newClient,(e,t)=>{var r,i;return Object.assign(Object.assign({},e),{session:null!==(i=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==i?i:null})}),e.addCase(ow.roomSessionEnded,(e,t)=>{var r;return(null===(r=e.session)||void 0===r?void 0:r.id)!==t.payload.roomSessionId?e:Object.assign(Object.assign({},e),{session:null})}),e.addCase(ow.clientKicked,e=>Object.assign(Object.assign({},e),{status:"kicked"})),e.addCase(ow.roomLeft,e=>Object.assign(Object.assign({},e),{status:"left"})),e.addCase(xw,e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))}}),{connectionStatusChanged:DC}=EC.actions,xC=()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=tw(r),s=lw(r),o=rw(r),a=ew(r),c=iw(r),d=nw(r),l=OC(r);"room_locked"===H_(r)?(null==i||i.emit("knock_room",{avatarUrl:null,config:{isAudioEnabled:!0,isVideoEnabled:!0},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:a,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:c,externalId:d}),e(DC("knocking"))):console.warn("Room is not locked, knock aborted")},IC=()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=tw(r),s=lw(r),o=rw(r),a=iw(r),c=nw(r),d=ew(r),l=OC(r),u=u_(t()),p=p_(t()),h=(e=>e.localParticipant.clientClaim)(t());null==i||i.emit("join_room",Object.assign({avatarUrl:null,config:{isAudioEnabled:p,isVideoEnabled:u},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:d,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:a,externalId:c},h&&{clientClaim:h})),e(DC("connecting"))};Jy([Be([Zy,OC,H_,Aw,v_,e=>e.roomConnection.error],(e,t,r,i,n,s)=>!(!(e&&"started"===n&&i&&t&&["ready","reconnecting","disconnected"].includes(r))||s))],({dispatch:e},t)=>{t&&e(IC())}),Ky({actionCreator:ow.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:i,resolution:n}=e,s=r();i===P_(s)&&("accepted"===n?(t(dw(e.metadata.roomKey)),t(IC())):"rejected"===n&&t(DC("knock_rejected")))}}),Ky({actionCreator:Yy,effect:(e,{dispatch:t,getState:r})=>{const i=r();if("connected"===H_(i)){const e=Lw(i).socket;null==e||e.emit("leave_room"),t(DC("leaving"))}else jw()}});const MC={audioEnabled:{actions:[vC.fulfilled],rtcEventName:"audioEnabled",getValue:e=>p_(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[bC.fulfilled],rtcEventName:"videoEnabled",getValue:e=>u_(e),getOutput:e=>({enabled:e})},localStream:{actions:[r_.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=b_(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({stream:e})},localScreenshareStream:{actions:[uS.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=hS(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({tracks:e})},localScreenshareStreamStopped:{actions:[lS],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[fC],rtcEventName:"displayName",getValue:e=>{const t=O_(e),r=(e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.preferences})(e);return(null==r?void 0:r.hideInsightsDisplayNames)?"[[redacted]]":t},getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>P_(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>Rw(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>nw(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>OC(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>Nw(e),getOutput:e=>({status:e})},roomSessionId:{actions:[ow.newClient,ow.roomJoined,ow.roomSessionEnded,ow.clientLeft],rtcEventName:"roomSessionId",getValue:e=>(e=>{var t;return null===(t=e.roomConnection.session)||void 0===t?void 0:t.id})(e),getOutput:e=>({roomSessionId:e})},rtcConnectionStatus:{actions:null,rtcEventName:"rtcConnectionStatus",getValue:e=>eC(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>uw(e),getOutput:e=>({userRole:e})}},jC=Object.values(MC).flatMap(({actions:e})=>{var t;return null!==(t=null==e?void 0:e.map(e=>e))&&void 0!==t?t:null}).filter(e=>null!==e),LC=e=>"object"==typeof e?JSON.stringify(e):e,AC=Ct({name:"rtcAnalytics",initialState:{reportedValues:{}},reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),NC=()=>(e,t)=>{const r=t(),i=YS(r).rtcManager;i&&(i.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(MC).forEach(({rtcEventName:t,getValue:n,getOutput:s})=>{var o;const a=n(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=LC(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(i.sendStatsCustomEvent(t,c),e(BC({rtcEventName:t,value:a})))}))},{updateReportedValues:BC}=AC.actions;Ky({matcher:lt(...jC),effect:({type:e},{getState:t,dispatch:r})=>{var i;const n=t(),s=YS(n).rtcManager;if(!s)return;const o=Object.values(MC).find(({actions:t})=>null==t?void 0:t.map(e=>e.type).includes(e));if(!o)return;const{getValue:a,getOutput:c,rtcEventName:d}=o,l=a(n),u=LC(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(i=n.rtcAnalytics.reportedValues)||void 0===i?void 0:i[d])!==u&&(s.sendStatsCustomEvent(d,p),r(BC({rtcEventName:d,value:l})))}}),Jy([XS],({dispatch:e},t)=>{t&&e(NC())});const FC=Ct({name:"streaming",initialState:{isStreaming:!1,error:null,startedAt:void 0},reducers:{doHandleStreamingStarted:e=>Object.assign(Object.assign({},e),{isStreaming:!0,error:null,startedAt:(new Date).getTime()}),doHandleStreamingStopped:e=>Object.assign(Object.assign({},e),{isStreaming:!1})}}),{doHandleStreamingStarted:zC,doHandleStreamingStopped:VC}=FC.actions,UC=Ct({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r}=t.payload;return r.knockers.length?Object.assign(Object.assign({},e),{waitingParticipants:r.knockers.map(e=>({id:e.clientId,displayName:e.displayName}))}):e}),e.addCase(ow.roomKnocked,(e,t)=>{const{clientId:r,displayName:i}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:i}]})}),e.addCase(ow.knockerLeft,(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter(e=>e.id!==r)})})}}),$C=Gy(e=>(t,r)=>{const{participantId:i}=e,n=r(),s=Bw(n);null==s||s.emit("handle_knock",{action:"accept",clientId:i,response:{}})}),GC=Gy(e=>(t,r)=>{const{participantId:i}=e,n=r(),s=Bw(n);null==s||s.emit("handle_knock",{action:"reject",clientId:i,response:{}})}),qC=L({app:Qy.reducer,authorization:cw.reducer,breakout:I_.reducer,chat:F_.reducer,cloudRecording:V_.reducer,connectionMonitor:nC.reducer,deviceCredentials:_w.reducer,localMedia:Vw.reducer,localParticipant:hC.reducer,localScreenshare:dS.reducer,notifications:SC.reducer,organization:TC.reducer,remoteParticipants:eS.reducer,room:gS.reducer,roomConnection:EC.reducer,rtcAnalytics:AC.reducer,rtcConnection:AS.reducer,signalConnection:kw.reducer,spotlights:PS.reducer,streaming:FC.reducer,waitingParticipants:UC.reducer}),HC=(e,t)=>{var r;if(Xy.match(t)){const i={app:Object.assign(Object.assign({},Qy.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},Vw.getInitialState()),null==e?void 0:e.localMedia)};return qC(i,t)}return qC(e,t)};let WC,KC=class{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}};function JC(e,t){return Am.ok(e,`${t} is required`),e}function QC(e,t){return Am.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function YC(e,t){return Am.ok("number"==typeof e,`${t}<number> is required`),e}function XC(e,t){return Am.ok("string"==typeof e,`${t}<string> is required`),e}function ZC(e,t,r){const i=r||t.name[0].toLowerCase()+t.name.substring(1);return Am.ok(e instanceof t,`${i}<${t.name}> is required`),e}function eR(e,t){return Am.ok(Array.isArray(e),`${t}<array> is required`),e}function tR(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function rR(e,t,r){XC(t,"name"),function(e,t,r){XC(r,"name");const i=`${r} must be null or of type ${t}`;Am.ok(null===e||typeof e===t,i)}(e,"string",t)}function iR({baseUrl:e,url:t}){return e?e+t:t}class nR{constructor({baseUrl:e}){XC(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return ky.request(r)}request(e,t){return XC(e,"url"),Am.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Am.ok(t,"options are required"),this._requestAxios(e,t).then(e=>{const{data:t,headers:r,status:i,statusText:n,config:s}=e,o=s&&s.url?iR({baseUrl:s.baseURL,url:s.url}):null;return new KC({data:t,headers:r,status:i,statusText:n,url:o})}).catch(e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:i,status:n,statusText:s,config:o}=t,a=o&&o.url?iR({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new KC({data:r,headers:i,status:n,statusText:s,url:a}))})}}class sR{constructor({httpClient:e}){Am.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){Am.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach(r=>{const i=e[r];t.append(r,i)}),t}request(e,t={}){const r=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:r,transformRequest:sR.dataToFormData}))}}WC="object"==typeof window?window.btoa||vv:"object"==typeof global&&global.btoa||vv;const oR=()=>Promise.resolve(null);class aR{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then(r=>{const i=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${WC(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),n=Object.assign({},t,{headers:i});return this._httpClient.request(e,n)})}}class cR{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=oR}={}){this.authenticatedHttpClient=new aR({httpClient:new nR({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new sR({httpClient:this.authenticatedHttpClient})}request(e,t){return XC(e,"url"),Am.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Am.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return XC(e,"url"),Am.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Am.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function dR(e,t){return XC(tR(e,"data")[t],t)}const lR=(uR=dR,(e,t)=>{const r=tR(e,"data")[t];return null==r?null:uR(e,t)});var uR;function pR(e,t,r){return function(e,t){return eR(tR(e,"data")[t],t)}(e,t).map(e=>r(e))}class hR{constructor(e,t,r=void 0){this.credentials={uuid:e},this.hmac=t,this.userId=r}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new hR(dR(function(e,t){const r=tR(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),dR(e,"hmac"),lR(e,"userId")||void 0)}}class fR{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then(({data:e})=>hR.fromJson(e)).catch(e=>{if(e.response&&404===e.response.status)return null;throw e})}}class mR{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise(t=>{this._chromeStorage.get(this._key,r=>{t(r[this._key]||e)})})}save(e){return new Promise(t=>{this._chromeStorage.set({[this._key]:e},()=>{t()})})}}class gR{constructor(e,t){JC(t,"localStorage"),this._key=XC(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let vR;try{vR=self.localStorage}catch(iv){vR={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var bR=vR;const yR="credentials_saved";class wR extends bp{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const i=new fR({apiClient:new cR({baseUrl:e})});let n=null;if("localStorage"===r)n=new gR(t,bR);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);n=new mR(t,window.chrome.storage.local)}return new wR({deviceService:i,credentialsStore:n})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise(t=>{const r=()=>{this._deviceService.getCredentials().then(r=>e.save(r?r.toJson():null).then(()=>t(r))).catch(()=>{setTimeout(r,2e3)})};r()})}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then(e=>e?hR.fromJson(e):null)}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then(e=>e||this._fetchNewCredentialsFromApi())),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then(()=>(this.emit(yR,e),e))}setUserId(e){return this.getCurrentCredentials().then(t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))}).then(()=>{})}}class _R{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:i}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=i}static fromJson(e){return new _R({isExhausted:QC(e.isExhausted,"isExhausted"),renewsAt:new Date(XC(e.renewsAt,"renewsAt")),totalMinutesLimit:YC(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:YC(e.totalMinutesUsed,"totalMinutesUsed")})}}class SR{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:i,onTrialUntil:n,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=i,this.onTrialUntil=n||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new SR({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:QC(e.isDeactivated,"isDeactivated"),isOnTrial:QC(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?_R.fromJson(e.embeddedFreeTierStatus):null})}}function CR(e){return null!=e}function RR(e={}){return{maxNumberOfInvitationsAndUsers:CR(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:CR(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:CR(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:CR(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:CR(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class kR{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,ZC(e,Object,"properties"),XC(e.organizationId,"organizationId"),XC(e.organizationName,"organizationName"),XC(e.subdomain,"subdomain"),ZC(e.permissions,Object,"permissions"),ZC(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new SR(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=ZC(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},i=(null==t?void 0:t.onboardingSurvey)||null,n=ZC(t.permissions,Object,"permissions");return new kR({organizationId:XC(t.organizationId,"organizationId"),organizationName:XC(t.organizationName,"organizationName"),subdomain:XC(t.subdomain,"subdomain"),permissions:n,limits:RR(ZC(t.limits,Object,"limits")),account:t.account?SR.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:r,onboardingSurvey:i,type:"string"==typeof t.type?t.type:null})}}kR.GLOBAL_ORGANIZATION_ID="1";class TR{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:i,consents:n}=r||{},s="email"in r?{value:r.email,verificationCode:XC(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(XC(t,"subdomain"),XC(e,"organizationName"),XC(i,"owner.displayName"),Am.ok(s||o,"owner.email or owner.idToken is required"),n){eR(n,"consents");for(const{consentRevisionId:e,action:t}of n)XC(e,"consentRevisionId"),rR(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},s&&{email:s}),o&&{idToken:o}),n&&{consents:n}),{displayName:i})}}).then(({data:e})=>dR(e,"organizationId"))}getOrganizationBySubdomain(e){return XC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then(({data:e})=>kR.fromJson(e)).catch(e=>{if(e instanceof KC){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationByOrganizationId(e){return XC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then(({data:e})=>kR.fromJson(e)).catch(e=>{if(e instanceof KC){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationsByContactPoint(e){const{code:t}=e,r="email"in e?e.email:null,i="phoneNumber"in e?e.phoneNumber:null;Am.ok((r||i)&&!(r&&i),"either email or phoneNumber is required"),XC(t,"code");const n=r?{type:"email",value:r}:{type:"phoneNumber",value:i};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:n,code:t}}).then(({data:e})=>pR(e,"organizations",e=>kR.fromJson(e)))}getOrganizationsByIdToken({idToken:e}){return XC(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then(({data:e})=>pR(e,"organizations",e=>kR.fromJson(Object.assign({permissions:{},limits:{}},tR(e,"organization")))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then(({data:e})=>pR(e,"organizations",e=>kR.fromJson(Object.assign({permissions:{},limits:{}},tR(e,"organization")))))}getSubdomainAvailability(e){return XC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then(({data:e})=>(ZC(e,Object,"data"),{status:dR(e,"status")}))}updatePreferences({organizationId:e,preferences:t}){return JC(e,"organizationId"),JC(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then(()=>{})}deleteOrganization({organizationId:e}){return JC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then(()=>{})}}class PR{constructor({organizationService:e,subdomain:t}){this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then(()=>{})}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}const OR="https://api.whereby.dev";const ER=s.createContext(null);R(ER);const DR=function(e=w){const t=e===w?k:R(e),r=()=>t().dispatch;return Object.assign(r,{withTypes:()=>r}),r}(ER),xR=function(e=w){const t=e===w?C:S(e),r=(e,r={})=>{const{equalityFn:i=T}="function"==typeof r?{equalityFn:r}:r;if(!e)throw new Error("You must pass a selector to useSelector");if("function"!=typeof e)throw new Error("You must pass a function as a selector to useSelector");if("function"!=typeof i)throw new Error("You must pass a function as an equality function to useSelector");const n=t(),{store:o,subscription:a,getServerState:c}=n,d=s.useRef(!0),l=s.useCallback({[e.name](t){const s=e(t);{const{devModeChecks:o={}}="function"==typeof r?{}:r,{identityFunctionCheck:a,stabilityCheck:c}=n,{identityFunctionCheck:l,stabilityCheck:u}={stabilityCheck:c,identityFunctionCheck:a,...o};if("always"===u||"once"===u&&d.current){const r=e(t);if(!i(s,r)){let i;try{throw new Error}catch(e){({stack:i}=e)}console.warn("Selector "+(e.name||"unknown")+" returned a different result when called with the same parameters. This can lead to unnecessary rerenders.\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization",{state:t,selected:s,selected2:r,stack:i})}}if(("always"===l||"once"===l&&d.current)&&s===t){let t;try{throw new Error}catch(e){({stack:t}=e)}console.warn("Selector "+(e.name||"unknown")+" returned the root state when called. This can lead to unnecessary rerenders.\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.",{stack:t})}d.current&&(d.current=!1)}return s}}[e.name],[e]),u=p.useSyncExternalStoreWithSelector(a.addNestedSub,o.getState,c||o.getState,l,i);return s.useDebugValue(u),u};return Object.assign(r,{withTypes:()=>r}),r}(ER);var IR=function(){return IR=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},IR.apply(this,arguments)};function MR(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}"function"==typeof SuppressedError&&SuppressedError;const jR=DR.withTypes(),LR=xR.withTypes(),AR=({stream:e,muted:r})=>{const i=t.useRef(null),n=LR(l_);return t.useEffect(()=>{i.current&&!r&&e&&n&&(i.current.srcObject!==e&&(i.current.srcObject=e),i.current.setSinkId&&i.current.setSinkId(n))},[e,i,n,r]),i},NR=s.forwardRef((e,t)=>{var{muted:r,mirror:i=!1,stream:n,onVideoResize:o}=e,a=MR(e,["muted","mirror","stream","onVideoResize"]);const c=jR(),d=s.useRef(null),l=AR({muted:r,stream:n});return s.useImperativeHandle(t,()=>Object.assign(d.current,{captureAspectRatio:()=>{if(!d.current)return null;const e=d.current.videoHeight,t=d.current.videoWidth;return t&&e&&t+e>20?t/e:null}})),s.useEffect(()=>{if(!d.current)return;const e=new ResizeObserver(zw(()=>{if(d.current&&(null==n?void 0:n.id)){const e=d.current.clientWidth,t=d.current.clientHeight;c(KS({streamId:n.id,width:e,height:t})),o&&o({width:e,height:t,stream:n})}},{delay:1e3,edges:!0}));return e.observe(d.current),()=>{e.disconnect()}},[n]),s.useEffect(()=>{d.current&&(d.current.srcObject!==n&&(d.current.srcObject=n),d.current.muted!==r&&(d.current.muted=Boolean(r)))},[r,n,d]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:d,autoPlay:!0,playsInline:!0},a,{style:Object.assign({transform:i?"scaleX(-1)":"none",width:"100%",height:"100%"},a.style)})),s.createElement("audio",{ref:l,autoPlay:!0,playsInline:!0}))});NR.displayName="VideoView";const BR=Be(e=>e.chat.chatMessages,e=>e.cloudRecording,B_,L_,RS,CS,T_,b_,aS,wS,H_,e=>e.streaming,e=>e.waitingParticipants.waitingParticipants,kC,MS,(e,t,r,i,n,s,o,a,c,d,l,u,p,h,f)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,breakout:{isActive:i,currentGroup:r,groupedParticipants:n,participantsInCurrentGroup:s},connectionStatus:l,events:h,liveStream:u.isStreaming?{status:"streaming",startedAt:u.startedAt}:void 0,localScreenshareStatus:o.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},o),{stream:a}),remoteParticipants:c,screenshares:d,waitingParticipants:p,spotlightedParticipants:f})),FR={localMediaOptions:{audio:!0,video:!0}};const zR=Be(e=>e.localMedia.cameraDeviceError,S_,c_,d_,l_,e=>e.localMedia.isSettingCameraDevice,e=>e.localMedia.isSettingMicrophoneDevice,__,b_,e=>e.localMedia.microphoneDeviceError,C_,R_,e=>e.localMedia.startError,(e,t,r,i,n,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:i,currentSpeakerDeviceId:n,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p}));var VR={TABLET_BREAKPOINT:750,BOTTOM_TOOLBAR_HEIGHT:82,VIDEO_CONTROLS_MIN_WIDTH:420,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800};function UR({top:e=0,left:t=0}={}){return{top:e,left:t}}function $R({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function GR({top:e=0,left:t=0,width:r=0,height:i=0}={}){return{bounds:$R({width:r,height:i}),origin:UR({top:e,left:t})}}function qR({top:e=0,left:t=0,bottom:r=0,right:i=0}={}){return{top:e,left:t,bottom:r,right:i}}function HR(e){return!!e&&!(e.width<=0||e.height<=0)}function WR(e,t){const{width:r,height:i}=t,n=i,s=n*e,o=Math.min(r/s,i/n);return{width:s*o,height:n*o}}const KR=({vertical:e,width:t,height:r,count:i,aspectRatio:n})=>{const s=[1,2,3].map(s=>(({width:e,height:t,rows:r,cols:i,aspectRatio:n})=>{const s=WR(n,{width:e/i,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(i/s):s,cols:e?s:Math.ceil(i/s),aspectRatio:n})),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}};function JR({count:e,width:t,height:r,aspectRatio:i}){if(e<=1)return{rows:1,cols:1};const{splits:n,vertical:s}=(({width:e,height:t,count:r,aspectRatio:i})=>{const n=KR({vertical:!0,width:e,height:t,count:r,aspectRatio:i}),s=KR({vertical:!1,width:e,height:t,count:r,aspectRatio:i});return n.weight>s.weight?{splits:n.splits,vertical:!0}:{splits:s.splits,vertical:!1}})({width:t,height:r,count:e,aspectRatio:i});return s?{rows:Math.ceil(e/n),cols:n}:{rows:n,cols:Math.ceil(e/n)}}function QR(e){var{aspectRatio:t,children:r,className:i,height:n,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=MR(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=n,h=0,f=0;t&&(({width:u,height:p}=WR(t,{width:a,height:n})),h=(a-u)/2,f=(n-p)/2);const m=Object.assign({width:`${Math.round(u)}px`,height:`${Math.round(p)}px`},h||f?{transform:`translate3d(${Math.round(h)}px, ${Math.round(f)}px, 0)`}:{});return s.createElement("div",{className:i,style:Object.assign({position:"absolute",top:0,left:0},o)},s.createElement("div",Object.assign({style:m},l),s.cloneElement(r,{contentWidth:u,contentHeight:p,withRoundedCorners:c,withShadow:d})))}function YR({origin:e,bounds:t}){return{top:Math.round(e.top),left:Math.round(e.left),height:Math.round(t.height),width:Math.round(t.width)}}function XR({cell:e,child:t,clientId:r,style:i={},withRoundedCorners:n=!1,withShadow:o=!1}){const a=!HR(e.bounds);return s.createElement(QR,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:i,withRoundedCorners:n,withShadow:o,key:r},t)}function ZR({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:i,gridContent:n=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=GR(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return n.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.videoGrid)||void 0===o?void 0:o.cells)||[],c=e.map((e,o)=>{var c,d;if(!r.videoGrid)return null;const l=a[o],u={top:r.videoGrid.origin.top+r.videoGrid.paddings.top+l.origin.top,left:r.videoGrid.origin.left+r.videoGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return XR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`video-${o}`}),clientId:h||`video-${o}`,withRoundedCorners:i,style:p,withShadow:n})});return c}({content:n,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.presentationGrid)||void 0===o?void 0:o.cells)||[];return e.map((e,o)=>{var c,d;if(!r.presentationGrid)return null;const l=a[o],u={top:r.presentationGrid.origin.top+r.presentationGrid.paddings.top+l.origin.top,left:r.presentationGrid.origin.left+r.presentationGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return XR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`presentation-${o}`}),clientId:h||`presentation-${o}`,style:p,withRoundedCorners:i,withShadow:n})})}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),i&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:i}){var n;if(!r.floatingContent)return null;const o=r.floatingContent,a=o.origin.top,c=o.origin.left,d={width:Math.round(o.bounds.width),height:Math.round(o.bounds.height),transform:`translate3d(${Math.round(t.origin.left+c)}px, ${Math.round(t.origin.top+a)}px, 0)`,position:"fixed",top:o.bounds.height/2,left:0,zIndex:40},l=(null===(n=e.props.client)||void 0===n?void 0:n.id)||"floating";return XR({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:i,withShadow:!1})}({content:i,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:i}){const n=t.subgrid.cells;return e.map((e,o)=>{var a,c,d,l;const u=n[o],p={height:Math.round(u.bounds.height),width:Math.round(u.bounds.width),transform:""},h={top:t.subgrid.origin.top+u.origin.top,left:t.subgrid.origin.left+u.origin.left};p.transform=`translate3d(${Math.round(h.left)}px, ${Math.round(h.top)}px, 0)`;const f=null===(c=null===(a=null==e?void 0:e.props)||void 0===a?void 0:a.participant)||void 0===c?void 0:c.id,m=(null===(d=u.paddings)||void 0===d?void 0:d.left)||0,g=(null===(l=u.paddings)||void 0===l?void 0:l.right)||0;return XR({cell:u,child:s.cloneElement(e,{avatarSize:u.bounds.width-m-g,canZoom:!1,cellPaddings:u.paddings,isSmallCell:u.isSmallCell,isZoomedByDefault:!1,key:f||`subgrid-${o}`,style:p}),clientId:f||`subgrid-${o}`,style:p,withRoundedCorners:r,withShadow:i})})}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},HR(a.bounds)&&s.createElement("div",{style:YR(a)}),p,t&&s.createElement(s.Fragment,null))}const ek=16/9,tk=4/3,rk=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function ik({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let i=null;if(t===r)i=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(n=e).sort((e,t)=>n.filter(t=>t===e).length-n.filter(e=>e===t).length).pop():r;i=rk({value:t||r,min:tk,max:ek})}var n;return{minAr:t,maxAr:r,chosenAr:i}}const nk="rows",sk="columns";function ok({layoutGrid:e,dim:t,secDim:r,index:i,count:n,gridGap:s}){const o=(t-s*(n-1))*(e.fractions?e.fractions[i]:1/n),a=e.lines[i];return[o,(r-s*(a-1))/a]}function ak({isHorizontal:e,layoutGrid:t,width:r,height:i,gridGap:n}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?i:r,u=e?r:i;for(let r=0;r<d;r++){const i=ok({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:n}),p={width:e?i[1]:i[0],height:e?i[0]:i[1]},h=t.lines[r];for(let t=0;t<h;t++)s.push({origin:Object.assign({},c),bounds:p}),e?c.x+=p.width+n:c.y+=p.height+n;e?(c.y+=p.height+n,c.x=o):(c.x+=p.width+n,c.y=a)}return s}function ck({layoutGrid:e,width:t,height:r,gridGap:i}){switch(e.type){case nk:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return ak({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i});case sk:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return ak({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i})}}function dk({width:e,height:t,cellCount:r,gridGap:i=0,paddings:n=qR()}){const s=e-(n.left+n.right),o=t-(n.top+n.bottom),a=Math.round(s/o*10)/10<=1?function(e){return{1:{type:nk,lines:[1]},2:{type:nk,lines:[1,1]},3:{type:nk,lines:[2,1]},4:{type:nk,lines:[2,2]},5:{type:nk,lines:[2,2,1]},6:{type:nk,lines:[2,2,2]},7:{type:nk,lines:[3,2,2]},8:{type:nk,lines:[2,2,2,2]},9:{type:nk,lines:[3,2,2,2]},10:{type:nk,lines:[3,3,2,2]},11:{type:nk,lines:[3,3,3,2]},12:{type:nk,lines:[3,3,3,3]},13:{type:nk,lines:[2,2,3,3,3]},14:{type:nk,lines:[2,3,3,3,3]},15:{type:nk,lines:[3,3,3,3,3]},16:{type:nk,lines:[2,2,3,3,3,3]},17:{type:nk,lines:[2,3,3,3,3,3]},18:{type:nk,lines:[3,3,3,3,3,3]},19:{type:nk,lines:[2,2,3,3,3,3,3]},20:{type:nk,lines:[2,3,3,3,3,3,3]},21:{type:nk,lines:[3,3,3,3,3,3,3]},22:{type:nk,lines:[2,2,3,3,3,3,3,3]},23:{type:nk,lines:[2,3,3,3,3,3,3,3]},24:{type:nk,lines:[3,3,3,3,3,3,3,3]}}[e]||{type:nk,lines:[3,3,3,3,3,3,3,3]}}(r):function(e){return{1:{type:sk,lines:[1]},2:{type:sk,lines:[1,1]},3:{type:sk,lines:[2,1]},4:{type:sk,lines:[2,2]},5:{type:nk,lines:[3,2],fractions:[.45,.55]},6:{type:sk,lines:[2,2,2]},7:{type:nk,lines:[4,3],fractions:[.45,.55]},8:{type:sk,lines:[2,2,2,2]},9:{type:sk,lines:[3,2,2,2]},10:{type:sk,lines:[3,3,2,2]},11:{type:sk,lines:[3,3,3,2]},12:{type:sk,lines:[3,3,3,3]},13:{type:sk,lines:[4,3,3,3]},14:{type:sk,lines:[4,4,3,3]},15:{type:sk,lines:[3,3,3,3,3]},16:{type:sk,lines:[4,3,3,3,3]},17:{type:sk,lines:[4,4,3,3,3]},18:{type:sk,lines:[4,4,4,3,3]},19:{type:sk,lines:[4,4,4,4,3]},20:{type:sk,lines:[4,4,4,4,4]},21:{type:sk,lines:[5,4,4,4,4]},22:{type:sk,lines:[5,5,4,4,4]},23:{type:sk,lines:[5,5,5,4,4]},24:{type:sk,lines:[5,5,5,5,4]}}[e]||{type:sk,lines:[5,5,5,5,5]}}(r);return{cellRects:ck({layoutGrid:a,width:s,height:o,gridGap:i})||[],cellCount:r,gridGap:i,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:n}}function lk({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:i,paddings:n=qR()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-n.left-n.right,p=e.height-n.top-n.bottom;return r&&(t?(c=Math.floor(u/i.width),a=Math.ceil(r/c),s=u,o=a*i.height,d=(u-c*i.width)/2):(a=Math.floor(p/i.height),c=Math.ceil(r/a),s=c*i.width,o=p,l=(p-a*i.height)/2)),{isPortrait:t,width:s+n.left+n.right,height:o+n.top+n.bottom,cellBounds:i,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:n}}const{BOTTOM_TOOLBAR_HEIGHT:uk,VIDEO_CONTROLS_MIN_WIDTH:pk,TABLET_BREAKPOINT:hk,SUBGRID_EMPTY_STAGE_MAX_WIDTH:fk}=VR,mk=qR({top:4,bottom:28,left:8,right:8});function gk({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function vk({cellCount:e}){const t=e<=6;return $R({width:t?250:300,height:t?150:200})}function bk({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){let o;for(let a=0;a<i.length;a++){const c=i[a];if(o=lk({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:$R({width:c+n.left+n.right,height:c+n.top+n.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}),a=o.cellBounds.width-n.left-n.right===i[i.length-1],c=$R({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=$R({width:o.width,height:o.height});return 0===r?{bounds:c,contentBounds:d,videoCells:[]}:{bounds:c,contentBounds:d,videoCells:[...Array(r)].map((e,t)=>{const{top:r,left:i,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:i,cols:n,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/n):Math.floor(e%i),u=r?Math.floor(e%n):Math.floor(e/i),p=function({index:e,isPortrait:t,rows:r,cols:i,cellBounds:n,cellCount:s}){const o=r*i,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?i:r)-a)+1||e>c?0:a*(t?n.width:n.height)/2}({index:e,isPortrait:r,rows:i,cols:n,cellBounds:o,cellCount:s});return{top:d.top+c+l*o.height+(r?0:p),left:d.left+a+u*o.width+(r?p:0),width:o.width,height:o.height}}({index:t,layout:o});return{origin:UR({top:r,left:i}),bounds:$R({width:s,height:c}),paddings:n,isSmallCell:a}})}}function yk({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:i,gridGap:n,hasConstrainedOverflow:s,hasPresentationContent:o,hasVideoContent:a,isConstrained:c,isMaximizeMode:d,isPortrait:l,isSmallScreen:u,maxGridWidth:p,shouldOverflowSubgrid:h,subgridVideos:f}){const{width:m,height:g}=r,v=o||a,b=f.length>0;if(!b&&!v)return{isPortrait:l,videosContainer:GR(),subgrid:Object.assign(Object.assign({},GR()),{contentBounds:$R(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:GR(Object.assign(Object.assign({},r),i)),subgrid:Object.assign(Object.assign({},GR()),{contentBounds:$R(),cells:[]}),hasOverflow:s};const y=h?20:0;let w=null;if(v)if(h){const i=t[0];let n=d?uk:uk+e.top+(c||u?i/2:i)+e.bottom;r.height-n<200&&(n=0),w=$R({width:r.width,height:n})}else w=$R(d?{width:r.width,height:t[0]+e.top+e.bottom}:l?{width:r.width,height:r.height/2}:{width:r.width/2,height:r.height});else w=$R({width:Math.min(fk,r.width),height:r.height});let _=0;w.width>p&&(_=(w.width-p)/2);const S=bk({containerBounds:w,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:qR({top:y,left:_,right:_})}),C=$R({width:S.contentBounds.width-w.width,height:S.contentBounds.height-w.height}),R=C.width>0||C.height>0;let k,T=null;T=!v||h||R?S.contentBounds:S.bounds;let P=T;v?(P=$R(h?{width:0,height:w.height+y+n}:l?{width:0,height:S.bounds.height+n}:{width:S.bounds.width+n,height:0}),k=function({bounds:e,fromBounds:t}){return{width:Math.max(t.width-e.width,0),height:Math.max(t.height-e.height,0)}}({bounds:P,fromBounds:r})):k=$R();const O=Object.assign({},i);let E;return E=UR(v?{top:l?Math.max(i.top+g-P.height+n,0):i.top,left:l?i.left:Math.max(i.left+m-T.width,0)}:{top:i.top+Math.max(0,(g-T.height)/2),left:i.left+Math.max(0,(m-T.width)/2)}),{isPortrait:l,videosContainer:GR(Object.assign(Object.assign({},k),O)),subgrid:Object.assign(Object.assign({},GR(Object.assign(Object.assign({},T),E))),{cells:S.videoCells.map((e,t)=>{var r,i;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(i=f[t])||void 0===i?void 0:i.clientId},e)}),contentBounds:S.contentBounds}),hasOverflow:R||h||s,overflowNeedBounds:h?$R():C}}function wk({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:i,hasPresentationContent:n,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=$R(),p=UR(),h=o?Object.assign({},e):$R(),f=o?Object.assign({},t):UR();if(n){const n=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:i}){const{width:n,height:s}=e;if(!(r.width>0))return{isPortrait:n<=s,supersizedContentBounds:e};const o=Math.round(n/2),a=Math.round(s/2),c=Math.max(n-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;{const e=WR(t,{width:c,height:s}),r=WR(t,{width:n,height:d});if(l=t<=1?r.height>e.height:r.width>e.width,l){const e=d-Math.max(r.height,a);p=Math.max(e,0)}else{const t=c-Math.max(e.width,o);u=Math.max(t,0)}}return{isPortrait:l,supersizedContentBounds:{width:l?n:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:i,minGridContainerBounds:$R({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=n.isPortrait,u=n.supersizedContentBounds,p=Object.assign({},t),o&&(h=$R({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=UR({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},GR(Object.assign(Object.assign({},u),p))),videoGrid:GR(Object.assign(Object.assign({},h),f))}}function _k({containerBounds:e,paddings:t=qR(),videos:r,isConstrained:i,maxGridWidth:n,gridGap:s}){const{width:o,height:a}=e,c=n?Math.min(o,n):o,d=r.length;let l=null,u=null;if(i){const e=dk({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),i=d>4;u=r.map((t,r)=>{const n=function({index:e,layout:t}){const{cellRects:r}=t,i=r[e]||GR();return{top:i.origin.y,left:i.origin.x,width:i.bounds.width,height:i.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:UR({top:n.top,left:n.left}),bounds:$R({width:n.width,height:n.height}),aspectRatio:n.width/n.height,isSmallCell:i,type:"video"}}),l=e}else{const e=r.map(e=>e.aspectRatio||1),n=vk({cellCount:d}),o=function({width:e,height:t,cellCount:r,gridGap:i,cellAspectRatios:n=[tk],paddings:s=qR()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:i,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=ik({choices:n});let d=c.chosenAr;const{rows:l,cols:u}=JR({count:r,width:o,height:a,aspectRatio:d});1===l?d=rk({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=rk({value:o/(a/l),min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}));const{cellWidth:p,cellHeight:h,extraHorizontalPadding:f,extraVerticalPadding:m}=function({width:e,height:t,rows:r,cols:i,gridGap:n,aspectRatio:s}){const o=(e-(i-1)*n)/i,a=(t-(r-1)*n)/r,c=o/a;let d=0,l=0;return s<c?d=o-a*s:s>c&&(l=a-o/s),{cellWidth:o-d,cellHeight:a-l,extraHorizontalPadding:d*i/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:i,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:i,paddings:s}}({width:c,height:a,cellCount:d,gridGap:s,cellAspectRatios:e,paddings:t});u=r.map((e,t)=>{const r=function({index:e,layout:t}){const{cellWidth:r,cellHeight:i,rows:n,cols:s,cellCount:o,gridGap:a}=t,c=Math.floor(e/s),d=Math.floor(e%s),l=function({rows:e,cols:t,cellWidth:r,index:i,cellCount:n,gridGap:s}){const o=e*t,a=o-n;if(!a)return 0;const c=o-a-1;return i>=c-(t-a)+1&&i<=c?a*r/2+s:0}({rows:n,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*i+c*a,left:d*r+d*a+l,width:r,height:i}}({index:t,layout:o}),s=o.cellWidth<n.width,a=i||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:UR({top:r.top,left:r.left}),bounds:$R({width:r.width,height:r.height}),aspectRatio:a,isSmallCell:s,type:"video"}}),l=o}return{videoCells:u,extraHorizontalPadding:o!==c?l.extraHorizontalPadding+(o-c)/2:l.extraHorizontalPadding,extraVerticalPadding:l.extraVerticalPadding,paddings:l.paddings,gridGap:s}}function Sk({a:e,b:t,gridGap:r,isPortrait:i}){const n=i?e.vertical:e.horizontal,s=i?t.vertical:t.horizontal;if(n===s)return{a:0,b:0};const o=n<s?e:t,a=i?o.vertical:o.horizontal,c=(r+(n+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function Ck({gridGap:e,isConstrained:t,presentationVideos:r,videos:i,videosContainerLayout:n,gridLayoutPaddings:s=qR(),presentationGridLayoutPaddings:o=qR(),maxGridWidth:a}){return{gridLayout:_k({containerBounds:n.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:i}),presentationGridLayout:_k({containerBounds:n.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function Rk({floatingVideo:e,frame:t,gridGap:r,isConstrained:i,isMaximizeMode:n=!1,isXLMeetingSize:s=!1,paddings:o=qR(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=mk,subgridVideos:p=[],videoControlsHeight:h=0,videos:f=[],videoGridGap:m}){let g=s&&(!screen||screen.width<=2048);const v=!!a.length,b=a.length>1,y=v&&!b?a[0].aspectRatio:null,w=!!f.length,_=t.bounds.width-o.left-o.right;let S=t.bounds.height-o.top-o.bottom;const C=Math.max(2200,.8*_),R=i&&f.length>12,k=S/4,T=Math.ceil((f.length-12)/3);S=R?S+k*T:S;const P=$R({width:_,height:S}),O=UR({top:o.top,left:o.left}),E=vk({cellCount:f.length}),D=d.width<hk||d.height<hk,x=n||g||!(v||w)||P.width<=P.height,I={cellPaddings:u,containerBounds:P,containerOrigin:O,gridGap:r,hasPresentationContent:v,hasVideoContent:w,isConstrained:i,isMaximizeMode:n,isSmallScreen:D,subgridVideos:p,maxGridWidth:C};let M=yk(Object.assign(Object.assign({},I),{cellSizeOptions:gk({hasOverflow:g,hasStage:v||w}),isPortrait:x,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})),j=!1;if(!g&&l&&!M.hasOverflow){yk(Object.assign(Object.assign({},I),{containerBounds:$R({width:P.width,height:P.height-uk}),cellSizeOptions:gk({hasOverflow:g,hasStage:v||w}),isPortrait:x,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})).hasOverflow&&(j=!0)}(j||M.hasOverflow&&!g)&&(g=!0,M=yk(Object.assign(Object.assign({},I),{cellSizeOptions:gk({hasOverflow:!0,hasStage:v||w}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})));const L=wk({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:w,minGridBounds:E});let{gridLayout:A,presentationGridLayout:N}=Ck({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C});if(M.hasOverflow&&!g){const{vPaddings:e,hPaddings:t}=function({need:e,stageLayout:t,gridLayout:r,presentationGridLayout:i,videosContainerLayout:n}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,i.extraVerticalPadding);s={presentationGrid:Math.min(n.isPortrait?i.extraVerticalPadding:t,e.height),grid:Math.min(n.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,i.extraHorizontalPadding);o={presentationGrid:Math.min(n.isPortrait?t:i.extraHorizontalPadding,e.width),grid:Math.min(n.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||$R(),stageLayout:M,gridLayout:A,presentationGridLayout:N,videosContainerLayout:L});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:i}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=i.isPortrait?2*e.presentationGrid+2*e.grid:e.presentationGrid+e.grid;r.videosContainer.bounds.height-=t,r.subgrid.origin.top-=t,r.subgrid.bounds.height+=t,i.presentationGrid.bounds.height-=2*e.presentationGrid,i.videoGrid.bounds.height-=2*e.grid,i.isPortrait&&(i.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=i.isPortrait?t.presentationGrid+t.grid:2*t.presentationGrid+2*t.grid;r.videosContainer.bounds.width-=e,r.subgrid.origin.left-=e,r.subgrid.bounds.width+=e,i.presentationGrid.bounds.width-=2*t.presentationGrid,i.videoGrid.bounds.width-=2*t.grid,i.isPortrait||(i.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:L}),({gridLayout:A,presentationGridLayout:N}=Ck({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C})))}const B=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:i,margin:n=8}){if(!r)return null;const s=WR(r.aspectRatio||0,{width:200,height:200}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+n)<pk;let c=0;o&&a?c=-1*i:o||a||(c=i);const d=UR({top:t.origin.top+(t.bounds.height-s.height-n)+c,left:t.origin.left+(t.bounds.width-s.width-n)});return{clientId:r.clientId,isDraggable:r.isDraggable,origin:d,bounds:s,aspectRatio:r.aspectRatio,isSmallCell:!0}}({roomBounds:d,containerFrame:t,floatingVideo:e||null,videoControlsHeight:h});c&&function({videosContainerLayout:e,gridLayout:t,presentationGridLayout:r,stageLayout:i,gridGap:n,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=i.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const i=Sk({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:n,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=i.a,e.videoGrid.origin.top-=i.b,d.vertical=i.b):(e.presentationGrid.origin.left+=i.a,e.videoGrid.origin.left-=i.b,d.horizontal=i.b)}if(c&&(o||a)&&!s){const s={horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},c={horizontal:t.extraHorizontalPadding+d.horizontal,vertical:t.extraVerticalPadding+d.vertical};let l;const u=o&&a;l=u&&e.isPortrait&&!i.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&i.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=Sk({a:l,b:{horizontal:0,vertical:0},gridGap:n,isPortrait:i.isPortrait});i.isPortrait?i.subgrid.origin.top-=p.b:i.subgrid.origin.left-=p.b}}({videosContainerLayout:L,gridLayout:A,presentationGridLayout:N,stageLayout:M,gridGap:r,shouldOverflowSubgrid:g});let F=o.top+M.videosContainer.bounds.height+M.subgrid.bounds.height+o.bottom;return(v||w)&&(F+=r),{isPortrait:M.isPortrait,hasOverflow:M.hasOverflow,videosContainer:Object.assign(Object.assign({},L),{bounds:$R({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:UR({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:$R({height:g?F:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},L.presentationGrid),{cells:N.videoCells,paddings:qR({top:N.paddings.top+N.extraVerticalPadding,bottom:N.paddings.bottom+N.extraVerticalPadding,left:N.paddings.left+N.extraHorizontalPadding,right:N.paddings.right+N.extraHorizontalPadding})}),videoGrid:Object.assign(Object.assign({},L.videoGrid),{cells:A.videoCells,paddings:qR({top:A.paddings.top+A.extraVerticalPadding,bottom:A.paddings.bottom+A.extraVerticalPadding,left:A.paddings.left+A.extraHorizontalPadding,right:A.paddings.right+A.extraHorizontalPadding})}),subgrid:M.subgrid,floatingContent:Object.assign(Object.assign(Object.assign({},B),e),{origin:(null==B?void 0:B.origin)||UR(),bounds:(null==B?void 0:B.bounds)||$R(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function kk({aspectRatio:e,avatarSize:t,cellPaddings:r,client:i,isDraggable:n=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:i,clientId:(null==i?void 0:i.id)||"",isDraggable:n,isPlaceholder:s,isSubgrid:o,type:"video"}}function Tk({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=12,gridGap:i=8,videoGridGap:n=8,enableSubgrid:o=!0,enableConstrainedGrid:a=!0}={}){const[c,d]=s.useState({width:0,height:0}),[l,u]=s.useState(!1),[p,h]=s.useState({}),[f,m]=s.useState(null),[g,v]=s.useState(null),{clientViewsInGrid:b,clientViewsInPresentationGrid:y,clientViewsInSubgrid:w,floatingClientView:_}=function({activeVideosSubgridTrigger:e=12,stageParticipantLimit:t=12,forceSubgrid:r=!0,enableSubgrid:i=!0,maximizedParticipant:n,floatingParticipant:o,isConstrained:a=!1}={}){const c=LR(SS),d=LR(MS),l=LR(cS),u=s.useMemo(()=>o,[o]),p=s.useMemo(()=>u?c.filter(e=>e.id!==u.id):c,[c,u]),h=s.useMemo(()=>!!i&&(!!r||l>t),[r,l,t,i]),f=s.useMemo(()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:i,maximizedParticipant:n,isPhoneResolution:s}){if(!r)return[];const o=i.length>0,a=(n?e.filter(e=>e.id!==n.id):e).filter(e=>!e.isPresentation&&!i.includes(e)),c=a.filter(e=>!e.isVideoEnabled),d=a.filter(e=>e.isVideoEnabled).length>t,l=a.filter(e=>!c.includes(e)&&e.isAudioEnabled),u=a.filter(e=>!c.includes(e)&&!e.isAudioEnabled);if(c.length&&o)return[...u,...c];if(s&&a.length>24){const e=[...l,...u],t=e.slice(0,24);return t.length<=24?[...e.filter(e=>!t.includes(e)),...c]:[...u,...c]}if(d&&u.length){const e=[...l,...u].slice(0,t);return e.length<=t?[...u.filter(t=>!e.includes(t)),...c]:[...u,...c]}return c}({clientViews:p,activeVideosSubgridTrigger:e,shouldShowSubgrid:h,spotlightedParticipants:d,maximizedParticipant:n,isPhoneResolution:a}),[p,h,e,d,a]),m=s.useMemo(()=>p.filter(e=>!f.includes(e)),[p,f]),g=s.useMemo(()=>n?[n]:d,[d,n]),v=s.useMemo(()=>m.filter(e=>!g.includes(e)),[m,g]);return{floatingClientView:u,clientViewsInGrid:v,clientViewsInPresentationGrid:g,clientViewsInSubgrid:f}}({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo(()=>_?[kk({client:_,aspectRatio:p[_.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[],[_,p]),C=s.useMemo(()=>b.map(e=>kk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[b,p]),R=s.useMemo(()=>y.map(e=>kk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[y,p]),k=s.useMemo(()=>w.map(e=>kk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})),[w,p]),T=s.useMemo(()=>GR(c),[c]);s.useEffect(()=>{a&&u(c.width<500||c.height<500)},[c,a]);const P=s.useMemo(()=>Rk({floatingVideo:S[0],frame:T,gridGap:i,isConstrained:l,roomBounds:T.bounds,videos:C,videoGridGap:n,presentationVideos:R,subgridVideos:k}),[T,S,C,R,k,i,n]);return{containerFrame:T,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:R,cellViewsInSubgrid:k,clientAspectRatios:p,videoStage:P,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}var Pk={exports:{}};const Ok=55296,Ek=127995,Dk=127999,xk=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function Ik(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,i=0;for(;r<e.length;)i+=Mk(r+i,e),Nk(e[r+i])&&i++,Lk(e[r+i])&&i++,Ak(e[r+i])&&i++,Bk(e[r+i])?i++:(t.push(e.substring(r,r+i)),r+=i,i=0);return t}function Mk(e,t){const r=t[e];if(!function(e){return e&&zk(e[0].charCodeAt(0),Ok,56319)}(r)||e===t.length-1)return 1;const i=r+t[e+1];let n=t.substring(e+2,e+5);return jk(i)&&jk(n)||function(e){return zk(Fk(e),Ek,Dk)}(n)?4:2}function jk(e){return zk(Fk(e),127462,127487)}function Lk(e){return"string"==typeof e&&zk(e.charCodeAt(0),65024,65039)}function Ak(e){return"string"==typeof e&&zk(e.charCodeAt(0),8400,8447)}function Nk(e){return"string"==typeof e&&-1!==xk.indexOf(e.charCodeAt(0))}function Bk(e){return"string"==typeof e&&8205===e.charCodeAt(0)}function Fk(e){return(e.charCodeAt(0)-Ok<<10)+(e.charCodeAt(1)-56320)+65536}function zk(e,t,r){return e>=t&&e<=r}Pk.exports=Ik,Pk.exports.substr=function(e,t,r){const i=Ik(e);if(void 0===t)return e;if(t>=i.length)return"";const n=i.length-t;let s=t+(void 0===r?n:r);return s>t+n&&(s=void 0),i.slice(t,s).join("")};var Vk=c(Pk.exports);const Uk=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map(e=>Vk(e)[0]).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,i=t.join("").toUpperCase();return s.createElement("svg",{viewBox:"-60 -60 120 120","aria-hidden":"true",style:{height:"100%",pointerEvents:"none",width:"100%"}},s.createElement("text",{x:0,y:0,textAnchor:"middle",dominantBaseline:"central",fontSize:r},i))};function $k(e){var{avatarUrl:t,className:r,size:i=40,name:n,variant:o="round"}=e,a=MR(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${i}px`,width:`${i}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:n},a),!t&&n?s.createElement(Uk,{name:n}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function Gk({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:i,stream:n,muted:o}){const a=AR({stream:n,muted:o});return s.createElement(s.Fragment,null,s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:i?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement($k,{variant:"square",avatarUrl:e,name:t,size:r?60:80}))),s.createElement("audio",{ref:a,autoPlay:!0,playsInline:!0}))}function qk(e,t,{checkForDefaultPrevented:r=!0}={}){return function(i){if(e?.(i),!1===r||!i.defaultPrevented)return t?.(i)}}function Hk(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function Wk(...e){return t=>{let r=!1;const i=e.map(e=>{const i=Hk(e,t);return r||"function"!=typeof i||(r=!0),i});if(r)return()=>{for(let t=0;t<i.length;t++){const r=i[t];"function"==typeof r?r():Hk(e[t],null)}}}}function Kk(...e){return s.useCallback(Wk(...e),e)}var Jk,Qk={exports:{}},Yk={};Qk.exports=(Jk||(Jk=1,function(){var e,r=t,i=Symbol.for("react.element"),n=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),c=Symbol.for("react.provider"),d=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),p=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),g=Symbol.iterator,v=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];!function(e,t,r){var i=v.ReactDebugCurrentFrame.getStackAddendum();""!==i&&(t+="%s",r=r.concat([i]));var n=r.map(function(e){return String(e)});n.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,n)}("error",e,r)}function y(e){return e.displayName||"Context"}function w(e){if(null==e)return null;if("number"==typeof e.tag&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case s:return"Fragment";case n:return"Portal";case a:return"Profiler";case o:return"StrictMode";case u:return"Suspense";case p:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case d:return y(e)+".Consumer";case c:return y(e._context)+".Provider";case l:return function(e,t,r){var i=e.displayName;if(i)return i;var n=t.displayName||t.name||"";return""!==n?r+"("+n+")":r}(e,e.render,"ForwardRef");case h:var t=e.displayName||null;return null!==t?t:w(e.type)||"Memo";case f:var r=e,i=r._payload,m=r._init;try{return w(m(i))}catch(e){return null}}return null}e=Symbol.for("react.module.reference");var _,S,C,R,k,T,P,O=Object.assign,E=0;function D(){}D.__reactDisabledLog=!0;var x,I=v.ReactCurrentDispatcher;function M(e,t,r){if(void 0===x)try{throw Error()}catch(e){var i=e.stack.trim().match(/\n( *(at )?)/);x=i&&i[1]||""}return"\n"+x+e}var j,L=!1,A="function"==typeof WeakMap?WeakMap:Map;function N(e,t){if(!e||L)return"";var r,i=j.get(e);if(void 0!==i)return i;L=!0;var n,s=Error.prepareStackTrace;Error.prepareStackTrace=void 0,n=I.current,I.current=null,function(){if(0===E){_=console.log,S=console.info,C=console.warn,R=console.error,k=console.group,T=console.groupCollapsed,P=console.groupEnd;var e={configurable:!0,enumerable:!0,value:D,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}E++}();try{if(t){var o=function(){throw Error()};if(Object.defineProperty(o.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(o,[])}catch(e){r=e}Reflect.construct(e,[],o)}else{try{o.call()}catch(e){r=e}e.call(o.prototype)}}else{try{throw Error()}catch(e){r=e}e()}}catch(t){if(t&&r&&"string"==typeof t.stack){for(var a=t.stack.split("\n"),c=r.stack.split("\n"),d=a.length-1,l=c.length-1;d>=1&&l>=0&&a[d]!==c[l];)l--;for(;d>=1&&l>=0;d--,l--)if(a[d]!==c[l]){if(1!==d||1!==l)do{if(d--,--l<0||a[d]!==c[l]){var u="\n"+a[d].replace(" at new "," at ");return e.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",e.displayName)),"function"==typeof e&&j.set(e,u),u}}while(d>=1&&l>=0);break}}}finally{L=!1,I.current=n,function(){if(0===--E){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:O({},e,{value:_}),info:O({},e,{value:S}),warn:O({},e,{value:C}),error:O({},e,{value:R}),group:O({},e,{value:k}),groupCollapsed:O({},e,{value:T}),groupEnd:O({},e,{value:P})})}E<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=s}var p=e?e.displayName||e.name:"",h=p?M(p):"";return"function"==typeof e&&j.set(e,h),h}function B(e,t,r){if(null==e)return"";if("function"==typeof e)return N(e,function(e){var t=e.prototype;return!(!t||!t.isReactComponent)}(e));if("string"==typeof e)return M(e);switch(e){case u:return M("Suspense");case p:return M("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case l:return N(e.render,!1);case h:return B(e.type,t,r);case f:var i=e,n=i._payload,s=i._init;try{return B(s(n),t,r)}catch(e){}}return""}j=new A;var F=Object.prototype.hasOwnProperty,z={},V=v.ReactDebugCurrentFrame;function U(e){if(e){var t=e._owner,r=B(e.type,e._source,t?t.type:null);V.setExtraStackFrame(r)}else V.setExtraStackFrame(null)}var $=Array.isArray;function G(e){return $(e)}function q(e){return""+e}function H(e){if(function(e){try{return q(e),!1}catch(e){return!0}}(e))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),q(e)}var W,K,J=v.ReactCurrentOwner,Q={key:!0,ref:!0,__self:!0,__source:!0};function Y(e,t,r,n,s){var o,a={},c=null,d=null;for(o in void 0!==r&&(H(r),c=""+r),function(e){if(F.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(t)&&(H(t.key),c=""+t.key),function(e){if(F.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}(t)&&(d=t.ref,function(e){"string"==typeof e.ref&&J.current}(t)),t)F.call(t,o)&&!Q.hasOwnProperty(o)&&(a[o]=t[o]);if(e&&e.defaultProps){var l=e.defaultProps;for(o in l)void 0===a[o]&&(a[o]=l[o])}if(c||d){var u="function"==typeof e?e.displayName||e.name||"Unknown":e;c&&function(e,t){var r=function(){W||(W=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(a,u),d&&function(e,t){var r=function(){K||(K=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};r.isReactWarning=!0,Object.defineProperty(e,"ref",{get:r,configurable:!0})}(a,u)}return function(e,t,r,n,s,o,a){var c={$$typeof:i,type:e,key:t,ref:r,props:a,_owner:o,_store:{}};return Object.defineProperty(c._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(c,"_self",{configurable:!1,enumerable:!1,writable:!1,value:n}),Object.defineProperty(c,"_source",{configurable:!1,enumerable:!1,writable:!1,value:s}),Object.freeze&&(Object.freeze(c.props),Object.freeze(c)),c}(e,c,d,s,n,J.current,a)}var X,Z=v.ReactCurrentOwner,ee=v.ReactDebugCurrentFrame;function te(e){if(e){var t=e._owner,r=B(e.type,e._source,t?t.type:null);ee.setExtraStackFrame(r)}else ee.setExtraStackFrame(null)}function re(e){return"object"==typeof e&&null!==e&&e.$$typeof===i}function ie(){if(Z.current){var e=w(Z.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}X=!1;var ne={};function se(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var r=function(e){var t=ie();if(!t){var r="string"==typeof e?e:e.displayName||e.name;r&&(t="\n\nCheck the top-level render call using <"+r+">.")}return t}(t);if(!ne[r]){ne[r]=!0;var i="";e&&e._owner&&e._owner!==Z.current&&(i=" It was passed a child from "+w(e._owner.type)+"."),te(e),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',r,i),te(null)}}}function oe(e,t){if("object"==typeof e)if(G(e))for(var r=0;r<e.length;r++){var i=e[r];re(i)&&se(i,t)}else if(re(e))e._store&&(e._store.validated=!0);else if(e){var n=function(e){if(null===e||"object"!=typeof e)return null;var t=g&&e[g]||e["@@iterator"];return"function"==typeof t?t:null}(e);if("function"==typeof n&&n!==e.entries)for(var s,o=n.call(e);!(s=o.next()).done;)re(s.value)&&se(s.value,t)}}function ae(e){var t,r=e.type;if(null!=r&&"string"!=typeof r){if("function"==typeof r)t=r.propTypes;else{if("object"!=typeof r||r.$$typeof!==l&&r.$$typeof!==h)return;t=r.propTypes}if(t){var i=w(r);!function(e,t,r,i,n){var s=Function.call.bind(F);for(var o in e)if(s(e,o)){var a=void 0;try{if("function"!=typeof e[o]){var c=Error((i||"React class")+": "+r+" type `"+o+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[o]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw c.name="Invariant Violation",c}a=e[o](t,o,i,r,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(e){a=e}!a||a instanceof Error||(U(n),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",i||"React class",r,o,typeof a),U(null)),a instanceof Error&&!(a.message in z)&&(z[a.message]=!0,U(n),b("Failed %s type: %s",r,a.message),U(null))}}(t,e.props,"prop",i,e)}else void 0===r.PropTypes||X||(X=!0,b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",w(r)||"Unknown"));"function"!=typeof r.getDefaultProps||r.getDefaultProps.isReactClassApproved||b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ce(t,r,n,g,v,y){var _=function(t){return"string"==typeof t||"function"==typeof t||t===s||t===a||t===o||t===u||t===p||t===m||"object"==typeof t&&null!==t&&(t.$$typeof===f||t.$$typeof===h||t.$$typeof===c||t.$$typeof===d||t.$$typeof===l||t.$$typeof===e||void 0!==t.getModuleId)}(t);if(!_){var S,C="";(void 0===t||"object"==typeof t&&null!==t&&0===Object.keys(t).length)&&(C+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),C+=ie(),null===t?S="null":G(t)?S="array":void 0!==t&&t.$$typeof===i?(S="<"+(w(t.type)||"Unknown")+" />",C=" Did you accidentally export a JSX literal instead of a component?"):S=typeof t,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",S,C)}var R=Y(t,r,n,v,y);if(null==R)return R;if(_){var k=r.children;if(void 0!==k)if(g)if(G(k)){for(var T=0;T<k.length;T++)oe(k[T],t);Object.freeze&&Object.freeze(k)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else oe(k,t)}return t===s?function(e){for(var t=Object.keys(e.props),r=0;r<t.length;r++){var i=t[r];if("children"!==i&&"key"!==i){te(e),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",i),te(null);break}}null!==e.ref&&(te(e),b("Invalid attribute `ref` supplied to `React.Fragment`."),te(null))}(R):ae(R),R}var de=function(e,t,r){return ce(e,t,r,!1)},le=function(e,t,r){return ce(e,t,r,!0)};Yk.Fragment=s,Yk.jsx=de,Yk.jsxs=le}()),Yk);var Xk=Qk.exports;function Zk(e,t=[]){let r=[];const i=()=>{const t=r.map(e=>s.createContext(e));return function(r){const i=r?.[e]||t;return s.useMemo(()=>({[`__scope${e}`]:{...r,[e]:i}}),[r,i])}};return i.scopeName=e,[function(t,i){const n=s.createContext(i),o=r.length;r=[...r,i];const a=t=>{const{scope:r,children:i,...a}=t,c=r?.[e]?.[o]||n,d=s.useMemo(()=>a,Object.values(a));return Xk.jsx(c.Provider,{value:d,children:i})};return a.displayName=t+"Provider",[a,function(r,a){const c=a?.[e]?.[o]||n,d=s.useContext(c);if(d)return d;if(void 0!==i)return i;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},eT(i,...t)]}function eT(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const i=r.reduce((t,{useScope:r,scopeName:i})=>({...t,...r(e)[`__scope${i}`]}),{});return s.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return r.scopeName=t.scopeName,r}function tT(e){const t=rT(e),r=s.forwardRef((e,r)=>{const{children:i,...n}=e,o=s.Children.toArray(i),a=o.find(nT);if(a){const e=a.props.children,i=o.map(t=>t===a?s.Children.count(e)>1?s.Children.only(null):s.isValidElement(e)?e.props.children:null:t);return Xk.jsx(t,{...n,ref:r,children:s.isValidElement(e)?s.cloneElement(e,void 0,i):null})}return Xk.jsx(t,{...n,ref:r,children:i})});return r.displayName=`${e}.Slot`,r}function rT(e){const t=s.forwardRef((e,t)=>{const{children:r,...i}=e;if(s.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),n=function(e,t){const r={...t};for(const i in t){const n=e[i],s=t[i];/^on[A-Z]/.test(i)?n&&s?r[i]=(...e)=>{const t=s(...e);return n(...e),t}:n&&(r[i]=n):"style"===i?r[i]={...n,...s}:"className"===i&&(r[i]=[n,s].filter(Boolean).join(" "))}return{...e,...r}}(i,r.props);return r.type!==s.Fragment&&(n.ref=t?Wk(t,e):e),s.cloneElement(r,n)}return s.Children.count(r)>1?s.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var iT=Symbol("radix.slottable");function nT(e){return s.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===iT}var sT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=tT(`Primitive.${t}`),i=s.forwardRef((e,i)=>{const{asChild:n,...s}=e,o=n?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Xk.jsx(o,{...s,ref:i})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{});function oT(e){const t=s.useRef(e);return s.useEffect(()=>{t.current=e}),s.useMemo(()=>(...e)=>t.current?.(...e),[])}var aT,cT="dismissableLayer.update",dT="dismissableLayer.pointerDownOutside",lT="dismissableLayer.focusOutside",uT=s.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),pT=s.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:i,onPointerDownOutside:n,onFocusOutside:o,onInteractOutside:a,onDismiss:c,...d}=e,l=s.useContext(uT),[u,p]=s.useState(null),h=u?.ownerDocument??globalThis?.document,[,f]=s.useState({}),m=Kk(t,e=>p(e)),g=Array.from(l.layers),[v]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=g.indexOf(v),y=u?g.indexOf(u):-1,w=l.layersWithOutsidePointerEventsDisabled.size>0,_=y>=b,S=function(e,t=globalThis?.document){const r=oT(e),i=s.useRef(!1),n=s.useRef(()=>{});return s.useEffect(()=>{const e=e=>{if(e.target&&!i.current){let i=function(){fT(dT,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",n.current),n.current=i,t.addEventListener("click",n.current,{once:!0})):i()}else t.removeEventListener("click",n.current);i.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",n.current)}},[t,r]),{onPointerDownCapture:()=>i.current=!0}}(e=>{const t=e.target,r=[...l.branches].some(e=>e.contains(t));_&&!r&&(n?.(e),a?.(e),e.defaultPrevented||c?.())},h),C=function(e,t=globalThis?.document){const r=oT(e),i=s.useRef(!1);return s.useEffect(()=>{const e=e=>{if(e.target&&!i.current){fT(lT,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}(e=>{const t=e.target;[...l.branches].some(e=>e.contains(t))||(o?.(e),a?.(e),e.defaultPrevented||c?.())},h);return function(e,t=globalThis?.document){const r=oT(e);s.useEffect(()=>{const e=e=>{"Escape"===e.key&&r(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[r,t])}(e=>{y===l.layers.size-1&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))},h),s.useEffect(()=>{if(u)return r&&(0===l.layersWithOutsidePointerEventsDisabled.size&&(aT=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(u)),l.layers.add(u),hT(),()=>{r&&1===l.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=aT)}},[u,h,r,l]),s.useEffect(()=>()=>{u&&(l.layers.delete(u),l.layersWithOutsidePointerEventsDisabled.delete(u),hT())},[u,l]),s.useEffect(()=>{const e=()=>f({});return document.addEventListener(cT,e),()=>document.removeEventListener(cT,e)},[]),Xk.jsx(sT.div,{...d,ref:m,style:{pointerEvents:w?_?"auto":"none":void 0,...e.style},onFocusCapture:qk(e.onFocusCapture,C.onFocusCapture),onBlurCapture:qk(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:qk(e.onPointerDownCapture,S.onPointerDownCapture)})});pT.displayName="DismissableLayer";function hT(){const e=new CustomEvent(cT);document.dispatchEvent(e)}function fT(e,t,r,{discrete:i}){const n=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&n.addEventListener(e,t,{once:!0}),i?function(e,t){e&&o.flushSync(()=>e.dispatchEvent(t))}(n,s):n.dispatchEvent(s)}s.forwardRef((e,t)=>{const r=s.useContext(uT),i=s.useRef(null),n=Kk(t,i);return s.useEffect(()=>{const e=i.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),Xk.jsx(sT.div,{...e,ref:n})}).displayName="DismissableLayerBranch";var mT=0;function gT(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var vT="focusScope.autoFocusOnMount",bT="focusScope.autoFocusOnUnmount",yT={bubbles:!1,cancelable:!0},wT=s.forwardRef((e,t)=>{const{loop:r=!1,trapped:i=!1,onMountAutoFocus:n,onUnmountAutoFocus:o,...a}=e,[c,d]=s.useState(null),l=oT(n),u=oT(o),p=s.useRef(null),h=Kk(t,e=>d(e)),f=s.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;s.useEffect(()=>{if(i){let e=function(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:RT(p.current,{select:!0})},t=function(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||RT(p.current,{select:!0}))},r=function(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&RT(c)};document.addEventListener("focusin",e),document.addEventListener("focusout",t);const i=new MutationObserver(r);return c&&i.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),i.disconnect()}}},[i,c,f.paused]),s.useEffect(()=>{if(c){kT.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(vT,yT);c.addEventListener(vT,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const i of e)if(RT(i,{select:t}),document.activeElement!==r)return}((e=_T(c),e.filter(e=>"A"!==e.tagName)),{select:!0}),document.activeElement===t&&RT(c))}return()=>{c.removeEventListener(vT,l),setTimeout(()=>{const e=new CustomEvent(bT,yT);c.addEventListener(bT,u),c.dispatchEvent(e),e.defaultPrevented||RT(t??document.body,{select:!0}),c.removeEventListener(bT,u),kT.remove(f)},0)}}var e},[c,l,u,f]);const m=s.useCallback(e=>{if(!r&&!i)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,n=document.activeElement;if(t&&n){const t=e.currentTarget,[i,s]=function(e){const t=_T(e),r=ST(t,e),i=ST(t.reverse(),e);return[r,i]}(t);i&&s?e.shiftKey||n!==s?e.shiftKey&&n===i&&(e.preventDefault(),r&&RT(s,{select:!0})):(e.preventDefault(),r&&RT(i,{select:!0})):n===t&&e.preventDefault()}},[r,i,f.paused]);return Xk.jsx(sT.div,{tabIndex:-1,...a,ref:h,onKeyDown:m})});function _T(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function ST(e,t){for(const r of e)if(!CT(r,{upTo:t}))return r}function CT(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function RT(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}wT.displayName="FocusScope";var kT=function(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=TT(e,t),e.unshift(t)},remove(t){e=TT(e,t),e[0]?.resume()}}}();function TT(e,t){const r=[...e],i=r.indexOf(t);return-1!==i&&r.splice(i,1),r}var PT=globalThis?.document?s.useLayoutEffect:()=>{},OT=s[" useId ".trim().toString()]||(()=>{}),ET=0;function DT(e){const[t,r]=s.useState(OT());return PT(()=>{r(e=>e??String(ET++))},[e]),e||(t?`radix-${t}`:"")}const xT=["top","right","bottom","left"],IT=Math.min,MT=Math.max,jT=Math.round,LT=Math.floor,AT=e=>({x:e,y:e}),NT={left:"right",right:"left",bottom:"top",top:"bottom"},BT={start:"end",end:"start"};function FT(e,t,r){return MT(e,IT(t,r))}function zT(e,t){return"function"==typeof e?e(t):e}function VT(e){return e.split("-")[0]}function UT(e){return e.split("-")[1]}function $T(e){return"x"===e?"y":"x"}function GT(e){return"y"===e?"height":"width"}const qT=new Set(["top","bottom"]);function HT(e){return qT.has(VT(e))?"y":"x"}function WT(e){return $T(HT(e))}function KT(e){return e.replace(/start|end/g,e=>BT[e])}const JT=["left","right"],QT=["right","left"],YT=["top","bottom"],XT=["bottom","top"];function ZT(e,t,r,i){const n=UT(e);let s=function(e,t,r){switch(e){case"top":case"bottom":return r?t?QT:JT:t?JT:QT;case"left":case"right":return t?YT:XT;default:return[]}}(VT(e),"start"===r,i);return n&&(s=s.map(e=>e+"-"+n),t&&(s=s.concat(s.map(KT)))),s}function eP(e){return e.replace(/left|right|bottom|top/g,e=>NT[e])}function tP(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function rP(e){const{x:t,y:r,width:i,height:n}=e;return{width:i,height:n,top:r,left:t,right:t+i,bottom:r+n,x:t,y:r}}function iP(e,t,r){let{reference:i,floating:n}=e;const s=HT(t),o=WT(t),a=GT(o),c=VT(t),d="y"===s,l=i.x+i.width/2-n.width/2,u=i.y+i.height/2-n.height/2,p=i[a]/2-n[a]/2;let h;switch(c){case"top":h={x:l,y:i.y-n.height};break;case"bottom":h={x:l,y:i.y+i.height};break;case"right":h={x:i.x+i.width,y:u};break;case"left":h={x:i.x-n.width,y:u};break;default:h={x:i.x,y:i.y}}switch(UT(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function nP(e,t){var r;void 0===t&&(t={});const{x:i,y:n,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=zT(t,e),f=tP(h),m=a[p?"floating"===u?"reference":"floating":u],g=rP(await s.getClippingRect({element:null==(r=await(null==s.isElement?void 0:s.isElement(m)))||r?m:m.contextElement||await(null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:d,rootBoundary:l,strategy:c})),v="floating"===u?{x:i,y:n,width:o.floating.width,height:o.floating.height}:o.reference,b=await(null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),y=await(null==s.isElement?void 0:s.isElement(b))&&await(null==s.getScale?void 0:s.getScale(b))||{x:1,y:1},w=rP(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:c}):v);return{top:(g.top-w.top+f.top)/y.y,bottom:(w.bottom-g.bottom+f.bottom)/y.y,left:(g.left-w.left+f.left)/y.x,right:(w.right-g.right+f.right)/y.x}}function sP(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function oP(e){return xT.some(t=>e[t]>=0)}const aP=new Set(["left","top"]);function cP(){return"undefined"!=typeof window}function dP(e){return pP(e)?(e.nodeName||"").toLowerCase():"#document"}function lP(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function uP(e){var t;return null==(t=(pP(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function pP(e){return!!cP()&&(e instanceof Node||e instanceof lP(e).Node)}function hP(e){return!!cP()&&(e instanceof Element||e instanceof lP(e).Element)}function fP(e){return!!cP()&&(e instanceof HTMLElement||e instanceof lP(e).HTMLElement)}function mP(e){return!(!cP()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof lP(e).ShadowRoot)}const gP=new Set(["inline","contents"]);function vP(e){const{overflow:t,overflowX:r,overflowY:i,display:n}=EP(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+r)&&!gP.has(n)}const bP=new Set(["table","td","th"]);function yP(e){return bP.has(dP(e))}const wP=[":popover-open",":modal"];function _P(e){return wP.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const SP=["transform","translate","scale","rotate","perspective"],CP=["transform","translate","scale","rotate","perspective","filter"],RP=["paint","layout","strict","content"];function kP(e){const t=TP(),r=hP(e)?EP(e):e;return SP.some(e=>!!r[e]&&"none"!==r[e])||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||CP.some(e=>(r.willChange||"").includes(e))||RP.some(e=>(r.contain||"").includes(e))}function TP(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const PP=new Set(["html","body","#document"]);function OP(e){return PP.has(dP(e))}function EP(e){return lP(e).getComputedStyle(e)}function DP(e){return hP(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function xP(e){if("html"===dP(e))return e;const t=e.assignedSlot||e.parentNode||mP(e)&&e.host||uP(e);return mP(t)?t.host:t}function IP(e){const t=xP(e);return OP(t)?e.ownerDocument?e.ownerDocument.body:e.body:fP(t)&&vP(t)?t:IP(t)}function MP(e,t,r){var i;void 0===t&&(t=[]),void 0===r&&(r=!0);const n=IP(e),s=n===(null==(i=e.ownerDocument)?void 0:i.body),o=lP(n);if(s){const e=jP(o);return t.concat(o,o.visualViewport||[],vP(n)?n:[],e&&r?MP(e):[])}return t.concat(n,MP(n,[],r))}function jP(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function LP(e){const t=EP(e);let r=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const n=fP(e),s=n?e.offsetWidth:r,o=n?e.offsetHeight:i,a=jT(r)!==s||jT(i)!==o;return a&&(r=s,i=o),{width:r,height:i,$:a}}function AP(e){return hP(e)?e:e.contextElement}function NP(e){const t=AP(e);if(!fP(t))return AT(1);const r=t.getBoundingClientRect(),{width:i,height:n,$:s}=LP(t);let o=(s?jT(r.width):r.width)/i,a=(s?jT(r.height):r.height)/n;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const BP=AT(0);function FP(e){const t=lP(e);return TP()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:BP}function zP(e,t,r,i){void 0===t&&(t=!1),void 0===r&&(r=!1);const n=e.getBoundingClientRect(),s=AP(e);let o=AT(1);t&&(i?hP(i)&&(o=NP(i)):o=NP(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==lP(e))&&t}(s,r,i)?FP(s):AT(0);let c=(n.left+a.x)/o.x,d=(n.top+a.y)/o.y,l=n.width/o.x,u=n.height/o.y;if(s){const e=lP(s),t=i&&hP(i)?lP(i):i;let r=e,n=jP(r);for(;n&&i&&t!==r;){const e=NP(n),t=n.getBoundingClientRect(),i=EP(n),s=t.left+(n.clientLeft+parseFloat(i.paddingLeft))*e.x,o=t.top+(n.clientTop+parseFloat(i.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=lP(n),n=jP(r)}}return rP({width:l,height:u,x:c,y:d})}function VP(e,t){const r=DP(e).scrollLeft;return t?t.left+r:zP(uP(e)).left+r}function UP(e,t,r){void 0===r&&(r=!1);const i=e.getBoundingClientRect();return{x:i.left+t.scrollLeft-(r?0:VP(e,i)),y:i.top+t.scrollTop}}const $P=new Set(["absolute","fixed"]);function GP(e,t,r){let i;if("viewport"===t)i=function(e,t){const r=lP(e),i=uP(e),n=r.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(n){s=n.width,o=n.height;const e=TP();(!e||e&&"fixed"===t)&&(a=n.offsetLeft,c=n.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)i=function(e){const t=uP(e),r=DP(e),i=e.ownerDocument.body,n=MT(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),s=MT(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let o=-r.scrollLeft+VP(e);const a=-r.scrollTop;return"rtl"===EP(i).direction&&(o+=MT(t.clientWidth,i.clientWidth)-n),{width:n,height:s,x:o,y:a}}(uP(e));else if(hP(t))i=function(e,t){const r=zP(e,!0,"fixed"===t),i=r.top+e.clientTop,n=r.left+e.clientLeft,s=fP(e)?NP(e):AT(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:n*s.x,y:i*s.y}}(t,r);else{const r=FP(e);i={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return rP(i)}function qP(e,t){const r=xP(e);return!(r===t||!hP(r)||OP(r))&&("fixed"===EP(r).position||qP(r,t))}function HP(e,t,r){const i=fP(t),n=uP(t),s="fixed"===r,o=zP(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=AT(0);function d(){c.x=VP(n)}if(i||!i&&!s)if(("body"!==dP(t)||vP(n))&&(a=DP(t)),i){const e=zP(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else n&&d();s&&!i&&n&&d();const l=!n||i||s?AT(0):UP(n,a);return{x:o.left+a.scrollLeft-c.x-l.x,y:o.top+a.scrollTop-c.y-l.y,width:o.width,height:o.height}}function WP(e){return"static"===EP(e).position}function KP(e,t){if(!fP(e)||"fixed"===EP(e).position)return null;if(t)return t(e);let r=e.offsetParent;return uP(e)===r&&(r=r.ownerDocument.body),r}function JP(e,t){const r=lP(e);if(_P(e))return r;if(!fP(e)){let t=xP(e);for(;t&&!OP(t);){if(hP(t)&&!WP(t))return t;t=xP(t)}return r}let i=KP(e,t);for(;i&&yP(i)&&WP(i);)i=KP(i,t);return i&&OP(i)&&WP(i)&&!kP(i)?r:i||function(e){let t=xP(e);for(;fP(t)&&!OP(t);){if(kP(t))return t;if(_P(t))return null;t=xP(t)}return null}(e)||r}const QP={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:i,strategy:n}=e;const s="fixed"===n,o=uP(i),a=!!t&&_P(t.floating);if(i===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=AT(1);const l=AT(0),u=fP(i);if((u||!u&&!s)&&(("body"!==dP(i)||vP(o))&&(c=DP(i)),fP(i))){const e=zP(i);d=NP(i),l.x=e.x+i.clientLeft,l.y=e.y+i.clientTop}const p=!o||u||s?AT(0):UP(o,c,!0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x+p.x,y:r.y*d.y-c.scrollTop*d.y+l.y+p.y}},getDocumentElement:uP,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:i,strategy:n}=e;const s="clippingAncestors"===r?_P(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let i=MP(e,[],!1).filter(e=>hP(e)&&"body"!==dP(e)),n=null;const s="fixed"===EP(e).position;let o=s?xP(e):e;for(;hP(o)&&!OP(o);){const t=EP(o),r=kP(o);r||"fixed"!==t.position||(n=null),(s?!r&&!n:!r&&"static"===t.position&&n&&$P.has(n.position)||vP(o)&&!r&&qP(e,o))?i=i.filter(e=>e!==o):n=t,o=xP(o)}return t.set(e,i),i}(t,this._c):[].concat(r),o=[...s,i],a=o[0],c=o.reduce((e,r)=>{const i=GP(t,r,n);return e.top=MT(i.top,e.top),e.right=IT(i.right,e.right),e.bottom=IT(i.bottom,e.bottom),e.left=MT(i.left,e.left),e},GP(t,a,n));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:JP,getElementRects:async function(e){const t=this.getOffsetParent||JP,r=this.getDimensions,i=await r(e.floating);return{reference:HP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=LP(e);return{width:t,height:r}},getScale:NP,isElement:hP,isRTL:function(e){return"rtl"===EP(e).direction}};function YP(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function XP(e,t,r,i){void 0===i&&(i={});const{ancestorScroll:n=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=i,d=AP(e),l=n||s?[...d?MP(d):[],...MP(t)]:[];l.forEach(e=>{n&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)});const u=d&&a?function(e,t){let r,i=null;const n=uP(e);function s(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const d=e.getBoundingClientRect(),{left:l,top:u,width:p,height:h}=d;if(a||t(),!p||!h)return;const f={rootMargin:-LT(u)+"px "+-LT(n.clientWidth-(l+p))+"px "+-LT(n.clientHeight-(u+h))+"px "+-LT(l)+"px",threshold:MT(0,IT(1,c))||1};let m=!0;function g(t){const i=t[0].intersectionRatio;if(i!==c){if(!m)return o();i?o(!1,i):r=setTimeout(()=>{o(!1,1e-7)},1e3)}1!==i||YP(d,e.getBoundingClientRect())||o(),m=!1}try{i=new IntersectionObserver(g,{...f,root:n.ownerDocument})}catch(e){i=new IntersectionObserver(g,f)}i.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver(e=>{let[i]=e;i&&i.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),r()}),d&&!c&&f.observe(d),f.observe(t));let m=c?zP(e):null;return c&&function t(){const i=zP(e);m&&!YP(m,i)&&r();m=i,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach(e=>{n&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)}),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const ZP=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,i;const{x:n,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:i,elements:n}=e,s=await(null==i.isRTL?void 0:i.isRTL(n.floating)),o=VT(r),a=UT(r),c="y"===HT(r),d=aP.has(o)?-1:1,l=s&&c?-1:1,u=zT(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*l,y:p*d}:{x:p*d,y:h*l}}(t,e);return o===(null==(r=a.offset)?void 0:r.placement)&&null!=(i=a.arrow)&&i.alignmentOffset?{}:{x:n+c.x,y:s+c.y,data:{...c,placement:o}}}}},eO=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:i,placement:n}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=zT(e,t),d={x:r,y:i},l=await nP(t,c),u=HT(VT(n)),p=$T(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=FT(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=FT(f+l["y"===u?"top":"left"],f,f-l[e])}const m=a.fn({...t,[p]:h,[u]:f});return{...m,data:{x:m.x-r,y:m.y-i,enabled:{[p]:s,[u]:o}}}}}},tO=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,i;const{placement:n,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:d}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=zT(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=VT(n),b=HT(a),y=VT(a)===a,w=await(null==c.isRTL?void 0:c.isRTL(d.floating)),_=p||(y||!m?[eP(a)]:function(e){const t=eP(e);return[KT(e),t,KT(t)]}(a)),S="none"!==f;!p&&S&&_.push(...ZT(a,m,f,w));const C=[a,..._],R=await nP(t,g),k=[];let T=(null==(i=s.flip)?void 0:i.overflows)||[];if(l&&k.push(R[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const i=UT(e),n=WT(e),s=GT(n);let o="x"===n?i===(r?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=eP(o)),[o,eP(o)]}(n,o,w);k.push(R[e[0]],R[e[1]])}if(T=[...T,{placement:n,overflows:k}],!k.every(e=>e<=0)){var P,O;const e=((null==(P=s.flip)?void 0:P.index)||0)+1,t=C[e];if(t){if(!("alignment"===u&&b!==HT(t))||T.every(e=>e.overflows[0]>0&&HT(e.placement)===b))return{data:{index:e,overflows:T},reset:{placement:t}}}let r=null==(O=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:O.placement;if(!r)switch(h){case"bestFit":{var E;const e=null==(E=T.filter(e=>{if(S){const t=HT(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:E[0];e&&(r=e);break}case"initialPlacement":r=a}if(n!==r)return{reset:{placement:r}}}return{}}}},rO=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){var r,i;const{placement:n,rects:s,platform:o,elements:a}=t,{apply:c=()=>{},...d}=zT(e,t),l=await nP(t,d),u=VT(n),p=UT(n),h="y"===HT(n),{width:f,height:m}=s.floating;let g,v;"top"===u||"bottom"===u?(g=u,v=p===(await(null==o.isRTL?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(v=u,g="end"===p?"top":"bottom");const b=m-l.top-l.bottom,y=f-l.left-l.right,w=IT(m-l[g],b),_=IT(f-l[v],y),S=!t.middlewareData.shift;let C=w,R=_;if(null!=(r=t.middlewareData.shift)&&r.enabled.x&&(R=y),null!=(i=t.middlewareData.shift)&&i.enabled.y&&(C=b),S&&!p){const e=MT(l.left,0),t=MT(l.right,0),r=MT(l.top,0),i=MT(l.bottom,0);h?R=f-2*(0!==e||0!==t?e+t:MT(l.left,l.right)):C=m-2*(0!==r||0!==i?r+i:MT(l.top,l.bottom))}await c({...t,availableWidth:R,availableHeight:C});const k=await o.getDimensions(a.floating);return f!==k.width||m!==k.height?{reset:{rects:!0}}:{}}}},iO=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:i="referenceHidden",...n}=zT(e,t);switch(i){case"referenceHidden":{const e=sP(await nP(t,{...n,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:oP(e)}}}case"escaped":{const e=sP(await nP(t,{...n,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:oP(e)}}}default:return{}}}}},nO=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:i,placement:n,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=zT(e,t)||{};if(null==d)return{};const u=tP(l),p={x:r,y:i},h=WT(n),f=GT(h),m=await o.getDimensions(d),g="y"===h,v=g?"top":"left",b=g?"bottom":"right",y=g?"clientHeight":"clientWidth",w=s.reference[f]+s.reference[h]-p[h]-s.floating[f],_=p[h]-s.reference[h],S=await(null==o.getOffsetParent?void 0:o.getOffsetParent(d));let C=S?S[y]:0;C&&await(null==o.isElement?void 0:o.isElement(S))||(C=a.floating[y]||s.floating[f]);const R=w/2-_/2,k=C/2-m[f]/2-1,T=IT(u[v],k),P=IT(u[b],k),O=T,E=C-m[f]-P,D=C/2-m[f]/2+R,x=FT(O,D,E),I=!c.arrow&&null!=UT(n)&&D!==x&&s.reference[f]/2-(D<O?T:P)-m[f]/2<0,M=I?D<O?D-O:D-E:0;return{[h]:p[h]+M,data:{[h]:x,centerOffset:D-x-M,...I&&{alignmentOffset:M}},reset:I}}}),sO=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:i,placement:n,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=zT(e,t),l={x:r,y:i},u=HT(n),p=$T(u);let h=l[p],f=l[u];const m=zT(a,t),g="number"==typeof m?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const e="y"===p?"height":"width",t=s.reference[p]-s.floating[e]+g.mainAxis,r=s.reference[p]+s.reference[e]-g.mainAxis;h<t?h=t:h>r&&(h=r)}if(d){var v,b;const e="y"===p?"width":"height",t=aP.has(VT(n)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),i=s.reference[u]+s.reference[e]+(t?0:(null==(b=o.offset)?void 0:b[u])||0)-(t?g.crossAxis:0);f<r?f=r:f>i&&(f=i)}return{[p]:h,[u]:f}}}},oO=(e,t,r)=>{const i=new Map,n={platform:QP,...r},s={...n.platform,_c:i};return(async(e,t,r)=>{const{placement:i="bottom",strategy:n="absolute",middleware:s=[],platform:o}=r,a=s.filter(Boolean),c=await(null==o.isRTL?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:n}),{x:l,y:u}=iP(d,i,c),p=i,h={},f=0;for(let r=0;r<a.length;r++){const{name:s,fn:m}=a[r],{x:g,y:v,data:b,reset:y}=await m({x:l,y:u,initialPlacement:i,placement:p,strategy:n,middlewareData:h,rects:d,platform:o,elements:{reference:e,floating:t}});l=null!=g?g:l,u=null!=v?v:u,h={...h,[s]:{...h[s],...b}},y&&f<=50&&(f++,"object"==typeof y&&(y.placement&&(p=y.placement),y.rects&&(d=!0===y.rects?await o.getElementRects({reference:e,floating:t,strategy:n}):y.rects),({x:l,y:u}=iP(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:n,middlewareData:h}})(e,t,{...n,platform:s})};var aO="undefined"!=typeof document?t.useLayoutEffect:function(){};function cO(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;let r,i,n;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(i=r;0!==i--;)if(!cO(e[i],t[i]))return!1;return!0}if(n=Object.keys(e),r=n.length,r!==Object.keys(t).length)return!1;for(i=r;0!==i--;)if(!{}.hasOwnProperty.call(t,n[i]))return!1;for(i=r;0!==i--;){const r=n[i];if(("_owner"!==r||!e.$$typeof)&&!cO(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function dO(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function lO(e,t){const r=dO(e);return Math.round(t*r)/r}function uO(e){const t=s.useRef(e);return aO(()=>{t.current=e}),t}const pO=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:i}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?nO({element:r.current,padding:i}).fn(t):{}:r?nO({element:r,padding:i}).fn(t):{}}}),hO=(e,t)=>({...ZP(e),options:[e,t]}),fO=(e,t)=>({...eO(e),options:[e,t]}),mO=(e,t)=>({...sO(e),options:[e,t]}),gO=(e,t)=>({...tO(e),options:[e,t]}),vO=(e,t)=>({...rO(e),options:[e,t]}),bO=(e,t)=>({...iO(e),options:[e,t]}),yO=(e,t)=>({...pO(e),options:[e,t]});var wO=s.forwardRef((e,t)=>{const{children:r,width:i=10,height:n=5,...s}=e;return Xk.jsx(sT.svg,{...s,ref:t,width:i,height:n,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:Xk.jsx("polygon",{points:"0,0 30,0 15,10"})})});wO.displayName="Arrow";var _O=wO;var SO="Popper",[CO,RO]=Zk(SO),[kO,TO]=CO(SO),PO=e=>{const{__scopePopper:t,children:r}=e,[i,n]=s.useState(null);return Xk.jsx(kO,{scope:t,anchor:i,onAnchorChange:n,children:r})};PO.displayName=SO;var OO="PopperAnchor",EO=s.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:i,...n}=e,o=TO(OO,r),a=s.useRef(null),c=Kk(t,a);return s.useEffect(()=>{o.onAnchorChange(i?.current||a.current)}),i?null:Xk.jsx(sT.div,{...n,ref:c})});EO.displayName=OO;var DO="PopperContent",[xO,IO]=CO(DO),MO=s.forwardRef((e,t)=>{const{__scopePopper:r,side:i="bottom",sideOffset:n=0,align:a="center",alignOffset:c=0,arrowPadding:d=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:h="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:g,...v}=e,b=TO(DO,r),[y,w]=s.useState(null),_=Kk(t,e=>w(e)),[S,C]=s.useState(null),R=function(e){const[t,r]=s.useState(void 0);return PT(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver(t=>{if(!Array.isArray(t))return;if(!t.length)return;const i=t[0];let n,s;if("borderBoxSize"in i){const e=i.borderBoxSize,t=Array.isArray(e)?e[0]:e;n=t.inlineSize,s=t.blockSize}else n=e.offsetWidth,s=e.offsetHeight;r({width:n,height:s})});return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}r(void 0)},[e]),t}(S),k=R?.width??0,T=R?.height??0,P=i+("center"!==a?"-"+a:""),O="number"==typeof p?p:{top:0,right:0,bottom:0,left:0,...p},E=Array.isArray(u)?u:[u],D=E.length>0,x={padding:O,boundary:E.filter(NO),altBoundary:D},{refs:I,floatingStyles:M,placement:j,isPositioned:L,middlewareData:A}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:i=[],platform:n,elements:{reference:a,floating:c}={},transform:d=!0,whileElementsMounted:l,open:u}=e,[p,h]=s.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=s.useState(i);cO(f,i)||m(i);const[g,v]=s.useState(null),[b,y]=s.useState(null),w=s.useCallback(e=>{e!==R.current&&(R.current=e,v(e))},[]),_=s.useCallback(e=>{e!==k.current&&(k.current=e,y(e))},[]),S=a||g,C=c||b,R=s.useRef(null),k=s.useRef(null),T=s.useRef(p),P=null!=l,O=uO(l),E=uO(n),D=uO(u),x=s.useCallback(()=>{if(!R.current||!k.current)return;const e={placement:t,strategy:r,middleware:f};E.current&&(e.platform=E.current),oO(R.current,k.current,e).then(e=>{const t={...e,isPositioned:!1!==D.current};I.current&&!cO(T.current,t)&&(T.current=t,o.flushSync(()=>{h(t)}))})},[f,t,r,E,D]);aO(()=>{!1===u&&T.current.isPositioned&&(T.current.isPositioned=!1,h(e=>({...e,isPositioned:!1})))},[u]);const I=s.useRef(!1);aO(()=>(I.current=!0,()=>{I.current=!1}),[]),aO(()=>{if(S&&(R.current=S),C&&(k.current=C),S&&C){if(O.current)return O.current(S,C,x);x()}},[S,C,x,O,P]);const M=s.useMemo(()=>({reference:R,floating:k,setReference:w,setFloating:_}),[w,_]),j=s.useMemo(()=>({reference:S,floating:C}),[S,C]),L=s.useMemo(()=>{const e={position:r,left:0,top:0};if(!j.floating)return e;const t=lO(j.floating,p.x),i=lO(j.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+i+"px)",...dO(j.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:i}},[r,d,j.floating,p.x,p.y]);return s.useMemo(()=>({...p,update:x,refs:M,elements:j,floatingStyles:L}),[p,x,M,j,L])}({strategy:"fixed",placement:P,whileElementsMounted:(...e)=>XP(...e,{animationFrame:"always"===m}),elements:{reference:b.anchor},middleware:[hO({mainAxis:n+T,alignmentAxis:c}),l&&fO({mainAxis:!0,crossAxis:!1,limiter:"partial"===h?mO():void 0,...x}),l&&gO({...x}),vO({...x,apply:({elements:e,rects:t,availableWidth:r,availableHeight:i})=>{const{width:n,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${i}px`),o.setProperty("--radix-popper-anchor-width",`${n}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),S&&yO({element:S,padding:d}),BO({arrowWidth:k,arrowHeight:T}),f&&bO({strategy:"referenceHidden",...x})]}),[N,B]=FO(j),F=oT(g);PT(()=>{L&&F?.()},[L,F]);const z=A.arrow?.x,V=A.arrow?.y,U=0!==A.arrow?.centerOffset,[$,G]=s.useState();return PT(()=>{y&&G(window.getComputedStyle(y).zIndex)},[y]),Xk.jsx("div",{ref:I.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:L?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:$,"--radix-popper-transform-origin":[A.transformOrigin?.x,A.transformOrigin?.y].join(" "),...A.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:Xk.jsx(xO,{scope:r,placedSide:N,onArrowChange:C,arrowX:z,arrowY:V,shouldHideArrow:U,children:Xk.jsx(sT.div,{"data-side":N,"data-align":B,...v,ref:_,style:{...v.style,animation:L?void 0:"none"}})})})});MO.displayName=DO;var jO="PopperArrow",LO={top:"bottom",right:"left",bottom:"top",left:"right"},AO=s.forwardRef(function(e,t){const{__scopePopper:r,...i}=e,n=IO(jO,r),s=LO[n.placedSide];return Xk.jsx("span",{ref:n.onArrowChange,style:{position:"absolute",left:n.arrowX,top:n.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[n.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[n.placedSide],visibility:n.shouldHideArrow?"hidden":void 0},children:Xk.jsx(_O,{...i,ref:t,style:{...i.style,display:"block"}})})});function NO(e){return null!==e}AO.displayName=jO;var BO=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:i,middlewareData:n}=t,s=0!==n.arrow?.centerOffset,o=s?0:e.arrowWidth,a=s?0:e.arrowHeight,[c,d]=FO(r),l={start:"0%",center:"50%",end:"100%"}[d],u=(n.arrow?.x??0)+o/2,p=(n.arrow?.y??0)+a/2;let h="",f="";return"bottom"===c?(h=s?l:`${u}px`,f=-a+"px"):"top"===c?(h=s?l:`${u}px`,f=`${i.floating.height+a}px`):"right"===c?(h=-a+"px",f=s?l:`${p}px`):"left"===c&&(h=`${i.floating.width+a}px`,f=s?l:`${p}px`),{data:{x:h,y:f}}}});function FO(e){const[t,r="center"]=e.split("-");return[t,r]}var zO=PO,VO=EO,UO=MO,$O=AO,GO=s.forwardRef((e,t)=>{const{container:i,...n}=e,[o,a]=s.useState(!1);PT(()=>a(!0),[]);const c=i||o&&globalThis?.document?.body;return c?r.createPortal(Xk.jsx(sT.div,{...n,ref:t}),c):null});GO.displayName="Portal";var qO=e=>{const{present:t,children:r}=e,i=function(e){const[t,r]=s.useState(),i=s.useRef(null),n=s.useRef(e),o=s.useRef("none"),a=e?"mounted":"unmounted",[c,d]=function(e,t){return s.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return s.useEffect(()=>{const e=HO(i.current);o.current="mounted"===c?e:"none"},[c]),PT(()=>{const t=i.current,r=n.current;if(r!==e){const i=o.current,s=HO(t);if(e)d("MOUNT");else if("none"===s||"none"===t?.display)d("UNMOUNT");else{d(r&&i!==s?"ANIMATION_OUT":"UNMOUNT")}n.current=e}},[e,d]),PT(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,s=s=>{const o=HO(i.current).includes(s.animationName);if(s.target===t&&o&&(d("ANIMATION_END"),!n.current)){const i=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=i)})}},a=e=>{e.target===t&&(o.current=HO(i.current))};return t.addEventListener("animationstart",a),t.addEventListener("animationcancel",s),t.addEventListener("animationend",s),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",a),t.removeEventListener("animationcancel",s),t.removeEventListener("animationend",s)}}d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:s.useCallback(e=>{i.current=e?getComputedStyle(e):null,r(e)},[])}}(t),n="function"==typeof r?r({present:i.isPresent}):s.Children.only(r),o=Kk(i.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(n));return"function"==typeof r||i.isPresent?s.cloneElement(n,{ref:o}):null};function HO(e){return e?.animationName||"none"}qO.displayName="Presence";var WO=s[" useInsertionEffect ".trim().toString()]||PT;function KO({prop:e,defaultProp:t,onChange:r=()=>{},caller:i}){const[n,o,a]=function({defaultProp:e,onChange:t}){const[r,i]=s.useState(e),n=s.useRef(r),o=s.useRef(t);return WO(()=>{o.current=t},[t]),s.useEffect(()=>{n.current!==r&&(o.current?.(r),n.current=r)},[r,n]),[r,i,o]}({defaultProp:t,onChange:r}),c=void 0!==e,d=c?e:n;{const t=s.useRef(void 0!==e);s.useEffect(()=>{const e=t.current;if(e!==c){const t=e?"controlled":"uncontrolled",r=c?"controlled":"uncontrolled";console.warn(`${i} is changing from ${t} to ${r}. 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.`)}t.current=c},[c,i])}const l=s.useCallback(t=>{if(c){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else o(t)},[c,e,o,a]);return[d,l]}var JO=new WeakMap,QO=new WeakMap,YO={},XO=0,ZO=function(e){return e&&(e.host||ZO(e.parentNode))},eE=function(e,t,r,i){var n=function(e,t){return t.map(function(t){if(e.contains(t))return t;var r=ZO(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(e){return Boolean(e)})}(t,Array.isArray(e)?e:[e]);YO[r]||(YO[r]=new WeakMap);var s=YO[r],o=[],a=new Set,c=new Set(n),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};n.forEach(d);var l=function(e){e&&!c.has(e)&&Array.prototype.forEach.call(e.children,function(e){if(a.has(e))l(e);else try{var t=e.getAttribute(i),n=null!==t&&"false"!==t,c=(JO.get(e)||0)+1,d=(s.get(e)||0)+1;JO.set(e,c),s.set(e,d),o.push(e),1===c&&n&&QO.set(e,!0),1===d&&e.setAttribute(r,"true"),n||e.setAttribute(i,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}})};return l(t),a.clear(),XO++,function(){o.forEach(function(e){var t=JO.get(e)-1,n=s.get(e)-1;JO.set(e,t),s.set(e,n),t||(QO.has(e)||e.removeAttribute(i),QO.delete(e)),n||e.removeAttribute(r)}),--XO||(JO=new WeakMap,JO=new WeakMap,QO=new WeakMap,YO={})}},tE=function(e,t,r){void 0===r&&(r="data-aria-hidden");var i=Array.from(Array.isArray(e)?e:[e]),n=function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return n?(i.push.apply(i,Array.from(n.querySelectorAll("[aria-live], script"))),eE(i,n,r,"aria-hidden")):function(){return null}},rE="right-scroll-bar-position",iE="width-before-scroll-bar";function nE(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var sE="undefined"!=typeof window?s.useLayoutEffect:s.useEffect,oE=new WeakMap;function aE(e,r){var i,n,s,o=(i=null,n=function(t){return e.forEach(function(e){return nE(e,t)})},s=t.useState(function(){return{value:i,callback:n,facade:{get current(){return s.value},set current(e){var t=s.value;t!==e&&(s.value=e,s.callback(e,t))}}}})[0],s.callback=n,s.facade);return sE(function(){var t=oE.get(o);if(t){var r=new Set(t),i=new Set(e),n=o.current;r.forEach(function(e){i.has(e)||nE(e,null)}),i.forEach(function(e){r.has(e)||nE(e,n)})}oE.set(o,e)},[e]),o}function cE(e){return e}var dE=function(e){var t=e.sideCar,r=MR(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=t.read();if(!i)throw new Error("Sidecar medium not found");return s.createElement(i,IR({},r))};dE.isSideCarExport=!0;var lE=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=cE);var r=[],i=!1;return{read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var n=t(e,i);return r.push(n),function(){r=r.filter(function(e){return e!==n})}},assignSyncMedium:function(e){for(i=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){i=!0;var t=[];if(r.length){var n=r;r=[],n.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},o=function(){return Promise.resolve().then(s)};o(),r={push:function(e){t.push(e),o()},filter:function(e){return t=t.filter(e),r}}}}}(null);return t.options=IR({async:!0,ssr:!1},e),t}(),uE=function(){},pE=s.forwardRef(function(e,t){var r=s.useRef(null),i=s.useState({onScrollCapture:uE,onWheelCapture:uE,onTouchMoveCapture:uE}),n=i[0],o=i[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noRelative,m=e.noIsolation,g=e.inert,v=e.allowPinchZoom,b=e.as,y=void 0===b?"div":b,w=e.gapMode,_=MR(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,C=aE([r,t]),R=IR(IR({},_),n);return s.createElement(s.Fragment,null,u&&s.createElement(S,{sideCar:lE,removeScrollBar:l,shards:p,noRelative:f,noIsolation:m,inert:g,setCallbacks:o,allowPinchZoom:!!v,lockRef:r,gapMode:w}),a?s.cloneElement(s.Children.only(c),IR(IR({},R),{ref:C})):s.createElement(y,IR({},R,{className:d,ref:C}),c))});pE.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},pE.classNames={fullWidth:iE,zeroRight:rE};function hE(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var fE=function(){var e=0,t=null;return{add:function(r){var i,n;0==e&&(t=hE())&&(n=r,(i=t).styleSheet?i.styleSheet.cssText=n:i.appendChild(document.createTextNode(n)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},mE=function(){var e,t=(e=fE(),function(t,r){s.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])});return function(e){var r=e.styles,i=e.dynamic;return t(r,i),null}},gE={left:0,top:0,right:0,gap:0},vE=function(e){return parseInt(e||"",10)||0},bE=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return gE;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],i=t["padding"===e?"paddingTop":"marginTop"],n=t["padding"===e?"paddingRight":"marginRight"];return[vE(r),vE(i),vE(n)]}(e),r=document.documentElement.clientWidth,i=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,i-r+t[2]-t[0])}},yE=mE(),wE="data-scroll-locked",_E=function(e,t,r,i){var n=e.left,s=e.top,o=e.right,a=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(i,";\n padding-right: ").concat(a,"px ").concat(i,";\n }\n body[").concat(wE,"] {\n overflow: hidden ").concat(i,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(i,";"),"margin"===r&&"\n padding-left: ".concat(n,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(o,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(a,"px ").concat(i,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(i,";")].filter(Boolean).join(""),"\n }\n \n .").concat(rE," {\n right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(iE," {\n margin-right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(rE," .").concat(rE," {\n right: 0 ").concat(i,";\n }\n \n .").concat(iE," .").concat(iE," {\n margin-right: 0 ").concat(i,";\n }\n \n body[").concat(wE,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},SE=function(){var e=parseInt(document.body.getAttribute(wE)||"0",10);return isFinite(e)?e:0},CE=function(e){var t=e.noRelative,r=e.noImportant,i=e.gapMode,n=void 0===i?"margin":i;s.useEffect(function(){return document.body.setAttribute(wE,(SE()+1).toString()),function(){var e=SE()-1;e<=0?document.body.removeAttribute(wE):document.body.setAttribute(wE,e.toString())}},[]);var o=s.useMemo(function(){return bE(n)},[n]);return s.createElement(yE,{styles:_E(o,!t,n,r?"":"!important")})},RE=!1;if("undefined"!=typeof window)try{var kE=Object.defineProperty({},"passive",{get:function(){return RE=!0,!0}});window.addEventListener("test",kE,kE),window.removeEventListener("test",kE,kE)}catch(AD){RE=!1}var TE=!!RE&&{passive:!1},PE=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},OE=function(e,t){var r=t.ownerDocument,i=t;do{if("undefined"!=typeof ShadowRoot&&i instanceof ShadowRoot&&(i=i.host),EE(e,i)){var n=DE(e,i);if(n[1]>n[2])return!0}i=i.parentNode}while(i&&i!==r.body);return!1},EE=function(e,t){return"v"===e?function(e){return PE(e,"overflowY")}(t):function(e){return PE(e,"overflowX")}(t)},DE=function(e,t){return"v"===e?function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]}(t):function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t)},xE=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},IE=function(e){return[e.deltaX,e.deltaY]},ME=function(e){return e&&"current"in e?e.current:e},jE=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},LE=0,AE=[];function NE(e){for(var t=null;null!==e;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var BE,FE=(BE=function(e){var t=s.useRef([]),r=s.useRef([0,0]),i=s.useRef(),n=s.useState(LE++)[0],o=s.useState(mE)[0],a=s.useRef(e);s.useEffect(function(){a.current=e},[e]),s.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(n));var t=function(e,t,r){if(r||2===arguments.length)for(var i,n=0,s=t.length;n<s;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(ME),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add("allow-interactivity-".concat(n))}),function(){document.body.classList.remove("block-interactivity-".concat(n)),t.forEach(function(e){return e.classList.remove("allow-interactivity-".concat(n))})}}},[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback(function(e,t){if("touches"in e&&2===e.touches.length||"wheel"===e.type&&e.ctrlKey)return!a.current.allowPinchZoom;var n,s=xE(e),o=r.current,c="deltaX"in e?e.deltaX:o[0]-s[0],d="deltaY"in e?e.deltaY:o[1]-s[1],l=e.target,u=Math.abs(c)>Math.abs(d)?"h":"v";if("touches"in e&&"h"===u&&"range"===l.type)return!1;var p=OE(u,l);if(!p)return!0;if(p?n=u:(n="v"===u?"h":"v",p=OE(u,l)),!p)return!1;if(!i.current&&"changedTouches"in e&&(c||d)&&(i.current=n),!n)return!0;var h=i.current||n;return function(e,t,r,i){var n=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),s=n*i,o=r.target,a=t.contains(o),c=!1,d=s>0,l=0,u=0;do{if(!o)break;var p=DE(e,o),h=p[0],f=p[1]-p[2]-n*h;(h||f)&&EE(e,o)&&(l+=f,u+=h);var m=o.parentNode;o=m&&m.nodeType===Node.DOCUMENT_FRAGMENT_NODE?m.host:m}while(!a&&o!==document.body||a&&(t.contains(o)||t===o));return(d&&Math.abs(l)<1||!d&&Math.abs(u)<1)&&(c=!0),c}(h,t,e,"h"===h?c:d)},[]),d=s.useCallback(function(e){var r=e;if(AE.length&&AE[AE.length-1]===o){var i="deltaY"in r?IE(r):xE(r),n=t.current.filter(function(e){return e.name===r.type&&(e.target===r.target||r.target===e.shadowParent)&&(t=e.delta,n=i,t[0]===n[0]&&t[1]===n[1]);var t,n})[0];if(n&&n.should)r.cancelable&&r.preventDefault();else if(!n){var s=(a.current.shards||[]).map(ME).filter(Boolean).filter(function(e){return e.contains(r.target)});(s.length>0?c(r,s[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}},[]),l=s.useCallback(function(e,r,i,n){var s={name:e,delta:r,target:i,should:n,shadowParent:NE(i)};t.current.push(s),setTimeout(function(){t.current=t.current.filter(function(e){return e!==s})},1)},[]),u=s.useCallback(function(e){r.current=xE(e),i.current=void 0},[]),p=s.useCallback(function(t){l(t.type,IE(t),t.target,c(t,e.lockRef.current))},[]),h=s.useCallback(function(t){l(t.type,xE(t),t.target,c(t,e.lockRef.current))},[]);s.useEffect(function(){return AE.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,TE),document.addEventListener("touchmove",d,TE),document.addEventListener("touchstart",u,TE),function(){AE=AE.filter(function(e){return e!==o}),document.removeEventListener("wheel",d,TE),document.removeEventListener("touchmove",d,TE),document.removeEventListener("touchstart",u,TE)}},[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:jE(n)}):null,f?s.createElement(CE,{noRelative:e.noRelative,gapMode:e.gapMode}):null)},lE.useMedium(BE),dE),zE=s.forwardRef(function(e,t){return s.createElement(pE,IR({},e,{ref:t,sideCar:FE}))});zE.classNames=pE.classNames;var VE="Popover",[UE,$E]=Zk(VE,[RO]),GE=RO(),[qE,HE]=UE(VE),WE=e=>{const{__scopePopover:t,children:r,open:i,defaultOpen:n,onOpenChange:o,modal:a=!1}=e,c=GE(t),d=s.useRef(null),[l,u]=s.useState(!1),[p,h]=KO({prop:i,defaultProp:n??!1,onChange:o,caller:VE});return Xk.jsx(zO,{...c,children:Xk.jsx(qE,{scope:t,contentId:DT(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:s.useCallback(()=>h(e=>!e),[h]),hasCustomAnchor:l,onCustomAnchorAdd:s.useCallback(()=>u(!0),[]),onCustomAnchorRemove:s.useCallback(()=>u(!1),[]),modal:a,children:r})})};WE.displayName=VE;var KE="PopoverAnchor";s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=HE(KE,r),o=GE(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:c}=n;return s.useEffect(()=>(a(),()=>c()),[a,c]),Xk.jsx(VO,{...o,...i,ref:t})}).displayName=KE;var JE="PopoverTrigger",QE=s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=HE(JE,r),s=GE(r),o=Kk(t,n.triggerRef),a=Xk.jsx(sT.button,{type:"button","aria-haspopup":"dialog","aria-expanded":n.open,"aria-controls":n.contentId,"data-state":cD(n.open),...i,ref:o,onClick:qk(e.onClick,n.onOpenToggle)});return n.hasCustomAnchor?a:Xk.jsx(VO,{asChild:!0,...s,children:a})});QE.displayName=JE;var YE="PopoverPortal",[XE,ZE]=UE(YE,{forceMount:void 0}),eD=e=>{const{__scopePopover:t,forceMount:r,children:i,container:n}=e,s=HE(YE,t);return Xk.jsx(XE,{scope:t,forceMount:r,children:Xk.jsx(qO,{present:r||s.open,children:Xk.jsx(GO,{asChild:!0,container:n,children:i})})})};eD.displayName=YE;var tD="PopoverContent",rD=s.forwardRef((e,t)=>{const r=ZE(tD,e.__scopePopover),{forceMount:i=r.forceMount,...n}=e,s=HE(tD,e.__scopePopover);return Xk.jsx(qO,{present:i||s.open,children:s.modal?Xk.jsx(nD,{...n,ref:t}):Xk.jsx(sD,{...n,ref:t})})});rD.displayName=tD;var iD=tT("PopoverContent.RemoveScroll"),nD=s.forwardRef((e,t)=>{const r=HE(tD,e.__scopePopover),i=s.useRef(null),n=Kk(t,i),o=s.useRef(!1);return s.useEffect(()=>{const e=i.current;if(e)return tE(e)},[]),Xk.jsx(zE,{as:iD,allowPinchZoom:!0,children:Xk.jsx(oD,{...e,ref:n,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:qk(e.onCloseAutoFocus,e=>{e.preventDefault(),o.current||r.triggerRef.current?.focus()}),onPointerDownOutside:qk(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,i=2===t.button||r;o.current=i},{checkForDefaultPrevented:!1}),onFocusOutside:qk(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})}),sD=s.forwardRef((e,t)=>{const r=HE(tD,e.__scopePopover),i=s.useRef(!1),n=s.useRef(!1);return Xk.jsx(oD,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(i.current||r.triggerRef.current?.focus(),t.preventDefault()),i.current=!1,n.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(i.current=!0,"pointerdown"===t.detail.originalEvent.type&&(n.current=!0));const s=t.target,o=r.triggerRef.current?.contains(s);o&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&n.current&&t.preventDefault()}})}),oD=s.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:i,onOpenAutoFocus:n,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=HE(tD,r),f=GE(r);return s.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??gT()),document.body.insertAdjacentElement("beforeend",e[1]??gT()),mT++,()=>{1===mT&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),mT--}},[]),Xk.jsx(wT,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:n,onUnmountAutoFocus:o,children:Xk.jsx(pT,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1),children:Xk.jsx(UO,{"data-state":cD(h.open),role:"dialog",id:h.contentId,...f,...p,ref:t,style:{...p.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)"}})})})}),aD="PopoverClose";s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=HE(aD,r);return Xk.jsx(sT.button,{type:"button",...i,ref:t,onClick:qk(e.onClick,()=>n.onOpenChange(!1))})}).displayName=aD;function cD(e){return e?"open":"closed"}s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=GE(r);return Xk.jsx($O,{...n,...i,ref:t})}).displayName="PopoverArrow";var dD=eD,lD=rD;const uD=WE,pD=QE,hD=s.forwardRef((e,t)=>{var{style:r,align:i="center",sideOffset:n=4}=e,o=MR(e,["style","align","sideOffset"]);return s.createElement(dD,null,s.createElement(lD,Object.assign({ref:t,align:i,sideOffset:n,style:Object.assign({width:"200px",backgroundColor:"#fff",border:"1px solid #e5e5e5",borderRadius:"0.375rem",boxShadow:"0 1px 2px 0 rgb(0 0 0 / 0.05)",color:"#333",fontSize:"14px",lineHeight:"1.5",padding:"16px",zIndex:50,outline:"none"},r)},o)))});hD.displayName=lD.displayName;const fD=s.createContext({}),mD=s.createContext({}),gD=()=>{const e=s.useContext(fD),t=s.useContext(mD);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},vD=s.createContext({}),bD=e=>{const{children:t}=e,r=MR(e,["children"]),[i,n]=s.useState(!1);return s.createElement(vD.Provider,{value:{open:i,setOpen:n}},s.createElement(uD,Object.assign({},r,{open:i,onOpenChange:n}),t))},yD=s.forwardRef((e,t)=>{var{children:r,style:i}=e,n=MR(e,["children","style"]);return s.createElement(hD,Object.assign({ref:t,style:Object.assign({display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minWidth:"180px",maxWidth:"300px",maxHeight:"100vh",overflowY:"auto",padding:0},i)},n),r)});yD.displayName="ParticipantMenuContent";const wD=s.forwardRef((e,t)=>{var{children:r,style:i}=e,n=MR(e,["children","style"]);return s.createElement(pD,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},i)},n),r)});wD.displayName=pD.displayName;const _D=s.forwardRef((e,t)=>{var{children:r,style:i,participantAction:n}=e,o=MR(e,["children","style","participantAction"]);const{participant:a,setOpen:c,maximizedParticipant:d,setMaximizedParticipant:l,setFloatingParticipant:u,floatingParticipant:p}=(()=>{const e=s.useContext(vD),t=gD();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),h=jR(),f=LR(MS).find(e=>e.id===a.id),m=(null==d?void 0:d.id)===a.id,g=(null==p?void 0:p.id)===a.id;let v;switch(n){case"maximize":v=()=>{l(m?null:a),c(!1)};break;case"spotlight":v=()=>{h(f?xS({id:a.id}):DS({id:a.id})),c(!1)};break;case"float":v=()=>{u(g?null:a),c(!1)}}return s.createElement("button",Object.assign({ref:t,role:"menuitem",tabIndex:-1,onClick:null!=v?v:o.onClick,style:Object.assign({alignItems:"stretch",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",height:"40px",lineHeight:"40px",minWidth:"140px",padding:"0 12px",textAlign:"left",textDecoration:"none",whiteSpace:"nowrap",width:"100%"},i)},o),r)});function SD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("g",null,s.createElement("circle",{cx:"6",cy:"12",r:"2"}),s.createElement("circle",{cx:"12",cy:"12",r:"2"}),s.createElement("circle",{cx:"18",cy:"12",r:"2"})))}function CD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m13.875 3c0 .62132.5037 1.125 1.125 1.125h3.284l-4.0795 4.0795c-.4393.43934-.4393 1.15166 0 1.591.4393.4393 1.1517.4393 1.591 0l4.0795-4.07951v3.28401c0 .62132.5037 1.125 1.125 1.125s1.125-.50368 1.125-1.125v-6c0-.15254-.0304-.29799-.0854-.43063-.0536-.12968-.1326-.25135-.2368-.35749l-.0147-.01469c-.203-.19928-.4812-.32219-.7881-.32219h-6c-.6213 0-1.125.50368-1.125 1.125zm-9.75 12c0-.6213-.50368-1.125-1.125-1.125s-1.125.5037-1.125 1.125v6c0 .3069.12291.5851.32219.7881.00486.005.00975.0099.01469.0147.10614.1042.22781.1832.35749.2368.13264.055.27809.0854.43063.0854h6c.62132 0 1.125-.5037 1.125-1.125s-.50368-1.125-1.125-1.125h-3.28401l4.07951-4.0795c.4393-.4393.4393-1.1517 0-1.591-.43934-.4393-1.15166-.4393-1.591 0l-4.0795 4.0795z"}))}function RD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m15.241.146691c-.1011-.1955882-.3809-.1955879-.482 0l-1.1063 2.139639c-.0258.04991-.0665.09058-.1164.11639l-2.1396 1.10629c-.1956.10113-.1956.38085 0 .48198l2.1396 1.10629c.0499.02581.0906.06648.1164.11639l1.1063 2.13964c.1011.19559.3809.19559.482 0l1.1063-2.13964c.0258-.04991.0665-.09058.1164-.11639l2.1396-1.10629c.1956-.10113.1956-.38085 0-.48198l-2.1396-1.10629c-.0499-.02581-.0906-.06648-.1164-.11639zm-13.741 2.900259v14.67495c0 .0511.00116.1018.00345.1523-.00229.0418-.00345.0837-.00345.1258 0 .5674.21005 1.1103.59339 1.6103.24265.3472.55042.6455.90566.8773 1.61225 1.213 4.36988 2.0124 7.50095 2.0124 4.3315 0 7.9484-1.53 8.8068-3.5681.0651-.1472.1148-.3024.1455-.4658.0315-.1532.0477-.3087.0477-.4661 0-.6032-.2374-1.1788-.668-1.7045-.1377-.1975-.2995-.4017-.4877-.6127l-14.22219-13.74809c-.28845-.27884-.67396-.43471-1.07516-.43471-.85436 0-1.54695.69259-1.54695 1.54695zm19.2646 4.59631c.0988-.19101.372-.19101.4708 0l.8546 1.65303c.0253.04874.065.08846.1137.11366l1.653.85465c.1911.0988.1911.372 0 .4708l-1.653.8546c-.0487.0253-.0884.065-.1137.1137l-.8546 1.653c-.0988.1911-.372.1911-.4708 0l-.8546-1.653c-.0253-.0487-.065-.0884-.1137-.1137l-1.653-.8546c-.1911-.0988-.1911-.372 0-.4708l1.653-.85465c.0487-.0252.0884-.06492.1137-.11366zm-3.2651 10.35684c0 .0769-.1144.6851-1.5305 1.3931-1.2964.6482-3.2274 1.1069-5.4695 1.1069s-4.17308-.4587-5.46952-1.1069c-1.41607-.708-1.53047-1.3162-1.53047-1.3931 0-.077.1144-.6851 1.53047-1.3932 1.29644-.6482 3.22742-1.1068 5.46952-1.1068s4.1731.4586 5.4695 1.1068c1.4161.7081 1.5305 1.3162 1.5305 1.3932z"}))}function kD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm1.875 19.5c0-.6213.5037-1.125 1.125-1.125h3.284l-5.5795-5.5795c-.4393-.4393-.4393-1.1517 0-1.591s1.1517-.4393 1.591 0l5.5795 5.5795v-3.284c0-.6213.5037-1.125 1.125-1.125s1.125.5037 1.125 1.125v6c0 .308-.1238.5872-.3244.7903-.0033.0034-.0067.0068-.0101.0102-.1067.1054-.2292.1851-.3599.2391-.1326.055-.2781.0854-.4306.0854h-6c-.6213 0-1.125-.5037-1.125-1.125z"}))}function TD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm8.625 12c0 .6213-.5037 1.125-1.125 1.125h-3.284l5.5795 5.5795c.4393.4393.4393 1.1517 0 1.591s-1.1517.4393-1.591 0l-5.5795-5.5795v3.284c0 .6213-.5037 1.125-1.125 1.125s-1.125-.5037-1.125-1.125v-6c0-.3081.1238-.5872.3244-.7904.0034-.0034.0068-.0068.0102-.0102.1067-.1053.2292-.185.3598-.239.1326-.055.2781-.0854.4306-.0854h6c.6213 0 1.125.5037 1.125 1.125z"}))}function PD({participant:e}){const t=LR(MS).find(t=>t.id===e.id),{isHovered:r,maximizedParticipant:i,floatingParticipant:n}=gD(),o=(null==i?void 0:i.id)===e.id,a=(null==n?void 0:n.id)===e.id;return r?s.createElement(bD,null,s.createElement(wD,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(SD,{height:20,width:20,transform:"rotate(90)"})),s.createElement(yD,null,e.isLocalClient?s.createElement(_D,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},a?s.createElement(s.Fragment,null,s.createElement(TD,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(kD,{height:16,width:16}),"Pop out")):null,s.createElement(_D,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(CD,{height:16,width:16}),o?"Minimize":"Maximize"),s.createElement(_D,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(RD,{height:16,width:16}),t?"Remove spotlight":"Spotlight"))):null}_D.displayName="ParticipantMenuItem";const OD=s.forwardRef(({className:e,participant:t,children:r},i)=>{const[n,o]=s.useState(!1),a=s.useCallback(()=>{o(!0)},[]),c=s.useCallback(()=>{o(!1)},[]);return s.createElement(mD.Provider,{value:{participant:t,isHovered:n}},s.createElement("div",{ref:i,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))});OD.displayName="GridCell";const ED=s.forwardRef((e,t)=>{var{stream:r,style:i}=e,n=MR(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=gD();if(!d)return null;const u=c[d.id];s.useImperativeHandle(t,()=>o.current);const p=s.useCallback(()=>{const e=o.current&&o.current.captureAspectRatio();e&&e!==u&&d.id&&a({aspectRatio:e,clientId:d.id})},[c,d.id,a]),h=r||d.stream;return h&&d.isVideoEnabled?s.createElement(NR,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),i),muted:d.isLocalClient},n,{stream:h,onVideoResize:p})):s.createElement(Gk,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0,muted:d.isLocalClient,stream:d.stream})});function DD({cellView:e,enableParticipantMenu:t,render:r}){const i=null==e?void 0:e.client;if(i)return"video"===e.type?s.createElement(OD,{participant:i},s.createElement(s.Fragment,null,r?r({participant:i}):s.createElement(s.Fragment,null,s.createElement(ED,null),t?s.createElement(PD,{participant:i}):null))):void 0}return ED.displayName="GridVideoView",e.GridCell=OD,e.GridVideoView=ED,e.ParticipantMenu=bD,e.ParticipantMenuContent=yD,e.ParticipantMenuItem=_D,e.ParticipantMenuTrigger=wD,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableParticipantMenu:a,enableConstrainedGrid:c}){const d=s.useRef(null),{containerFrame:l,cellViewsFloating:u,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,videoStage:g,setContainerBounds:v,setClientAspectRatios:b,maximizedParticipant:y,setMaximizedParticipant:w,isConstrained:_,floatingParticipant:S,setFloatingParticipant:C}=Tk({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableConstrainedGrid:c}),R=s.useCallback(({aspectRatio:e,clientId:t})=>{b(r=>Object.assign(Object.assign({},r),{[t]:e}))},[b]),k=s.useMemo(()=>DD(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{})),[u]),T=s.useMemo(()=>h.map(t=>DD(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[h]),P=s.useMemo(()=>p.map(t=>DD(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[p]),O=s.useMemo(()=>f.map(e=>DD({cellView:e,enableParticipantMenu:a})),[f]);return s.useEffect(()=>{if(!d.current)return;const e=new ResizeObserver(zw(()=>{var e,t,r,i;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(i=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==i?i:480})},{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}},[]),s.createElement(fD.Provider,{value:{onSetClientAspectRatio:R,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,maximizedParticipant:y,setMaximizedParticipant:w,floatingParticipant:S,setFloatingParticipant:C,isConstrained:_}},s.createElement("div",{ref:d,style:{width:"100%",height:"100%",position:"relative"}},s.createElement(ZR,{containerFrame:l,floatingContent:k,layoutVideoStage:g,presentationGridContent:T,gridContent:P,subgridContent:O})))},e.VideoView=NR,e.WherebyProvider=function({children:e}){const t=(({preloadedState:e,injectServices:t})=>ct({devTools:!1,reducer:HC,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(Wy.middleware),preloadedState:e}))({injectServices:function(){const e=wR.create({baseUrl:OR}),t=new cR({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:OR}),r=new TR({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=hg({host:new URL(e).host});return new PR({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}()});return s.createElement(_,{context:ER,store:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){const t=jR(),r=LR(zR);return s.useEffect(()=>(t(s_(e)),()=>{t(o_())}),[]),{state:r,actions:{setCameraDevice:s.useCallback(e=>t($w({deviceId:e})),[t]),setMicrophoneDevice:s.useCallback(e=>t(Gw({deviceId:e})),[t]),setSpeakerDevice:s.useCallback(e=>t(qw({deviceId:e})),[t]),toggleCameraEnabled:s.useCallback(e=>t(Hw({enabled:e})),[t]),toggleMicrophoneEnabled:s.useCallback(e=>t(Ww({enabled:e})),[t]),toggleLowDataModeEnabled:s.useCallback(e=>t(Kw({enabled:e})),[t])}}},e.useRoomConnection=function(e,t=FR){const r=jR(),i=LR(BR),n=s.useMemo(()=>{const r=new URL(e),i=new URLSearchParams(r.search),n=t.roomKey||i.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:n,roomUrl:e,userAgent:"browser-sdk:3.12.19",externalId:t.externalId||null}},[e,t]);s.useEffect(()=>()=>{r(Yy())},[]);const o=s.useCallback(e=>r(z_({text:e})),[r]),a=s.useCallback(()=>r(xC()),[r]),c=s.useCallback(e=>r(gC({displayName:e})),[r]),d=s.useCallback(e=>r(Hw({enabled:e})),[r]),l=s.useCallback(e=>r(Ww({enabled:e})),[r]),u=s.useCallback(e=>r(Kw({enabled:e})),[r]),p=s.useCallback(e=>r(yC({enabled:e})),[r]),h=s.useCallback(e=>r(nS({clientIds:[e],enable:!0})),[r]),f=s.useCallback(e=>r(sS({clientIds:[e],enable:!0})),[r]),m=s.useCallback(e=>r($C({participantId:e})),[r]),g=s.useCallback(e=>r(GC({participantId:e})),[r]),v=s.useCallback(()=>r($_()),[r]),b=s.useCallback(()=>r(uS()),[r]),y=s.useCallback(()=>r(G_()),[r]),w=s.useCallback(()=>r(pS()),[r]),_=s.useCallback(()=>r(Xy(n)),[r]),S=s.useCallback(()=>r(Yy()),[r]),C=s.useCallback(e=>r(vS({locked:e})),[r]),R=s.useCallback(e=>r(nS({clientIds:e,enable:!1})),[r]),k=s.useCallback(e=>r(sS({clientIds:e,enable:!1})),[r]),T=s.useCallback(e=>r(DS({id:e})),[r]),P=s.useCallback(e=>r(xS({id:e})),[r]),O=s.useCallback(e=>r(bS({clientId:e})),[r]),E=s.useCallback(e=>r(yS({stayBehind:e})),[r]),D=s.useCallback(e=>r(M_({group:e})),[r]),x=s.useCallback(()=>r(M_({group:""})),[r]),{events:I}=i;return{state:MR(i,["events"]),events:I,actions:{toggleLowDataMode:u,toggleRaiseHand:p,askToSpeak:h,askToTurnOnCamera:f,acceptWaitingParticipant:m,knock:a,joinRoom:_,leaveRoom:S,lockRoom:C,muteParticipants:R,turnOffParticipantCameras:k,kickParticipant:O,endMeeting:E,rejectWaitingParticipant:g,sendChatMessage:o,setDisplayName:c,startCloudRecording:v,startScreenshare:b,stopCloudRecording:y,stopScreenshare:w,toggleCamera:d,toggleMicrophone:l,spotlightParticipant:T,removeSpotlight:P,joinBreakoutGroup:D,joinBreakoutMainRoom:x}}},e}({},React,ReactDOM);
3
+ let jo;ko.AwaitQueue=class{pendingTasks=new Map;nextTaskId=0;stopping=!1;constructor(){Mo.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,Mo.debug(`push() [name:${t}]`),"function"!=typeof e)throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch(e){}return new Promise((r,i)=>{const n={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(n.completed)return;n.completed=!0,this.pendingTasks.delete(n.id),Mo.debug(`resolving task [name:${n.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!n.completed&&(n.completed=!0,this.pendingTasks.delete(n.id),Mo.debug(`rejecting task [name:${n.name}]: %s`,String(e)),i(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(n.id,n),1===this.pendingTasks.size&&this.execute(n)})}stop(){Mo.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Mo.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new Io.AwaitQueueStoppedError);this.stopping=!1}remove(e){Mo.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Io.AwaitQueueRemovedTaskError):Mo.debug(`stop() | no task with given idx [taskIdx:${e}]`)}dump(){const e=Date.now();let t=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:t++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0}))}async execute(e){if(Mo.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.AwaitQueueRemovedTaskError=e.AwaitQueueStoppedError=e.AwaitQueue=void 0;var t=ko;Object.defineProperty(e,"AwaitQueue",{enumerable:!0,get:function(){return t.AwaitQueue}});var r=Eo;Object.defineProperty(e,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return r.AwaitQueueStoppedError}}),Object.defineProperty(e,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return r.AwaitQueueRemovedTaskError}})}(Ro);var Lo="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:a):e=>(jo||(jo=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0)),Ao={};Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.Producer=void 0;const No=as,Bo=Ps,Fo=new ts.Logger("Producer");class zo extends No.EnhancedEventEmitter{constructor({id:e,localId:t,rtpSender:r,track:i,rtpParameters:n,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),this._closed=!1,this._observer=new No.EnhancedEventEmitter,Fo.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=i,this._kind=i.kind,this._rtpParameters=n,this._paused=!!o&&!i.enabled,this._maxSpatialLayer=void 0,this._stopTracks=s,this._disableTrackOnPause=o,this._zeroRtpOnPause=a,this._appData=c??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Fo.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Fo.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Bo.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){Fo.debug("pause()"),this._closed?Fo.error("pause() | Producer closed"):(this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause"))}resume(){Fo.debug("resume()"),this._closed?Fo.error("resume() | Producer closed"):(this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume"))}async replaceTrack({track:e}){if(Fo.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new Bo.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new Bo.InvalidStateError("track ended");e!==this._track?(await new Promise((t,r)=>{this.safeEmit("@replacetrack",e,t,r)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()):Fo.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new Bo.InvalidStateError("closed");if("video"!==this._kind)throw new Bo.UnsupportedError("not a video Producer");if("number"!=typeof e)throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,r)=>{this.safeEmit("@setmaxspatiallayer",e,t,r)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Bo.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)})}onTrackEnded(){Fo.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch(e){}}}Ao.Producer=zo;var Vo={};Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.Consumer=void 0;const Uo=as,$o=Ps,Go=new ts.Logger("Consumer");class qo extends Uo.EnhancedEventEmitter{constructor({id:e,localId:t,producerId:r,rtpReceiver:i,track:n,rtpParameters:s,appData:o}){super(),this._closed=!1,this._observer=new Uo.EnhancedEventEmitter,Go.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=i,this._track=n,this._rtpParameters=s,this._paused=!n.enabled,this._appData=o??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Go.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Go.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new $o.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){Go.debug("pause()"),this._closed?Go.error("pause() | Consumer closed"):this._paused?Go.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){Go.debug("resume()"),this._closed?Go.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):Go.debug("resume() | Consumer is already resumed")}onTrackEnded(){Go.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch(e){}}}Vo.Consumer=qo;var Ho={};Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.DataProducer=void 0;const Wo=as,Ko=Ps,Jo=new ts.Logger("DataProducer");class Qo extends Wo.EnhancedEventEmitter{constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:i}){super(),this._closed=!1,this._observer=new Wo.EnhancedEventEmitter,Jo.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Jo.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Jo.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(Jo.debug("send()"),this._closed)throw new Ko.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Jo.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?Jo.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):Jo.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Jo.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||Jo.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}}Ho.DataProducer=Qo;var Xo={};Object.defineProperty(Xo,"__esModule",{value:!0}),Xo.DataConsumer=void 0;const Yo=as,Zo=new ts.Logger("DataConsumer");class ea extends Yo.EnhancedEventEmitter{constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:i,appData:n}){super(),this._closed=!1,this._observer=new Yo.EnhancedEventEmitter,Zo.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=i,this._appData=n??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Zo.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Zo.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Zo.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let{error:t}=e;t||(t=new Error("unknown DataChannel error")),"sctp-failure"===t.errorDetail?Zo.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):Zo.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Zo.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}}Xo.DataConsumer=ea;var ta=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),ra=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ia=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ta(r,t,i[n]);return ra(r,t),r}}(),na=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Co,"__esModule",{value:!0}),Co.Transport=void 0;const sa=Ro,oa=na(Lo),aa=ts,ca=as,da=Ps,la=ia(xs),ua=ia(Ms),pa=Ao,ha=Vo,fa=Ho,ma=Xo,ga=new aa.Logger("Transport");class va{constructor(e){this.consumerOptions=e,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}let ba=class extends ca.EnhancedEventEmitter{constructor({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:u,extendedRtpCapabilities:p,canProduceByKind:h}){super(),this._closed=!1,this._iceGatheringState="new",this._connectionState="new",this._producers=new Map,this._consumers=new Map,this._dataProducers=new Map,this._dataConsumers=new Map,this._probatorConsumerCreated=!1,this._awaitQueue=new sa.AwaitQueue,this._pendingConsumerTasks=[],this._consumerCreationInProgress=!1,this._pendingPauseConsumers=new Map,this._consumerPauseInProgress=!1,this._pendingResumeConsumers=new Map,this._consumerResumeInProgress=!1,this._pendingCloseConsumers=new Map,this._consumerCloseInProgress=!1,this._observer=new ca.EnhancedEventEmitter,ga.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._extendedRtpCapabilities=p,this._canProduceByKind=h,this._maxSctpMessageSize=s?s.maxMessageSize:null;const f=la.clone(c)??{};delete f.iceServers,delete f.iceTransportPolicy,delete f.bundlePolicy,delete f.rtcpMuxPolicy,delete f.sdpSemantics,this._handler=u(),this._handler.run({direction:e,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:f,proprietaryConstraints:d,extendedRtpCapabilities:p}),this._appData=l??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){ga.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(const e of this._producers.values())e.transportClosed();this._producers.clear();for(const e of this._consumers.values())e.transportClosed();this._consumers.clear();for(const e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(const e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close")}}async getStats(){if(this._closed)throw new da.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(ga.debug("restartIce()"),this._closed)throw new da.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(ga.debug("updateIceServers()"),this._closed)throw new da.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,encodings:t,codecOptions:r,codec:i,stopTracks:n=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if(ga.debug("produce() [track:%o]",e),this._closed)throw new da.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new da.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new da.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new da.InvalidStateError("track ended");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("produce"))throw new TypeError('no "produce" listener set into this transport');if(c&&"object"!=typeof c)throw new TypeError("if given, appData must be an object");return this._awaitQueue.push(async()=>{let d;if(t&&!Array.isArray(t))throw TypeError("encodings must be an array");t&&0===t.length?d=void 0:t&&(d=t.map(e=>{const t={active:!0};return!1===e.active&&(t.active=!1),"boolean"==typeof e.dtx&&(t.dtx=e.dtx),"string"==typeof e.scalabilityMode&&(t.scalabilityMode=e.scalabilityMode),"number"==typeof e.scaleResolutionDownBy&&(t.scaleResolutionDownBy=e.scaleResolutionDownBy),"number"==typeof e.maxBitrate&&(t.maxBitrate=e.maxBitrate),"number"==typeof e.maxFramerate&&(t.maxFramerate=e.maxFramerate),"boolean"==typeof e.adaptivePtime&&(t.adaptivePtime=e.adaptivePtime),"string"==typeof e.priority&&(t.priority=e.priority),"string"==typeof e.networkPriority&&(t.networkPriority=e.networkPriority),t}));const{localId:l,rtpParameters:u,rtpSender:p}=await this._handler.send({track:e,encodings:d,codecOptions:r,codec:i,onRtpSender:a});try{ua.validateRtpParameters(u);const{id:t}=await new Promise((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:u,appData:c},t,r)}),r=new pa.Producer({id:t,localId:l,rtpSender:p,track:e,rtpParameters:u,stopTracks:n,disableTrackOnPause:s,zeroRtpOnPause:o,appData:c});return this._producers.set(r.id,r),this.handleProducer(r),this._observer.safeEmit("newproducer",r),r}catch(e){throw this._handler.stopSending(l).catch(()=>{}),e}},"transport.produce()").catch(t=>{if(n)try{e.stop()}catch(e){}throw t})}async consume({id:e,producerId:t,kind:r,rtpParameters:i,streamId:n,onRtpReceiver:s,appData:o={}}){if(ga.debug("consume()"),this._closed)throw new da.InvalidStateError("closed");if("recv"!==this._direction)throw new da.UnsupportedError("not a receiving Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing producerId");if("audio"!==r&&"video"!==r)throw new TypeError(`invalid kind '${r}'`);if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(o&&"object"!=typeof o)throw new TypeError("if given, appData must be an object");const a=la.clone(i);if(!ua.canReceive(a,this._extendedRtpCapabilities))throw new da.UnsupportedError("cannot consume this Producer");const c=new va({id:e,producerId:t,kind:r,rtpParameters:a,streamId:n,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),(0,oa.default)(()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()}),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:i="",protocol:n="",appData:s={}}={}){if(ga.debug("produceData()"),this._closed)throw new da.InvalidStateError("closed");if("send"!==this._direction)throw new da.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new da.UnsupportedError("SCTP not enabled by remote Transport");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(0===this.listenerCount("producedata"))throw new TypeError('no "producedata" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");return(t||r)&&(e=!1),this._awaitQueue.push(async()=>{const{dataChannel:o,sctpStreamParameters:a}=await this._handler.sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n});ua.validateSctpStreamParameters(a);const{id:c}=await new Promise((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:i,protocol:n,appData:s},e,t)}),d=new fa.DataProducer({id:c,dataChannel:o,sctpStreamParameters:a,appData:s});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:r,label:i="",protocol:n="",appData:s={}}){if(ga.debug("consumeData()"),this._closed)throw new da.InvalidStateError("closed");if("recv"!==this._direction)throw new da.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new da.UnsupportedError("SCTP not enabled by remote Transport");if("string"!=typeof e)throw new TypeError("missing id");if("string"!=typeof t)throw new TypeError("missing dataProducerId");if(0===this.listenerCount("connect")&&"new"===this._connectionState)throw new TypeError('no "connect" listener set into this transport');if(s&&"object"!=typeof s)throw new TypeError("if given, appData must be an object");const o=la.clone(r);return ua.validateSctpStreamParameters(o),this._awaitQueue.push(async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:i,protocol:n}),a=new ma.DataConsumer({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:o,appData:s});return this._dataConsumers.set(a.id,a),this.handleDataConsumer(a),this._observer.safeEmit("newdataconsumer",a),a},"transport.consumeData()")}async createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingConsumerTasks.length)return void ga.debug("createPendingConsumers() | there is no Consumer to be created");const e=[...this._pendingConsumerTasks];let t;this._pendingConsumerTasks=[];const r=[];for(const t of e){const{id:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:i,rtpParameters:n,streamId:s,onRtpReceiver:o})}try{const i=await this._handler.receive(r);for(let r=0;r<i.length;++r){const n=e[r],s=i[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=n.consumerOptions,{localId:u,rtpReceiver:p,track:h}=s,f=new ha.Consumer({id:o,localId:u,producerId:a,rtpReceiver:p,track:h,rtpParameters:d,appData:l});this._consumers.set(f.id,f),this.handleConsumer(f),this._probatorConsumerCreated||t||"video"!==c||(t=f),this._observer.safeEmit("newconsumer",f),n.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=ua.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),ga.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){ga.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",e)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingPauseConsumers.size)return void ga.debug("pausePendingConsumers() | there is no Consumer to be paused");const e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.pauseReceiving(t)}catch(e){ga.error("pausePendingConsumers() | failed to pause Consumers:",e)}},"transport.pausePendingConsumers").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingResumeConsumers.size)return void ga.debug("resumePendingConsumers() | there is no Consumer to be resumed");const e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{const t=e.map(e=>e.localId);await this._handler.resumeReceiving(t)}catch(e){ga.error("resumePendingConsumers() | failed to resume Consumers:",e)}},"transport.resumePendingConsumers").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(0===this._pendingCloseConsumers.size)return void ga.debug("closePendingConsumers() | there is no Consumer to be closed");const e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(e=>e.localId))}catch(e){ga.error("closePendingConsumers() | failed to close Consumers:",e)}},"transport.closePendingConsumers").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){const e=this._handler;e.on("@connect",({dtlsParameters:e},t,r)=>{this._closed?r(new da.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)}),e.on("@icegatheringstatechange",e=>{e!==this._iceGatheringState&&(ga.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))}),e.on("@connectionstatechange",e=>{e!==this._connectionState&&(ga.debug("connection state changed to %s",e),this._connectionState=e,this._closed||this.safeEmit("connectionstatechange",e))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),this._closed||this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(e=>ga.warn("producer.close() failed:%o",e))}),e.on("@pause",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(r)}),e.on("@resume",(t,r)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(r)}),e.on("@replacetrack",(t,r,i)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(r).catch(i)}),e.on("@setmaxspatiallayer",(t,r,i)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(r).catch(i)}),e.on("@setrtpencodingparameters",(t,r,i)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(r).catch(i)}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new da.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(r)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),this._closed||(this._pendingCloseConsumers.set(e.id,e),!1===this._consumerCloseInProgress&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),(0,oa.default)(()=>{this._closed||!1===this._consumerPauseInProgress&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),(0,oa.default)(()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()})}),e.on("@getstats",(t,r)=>{if(this._closed)return r(new da.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(r)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};Co.Transport=ba;var ya={},wa={},_a=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Sa=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ca=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&_a(r,t,i[n]);return Sa(r,t),r}}();Object.defineProperty(wa,"__esModule",{value:!0});var Ra=wa.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=[];let i=!1,n=!1;for(const s of e.media){const e=s.type;switch(e){case"audio":if(i)continue;i=!0;break;case"video":if(n)continue;n=!0;break;default:continue}for(const r of s.rtp){const i={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(i.preferredPayloadType,i)}for(const e of s.fmtp||[]){const r=Oa.parseParams(e.config),i=t.get(e.payload);i&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),i.parameters=r)}for(const r of s.rtcpFb||[]){const i={type:r.type,parameter:r.subtype};if(i.parameter||delete i.parameter,"*"!==r.payload){const e=t.get(r.payload);if(!e)continue;e.rtcpFeedback.push(i)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(i)}for(const t of s.ext||[]){if(t["encrypt-uri"])continue;const i={kind:e,uri:t.uri,preferredId:t.value};r.push(i)}}return{codecs:Array.from(t.values()),headerExtensions:r}},ka=wa.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,i=e.fingerprint;if(!r||!i){const t=(e.media||[]).find(e=>0!==e.port);t&&(r??(r=t.setup),i??(i=t.fingerprint))}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!i)throw new Error("no a=fingerprint found at SDP session or media level");switch(r){case"active":t="client";break;case"passive":t="server";break;case"actpass":t="auto"}return{role:t,fingerprints:[{algorithm:i.type,value:i.hash}]}},Ta=wa.getCname=function({offerMediaObject:e}){const t=(e.ssrcs||[]).find(e=>"cname"===e.attribute);if(!t)return"";return t.value},Pa=wa.applyCodecParameters=function({offerRtpParameters:e,answerMediaObject:t}){for(const r of e.codecs){const e=r.mimeType.toLowerCase();if("audio/opus"!==e)continue;if(!(t.rtp||[]).find(e=>e.payload===r.payloadType))continue;t.fmtp=t.fmtp||[];let i=t.fmtp.find(e=>e.payload===r.payloadType);i||(i={payload:r.payloadType,config:""},t.fmtp.push(i));const n=Oa.parseParams(i.config);switch(e){case"audio/opus":{const e=r.parameters["sprop-stereo"];void 0!==e&&(n.stereo=Number(e)?1:0);break}}i.config="";for(const e of Object.keys(n))i.config&&(i.config+=";"),i.config+=`${e}=${n[e]}`}};const Oa=Ca(gi);var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.getRtpEncodings=function({offerMediaObject:e}){const t=new Set;for(const r of e.ssrcs||[]){const e=r.id;t.add(e)}if(0===t.size)throw new Error("no a=ssrc lines found");const r=new Map;for(const i of e.ssrcGroups||[]){if("FID"!==i.semantics)continue;let[e,n]=i.ssrcs.split(/\s+/);e=Number(e),n=Number(n),t.has(e)&&(t.delete(e),t.delete(n),r.set(e,n))}for(const e of t)r.set(e,null);const i=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),i.push(r)}return i},Ea.addLegacySimulcast=function({offerMediaObject:e,numStreams:t}){if(t<=1)throw new TypeError("numStreams must be greater than 1");const r=(e.ssrcs||[]).find(e=>"msid"===e.attribute);if(!r)throw new Error("a=ssrc line with msid information not found");const[i,n]=r.value.split(" "),s=Number(r.id);let o;(e.ssrcGroups||[]).some(e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===s&&(o=Number(t[1]),!0)});const a=e.ssrcs.find(e=>"cname"===e.attribute);if(!a)throw new Error("a=ssrc line with cname information not found");const c=a.value,d=[],l=[];for(let e=0;e<t;++e)d.push(s+e),o&&l.push(o+e);e.ssrcGroups=[],e.ssrcs=[],e.ssrcGroups.push({semantics:"SIM",ssrcs:d.join(" ")});for(const t of d)e.ssrcs.push({id:t,attribute:"cname",value:c}),e.ssrcs.push({id:t,attribute:"msid",value:`${i} ${n}`});for(let t=0;t<l.length;++t){const r=d[t],s=l[t];e.ssrcs.push({id:s,attribute:"cname",value:c}),e.ssrcs.push({id:s,attribute:"msid",value:`${i} ${n}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var Da={};Object.defineProperty(Da,"__esModule",{value:!0});var xa=Da.addNackSuppportForOpus=function(e){for(const t of e.codecs??[])"audio/opus"!==t.mimeType.toLowerCase()&&"audio/multiopus"!==t.mimeType.toLowerCase()||t.rtcpFeedback?.some(e=>"nack"===e.type&&!e.parameter)||(t.rtcpFeedback||(t.rtcpFeedback=[]),t.rtcpFeedback.push({type:"nack"}))};var Ia={};Object.defineProperty(Ia,"__esModule",{value:!0});var Ma=Ia.HandlerInterface=void 0;const ja=as;class La extends ja.EnhancedEventEmitter{constructor(){super()}}Ma=Ia.HandlerInterface=La;var Aa={},Na={},Ba=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Fa=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),za=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Ba(r,t,i[n]);return Fa(r,t),r}}();Object.defineProperty(Na,"__esModule",{value:!0}),Na.OfferMediaSection=Na.AnswerMediaSection=Na.MediaSection=void 0;const Va=za(gi),Ua=za(xs);class $a{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:i=!1}){if(this._mediaObject={},this._planB=i,e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(const e of t){const t={component:1};t.foundation=e.foundation,t.ip=e.address??e.ip,t.port=e.port,t.priority=e.priority,t.transport=e.protocol,t.type=e.type,e.tcpType&&(t.tcptype=e.tcpType),this._mediaObject.candidates.push(t)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}r&&this.setDtlsRole(r.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return 0===this._mediaObject.port}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause(),delete this._mediaObject.ext,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}close(){this.disable(),this._mediaObject.port=0}}Na.MediaSection=$a;Na.AnswerMediaSection=class extends $a{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:d,extmapAllowMixed:l=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(const e of c.codecs){const t={payload:e.payloadType,codec:Ga(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Ua.clone(e.parameters)??{};let i=Ua.clone(e.rtcpFeedback)??[];if(d){const{opusStereo:t,opusFec:n,opusDtx:s,opusMaxPlaybackRate:o,opusMaxAverageBitrate:c,opusPtime:l,opusNack:u,videoGoogleStartBitrate:p,videoGoogleMaxBitrate:h,videoGoogleMinBitrate:f}=d,m=a.codecs.find(t=>t.payloadType===e.payloadType);switch(e.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":void 0!==t&&(m.parameters["sprop-stereo"]=t?1:0,r.stereo=t?1:0),void 0!==n&&(m.parameters.useinbandfec=n?1:0,r.useinbandfec=n?1:0),void 0!==s&&(m.parameters.usedtx=s?1:0,r.usedtx=s?1:0),void 0!==o&&(r.maxplaybackrate=o),void 0!==c&&(r.maxaveragebitrate=c),void 0!==l&&(m.parameters.ptime=l,r.ptime=l),u||(m.rtcpFeedback=m.rtcpFeedback.filter(e=>"nack"!==e.type||e.parameter),i=i.filter(e=>"nack"!==e.type||e.parameter));break;case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":void 0!==p&&(r["x-google-start-bitrate"]=p),void 0!==h&&(r["x-google-max-bitrate"]=h),void 0!==f&&(r["x-google-min-bitrate"]=f)}}const n={payload:e.payloadType,config:""};for(const e of Object.keys(r))n.config&&(n.config+=";"),n.config+=`${e}=${r[e]}`;n.config&&this._mediaObject.fmtp.push(n);for(const t of i)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions){(o.ext??[]).some(t=>t.uri===e.uri)&&this._mediaObject.ext.push({uri:e.uri,value:e.id})}if(l&&"extmap-allow-mixed"===o.extmapAllowMixed&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(const e of o.rids??[])"send"===e.direction&&this._mediaObject.rids.push({id:e.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize",this._planB&&"video"===this._mediaObject.type&&(this._mediaObject.xGoogleFlag="conference");break;case"application":"number"==typeof o.sctpPort?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize})}}setDtlsRole(e){switch(e){case"client":this._mediaObject.setup="active";break;case"server":this._mediaObject.setup="passive";break;case"auto":this._mediaObject.setup="actpass"}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;const t={};for(const r of e)r.rid&&(t[r.rid]=r);const r=this._mediaObject.simulcast.list1,i=Va.parseSimulcastStreamList(r);for(const e of i)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=i.map(e=>e.map(e=>`${e.paused?"~":""}${e.scid}`).join(",")).join(";")}};function Ga(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}Na.OfferMediaSection=class extends $a{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1,mid:o,kind:a,offerRtpParameters:c,streamId:d,trackId:l,oldDataChannelSpec:u=!1}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:s}),this._mediaObject.mid=String(o),this._mediaObject.type=a,n?(this._mediaObject.connection={ip:n.ip,version:n.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=n.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=i?"UDP/DTLS/SCTP":"UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._planB||(this._mediaObject.msid=`${d??"-"} ${l}`);for(const e of c.codecs){const t={payload:e.payloadType,codec:Ga(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r={payload:e.payloadType,config:""};for(const t of Object.keys(e.parameters))r.config&&(r.config+=";"),r.config+=`${t}=${e.parameters[t]}`;r.config&&this._mediaObject.fmtp.push(r);for(const t of e.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:e.payloadType,type:t.type,subtype:t.parameter})}this._mediaObject.payloads=c.codecs.map(e=>e.payloadType).join(" "),this._mediaObject.ext=[];for(const e of c.headerExtensions)this._mediaObject.ext.push({uri:e.uri,value:e.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";const e=c.encodings[0],t=e.ssrc,r=e.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],c.rtcp.cname&&this._mediaObject.ssrcs.push({id:t,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:t,attribute:"msid",value:`${d??"-"} ${l}`}),r&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:r,attribute:"cname",value:c.rtcp.cname}),this._planB&&this._mediaObject.ssrcs.push({id:r,attribute:"msid",value:`${d??"-"} ${l}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${t} ${r}`}));break}case"application":u?(this._mediaObject.payloads=i.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:i.port,maxMessageSize:i.maxMessageSize}):(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=i.port,this._mediaObject.maxMessageSize=i.maxMessageSize)}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}planBReceive({offerRtpParameters:e,streamId:t,trackId:r}){const i=e.encodings[0],n=i.ssrc,s=i.rtx?.ssrc,o=this._mediaObject.payloads.split(" ");for(const t of e.codecs){if(o.includes(String(t.payloadType)))continue;const e={payload:t.payloadType,codec:Ga(t),rate:t.clockRate};t.channels>1&&(e.encoding=t.channels),this._mediaObject.rtp.push(e);const r={payload:t.payloadType,config:""};for(const e of Object.keys(t.parameters))r.config&&(r.config+=";"),r.config+=`${e}=${t.parameters[e]}`;r.config&&this._mediaObject.fmtp.push(r);for(const e of t.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:t.payloadType,type:e.type,subtype:e.parameter})}this._mediaObject.payloads+=` ${e.codecs.filter(e=>!this._mediaObject.payloads.includes(e.payloadType)).map(e=>e.payloadType).join(" ")}`,this._mediaObject.payloads=this._mediaObject.payloads.trim(),e.rtcp.cname&&this._mediaObject.ssrcs.push({id:n,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:n,attribute:"msid",value:`${t??"-"} ${r}`}),s&&(e.rtcp.cname&&this._mediaObject.ssrcs.push({id:s,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:s,attribute:"msid",value:`${t??"-"} ${r}`}),this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${n} ${s}`}))}planBStopReceiving({offerRtpParameters:e}){const t=e.encodings[0],r=t.ssrc,i=t.rtx?.ssrc;this._mediaObject.ssrcs=this._mediaObject.ssrcs.filter(e=>e.id!==r&&e.id!==i),i&&(this._mediaObject.ssrcGroups=this._mediaObject.ssrcGroups.filter(e=>e.ssrcs!==`${r} ${i}`))}};var qa=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Ha=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Wa=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&qa(r,t,i[n]);return Ha(r,t),r}}();Object.defineProperty(Aa,"__esModule",{value:!0});var Ka=Aa.RemoteSdp=void 0;const Ja=Wa(gi),Qa=Na,Xa=new ts.Logger("RemoteSdp");Ka=Aa.RemoteSdp=class{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:i,plainRtpParameters:n,planB:s=!1}){if(this._mediaSections=[],this._midToIndex=new Map,this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=i,this._plainRtpParameters=n,this._planB=s,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:1e4,sessionVersion:0,username:"mediasoup-client"},name:"-",timing:{start:0,stop:0},media:[]},e?.iceLite&&(this._sdpObject.icelite="ice-lite"),r){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};const e=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:r.fingerprints[e-1].algorithm,hash:r.fingerprints[e-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}n&&(this._sdpObject.origin.address=n.ip,this._sdpObject.origin.ipVer=n.ipVersion)}updateIceParameters(e){Xa.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(const t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Xa.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(const t of this._mediaSections)t.setDtlsRole(e)}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){const t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s=!1}){const o=new Qa.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:i,codecOptions:n,extmapAllowMixed:s});t?this._replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this._replaceMediaSection(o):this._addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n}){const s=this._midToIndex.get(e);let o;if(void 0!==s&&(o=this._mediaSections[s]),o)o.planBReceive({offerRtpParameters:r,streamId:i,trackId:n}),this._replaceMediaSection(o);else{o=new Qa.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,mid:e,kind:t,offerRtpParameters:r,streamId:i,trackId:n});const s=this._mediaSections.find(e=>e.closed);s?this._replaceMediaSection(o,s.mid):this._addMediaSection(o)}}pauseMediaSection(e){this._findMediaSection(e).pause()}resumeSendingMediaSection(e){this._findMediaSection(e).resume()}resumeReceivingMediaSection(e){this._findMediaSection(e).resume()}disableMediaSection(e){this._findMediaSection(e).disable()}closeMediaSection(e){const t=this._findMediaSection(e);return e===this._firstMid?(Xa.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this._regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){const r=this._findMediaSection(e);r.muxSimulcastStreams(t),this._replaceMediaSection(r)}planBStopReceiving({mid:e,offerRtpParameters:t}){const r=this._findMediaSection(e);r.planBStopReceiving({offerRtpParameters:t}),this._replaceMediaSection(r)}sendSctpAssociation({offerMediaObject:e}){const t=new Qa.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this._addMediaSection(t)}receiveSctpAssociation({oldDataChannelSpec:e=!1}={}){const t=new Qa.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application",oldDataChannelSpec:e});this._addMediaSection(t)}getSdp(){return this._sdpObject.origin.sessionVersion++,Ja.write(this._sdpObject)}_addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this._regenerateBundleMids()}_replaceMediaSection(e,t){if("string"==typeof t){const r=this._midToIndex.get(t);if(void 0===r)throw new Error(`no media section found for reuseMid '${t}'`);const i=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(i.mid),this._midToIndex.set(e.mid,r),this._sdpObject.media[r]=e.getObject(),this._regenerateBundleMids()}else{const t=this._midToIndex.get(e.mid);if(void 0===t)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[t]=e,this._sdpObject.media[t]=e.getObject()}}_findMediaSection(e){const t=this._midToIndex.get(e);if(void 0===t)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}_regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};var Ya={};Object.defineProperty(Ya,"__esModule",{value:!0});var Za=Ya.parse=function(e){const t=ec.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const ec=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var tc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),rc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ic=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&tc(r,t,i[n]);return rc(r,t),r}}();Object.defineProperty(ya,"__esModule",{value:!0}),ya.Chrome111=void 0;const nc=ic(gi),sc=ts,oc=ic(xs),ac=ic(Ms),cc=ic(wa),dc=ic(Ea),lc=ic(Da),uc=Ps,pc=Ia,hc=Aa,fc=Ya,mc=new sc.Logger("Chrome111"),gc={OS:1024,MIS:1024};class vc extends pc.HandlerInterface{static createFactory(){return()=>new vc}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome111"}close(){if(mc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){mc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=nc.parse(t.sdp),i=cc.extractRtpCapabilities({sdpObject:r});return lc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return mc.debug("getNativeSctpCapabilities()"),{numStreams:gc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),mc.debug("run()"),this._direction=e,this._remoteSdp=new hc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:ac.getSendingRtpParameters("audio",d),video:ac.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:ac.getSendingRemoteRtpParameters("audio",d),video:ac.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):(mc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),mc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),mc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});mc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();mc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){if(this.assertNotClosed(),this.assertSendDirection(),mc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1){let e=1;for(const r of t){const t=r.scalabilityMode?(0,fc.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`})}const s=oc.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=ac.reduceCodecs(s.codecs,i);const o=oc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=ac.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);const d=await this._pc.createOffer();let l=nc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),mc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const u=c.mid;s.mid=u,l=nc.parse(this._pc.localDescription.sdp);const p=l.media[a.idx];if(s.rtcp.cname=cc.getCname({offerMediaObject:p}),t)if(1===t.length){const e=dc.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=dc.getRtpEncodings({offerMediaObject:p});this._remoteSdp.send({offerMediaObject:p,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return mc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,c),{localId:u,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),mc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();mc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),mc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();mc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),mc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();mc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?mc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):mc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),mc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();mc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),mc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();mc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};mc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%gc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=nc.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),mc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};mc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;mc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=nc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);cc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:nc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),mc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){mc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){mc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){mc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();mc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};mc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=nc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=nc.parse(this._pc.localDescription.sdp));const r=cc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new uc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}ya.Chrome111=vc;var bc={},yc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),wc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),_c=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&yc(r,t,i[n]);return wc(r,t),r}}();Object.defineProperty(bc,"__esModule",{value:!0}),bc.Chrome74=void 0;const Sc=_c(gi),Cc=ts,Rc=_c(xs),kc=_c(Ms),Tc=_c(wa),Pc=_c(Ea),Oc=_c(Da),Ec=Ps,Dc=Ia,xc=Aa,Ic=Ya,Mc=new Cc.Logger("Chrome74"),jc={OS:1024,MIS:1024};class Lc extends Dc.HandlerInterface{static createFactory(){return()=>new Lc}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome74"}close(){if(Mc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Mc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=Sc.parse(t.sdp),i=Tc.extractRtpCapabilities({sdpObject:r});return Oc.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Mc.debug("getNativeSctpCapabilities()"),{numStreams:jc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Mc.debug("run()"),this._direction=e,this._remoteSdp=new xc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:kc.getSendingRtpParameters("audio",d),video:kc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:kc.getSendingRemoteRtpParameters("audio",d),video:kc.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):(Mc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}))}async updateIceServers(e){this.assertNotClosed(),Mc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Mc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Mc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Mc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const n=Rc.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=kc.reduceCodecs(n.codecs,i);const s=Rc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=kc.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});let c,d=await this._pc.createOffer(),l=Sc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let u=!1;const p=(0,Ic.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(Mc.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=Sc.parse(d.sdp),c=l.media[o.idx],Pc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:Sc.write(l)}),Mc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const h=a.mid;if(n.mid=h,l=Sc.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=Tc.getCname({offerMediaObject:c}),t)if(1===t.length){let e=Pc.getRtpEncodings({offerMediaObject:c});Object.assign(e[0],t[0]),u&&(e=[e[0]]),n.encodings=e}else n.encodings=t;else n.encodings=Pc.getRtpEncodings({offerMediaObject:c});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Mc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Mc.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Mc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Mc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Mc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Mc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Mc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Mc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Mc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Mc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Mc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%jc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Sc.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Mc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Mc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Mc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Sc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);Tc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:Sc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Mc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Mc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mc.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mc.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Mc.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Mc.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Mc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Sc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Mc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Sc.parse(this._pc.localDescription.sdp));const r=Tc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ec.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}bc.Chrome74=Lc;var Ac={},Nc=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Bc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Fc=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Nc(r,t,i[n]);return Bc(r,t),r}}();Object.defineProperty(Ac,"__esModule",{value:!0}),Ac.Chrome70=void 0;const zc=Fc(gi),Vc=ts,Uc=Fc(xs),$c=Fc(Ms),Gc=Fc(wa),qc=Fc(Ea),Hc=Ia,Wc=Aa,Kc=Ya,Jc=new Vc.Logger("Chrome70"),Qc={OS:1024,MIS:1024};class Xc extends Hc.HandlerInterface{static createFactory(){return()=>new Xc}constructor(){super(),this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome70"}close(){if(Jc.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Jc.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=zc.parse(t.sdp);return Gc.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Jc.debug("getNativeSctpCapabilities()"),{numStreams:Qc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Jc.debug("run()"),this._direction=e,this._remoteSdp=new Wc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:$c.getSendingRtpParameters("audio",d),video:$c.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:$c.getSendingRemoteRtpParameters("audio",d),video:$c.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Jc.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Jc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Jc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Jc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Jc.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Jc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const n=Uc.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=$c.reduceCodecs(n.codecs,i);const s=Uc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=$c.reduceCodecs(s.codecs,i);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let c,d=await this._pc.createOffer(),l=zc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),t&&t.length>1&&(Jc.debug("send() | enabling legacy simulcast"),l=zc.parse(d.sdp),c=l.media[o.idx],qc.addLegacySimulcast({offerMediaObject:c,numStreams:t.length}),d={type:"offer",sdp:zc.write(l)});let u=!1;const p=(0,Kc.parse)((t??[{}])[0].scalabilityMode);if(t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===n.codecs[0].mimeType.toLowerCase()&&(Jc.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=zc.parse(d.sdp),c=l.media[o.idx],qc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:zc.write(l)}),Jc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d),t){Jc.debug("send() | applying given encodings");const e=a.sender.getParameters();for(let r=0;r<(e.encodings??[]).length;++r){const i=e.encodings[r],n=t[r];if(!n)break;e.encodings[r]=Object.assign(i,n)}await a.sender.setParameters(e)}const h=a.mid;if(n.mid=h,l=zc.parse(this._pc.localDescription.sdp),c=l.media[o.idx],n.rtcp.cname=Gc.getCname({offerMediaObject:c}),n.encodings=qc.getRtpEncodings({offerMediaObject:c}),t)for(let e=0;e<n.encodings.length;++e)t[e]&&Object.assign(n.encodings[e],t[e]);if(u&&(n.encodings=[n.encodings[0]]),n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Jc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:n,rtpSender:a.sender}}async stopSending(e){this.assertSendDirection(),Jc.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Jc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Jc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Jc.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),Jc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Jc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Jc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Jc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Jc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Qc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=zc.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Jc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Jc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Jc.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=zc.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);Gc.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:zc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Jc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Jc.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Jc.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Jc.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Jc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=zc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Jc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=zc.parse(this._pc.localDescription.sdp));const r=Gc.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Ac.Chrome70=Xc;var Yc={},Zc={};Object.defineProperty(Zc,"__esModule",{value:!0}),Zc.getRtpEncodings=function({offerMediaObject:e,track:t}){const r=new Set;for(const i of e.ssrcs||[]){if("msid"!==i.attribute)continue;if(i.value.split(" ")[1]===t.id){const e=i.id;r.add(e)}}if(0===r.size)throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);const i=new Map;for(const t of e.ssrcGroups||[]){if("FID"!==t.semantics)continue;let[e,n]=t.ssrcs.split(/\s+/);e=Number(e),n=Number(n),r.has(e)&&(r.delete(e),r.delete(n),i.set(e,n))}for(const e of r)i.set(e,null);const n=[];for(const[e,t]of i){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},Zc.addLegacySimulcast=function({offerMediaObject:e,track:t,numStreams:r}){if(r<=1)throw new TypeError("numStreams must be greater than 1");let i,n,s;if(!(e.ssrcs||[]).find(e=>{if("msid"!==e.attribute)return!1;return e.value.split(" ")[1]===t.id&&(i=e.id,s=e.value.split(" ")[0],!0)}))throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);(e.ssrcGroups||[]).some(e=>{if("FID"!==e.semantics)return!1;const t=e.ssrcs.split(/\s+/);return Number(t[0])===i&&(n=Number(t[1]),!0)});const o=e.ssrcs.find(e=>"cname"===e.attribute&&e.id===i);if(!o)throw new Error(`a=ssrc line with cname information not found [track.id:${t.id}]`);const a=o.value,c=[],d=[];for(let e=0;e<r;++e)c.push(i+e),n&&d.push(n+e);e.ssrcGroups=e.ssrcGroups||[],e.ssrcs=e.ssrcs||[],e.ssrcGroups.push({semantics:"SIM",ssrcs:c.join(" ")});for(const r of c)e.ssrcs.push({id:r,attribute:"cname",value:a}),e.ssrcs.push({id:r,attribute:"msid",value:`${s} ${t.id}`});for(let r=0;r<d.length;++r){const i=c[r],n=d[r];e.ssrcs.push({id:n,attribute:"cname",value:a}),e.ssrcs.push({id:n,attribute:"msid",value:`${s} ${t.id}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${i} ${n}`})}};var ed=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),td=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),rd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ed(r,t,i[n]);return td(r,t),r}}();Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.Chrome67=void 0;const id=rd(gi),nd=ts,sd=rd(xs),od=rd(Ms),ad=rd(wa),cd=rd(Zc),dd=Ia,ld=Aa,ud=new nd.Logger("Chrome67"),pd={OS:1024,MIS:1024};class hd extends dd.HandlerInterface{static createFactory(){return()=>new hd}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome67"}close(){if(ud.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){ud.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=id.parse(t.sdp);return ad.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return ud.debug("getNativeSctpCapabilities()"),{numStreams:pd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){ud.debug("run()"),this._direction=e,this._remoteSdp=new ld.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:od.getSendingRtpParameters("audio",d),video:od.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:od.getSendingRemoteRtpParameters("audio",d),video:od.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(ud.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){ud.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(ud.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ud.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ud.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),ud.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&ud.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=id.parse(s.sdp);const a=sd.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=od.reduceCodecs(a.codecs);const c=sd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=od.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(ud.debug("send() | enabling simulcast"),o=id.parse(s.sdp),n=o.media.find(e=>"video"===e.type),cd.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:id.write(o)}),ud.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=id.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=ad.getCname({offerMediaObject:n}),a.encodings=cd.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find(t=>t.track===e);return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection(),ud.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");this._pc.removeTrack(t),t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();ud.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void ud.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?ud.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ud.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),ud.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),ud.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};ud.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%pd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=id.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),ud.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};ud.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;ud.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=id.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find(e=>String(e.mid)===i);ad.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:id.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),ud.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=i,o=e,a=this._pc.getReceivers().find(e=>e.track&&e.track.id===s);if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(s,{mid:o,rtpParameters:n,rtpReceiver:a}),t.push({localId:s,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){ud.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ud.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};ud.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};ud.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=id.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}ud.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=id.parse(this._pc.localDescription.sdp));const r=ad.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Yc.Chrome67=hd;var fd={},md=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),gd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),vd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&md(r,t,i[n]);return gd(r,t),r}}();Object.defineProperty(fd,"__esModule",{value:!0}),fd.Chrome55=void 0;const bd=vd(gi),yd=ts,wd=Ps,_d=vd(xs),Sd=vd(Ms),Cd=vd(wa),Rd=vd(Zc),kd=Ia,Td=Aa,Pd=new yd.Logger("Chrome55"),Od={OS:1024,MIS:1024};class Ed extends kd.HandlerInterface{static createFactory(){return()=>new Ed}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Chrome55"}close(){if(Pd.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Pd.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=bd.parse(t.sdp);return Cd.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Pd.debug("getNativeSctpCapabilities()"),{numStreams:Od}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Pd.debug("run()"),this._direction=e,this._remoteSdp=new Td.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Sd.getSendingRtpParameters("audio",d),video:Sd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Sd.getSendingRemoteRtpParameters("audio",d),video:Sd.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Pd.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Pd.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Pd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Pd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Pd.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Pd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Pd.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=bd.parse(s.sdp);const a=_d.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Sd.reduceCodecs(a.codecs);const c=_d.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Sd.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Pd.debug("send() | enabling simulcast"),o=bd.parse(s.sdp),n=o.media.find(e=>"video"===e.type),Rd.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:bd.write(o)}),Pd.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=bd.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=Cd.getCname({offerMediaObject:n}),a.encodings=Rd.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),Pd.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();Pd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Pd.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new wd.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new wd.UnsupportedError(" not implemented")}async setRtpEncodingParameters(e,t){throw new wd.UnsupportedError("not supported")}async getSenderStats(e){throw new wd.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Pd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Od.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=bd.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Pd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Pd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Pd.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=bd.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find(e=>String(e.mid)===i);Cd.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:bd.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Pd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=r.streamId??n.rtcp.cname,c=this._pc.getRemoteStreams().find(e=>e.id===a).getTrackById(o);if(!c)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n}),t.push({localId:o,track:c})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Pd.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Pd.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new wd.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Pd.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Pd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=bd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Pd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=bd.parse(this._pc.localDescription.sdp));const r=Cd.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}fd.Chrome55=Ed;var Dd={},xd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Id=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Md=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&xd(r,t,i[n]);return Id(r,t),r}}();Object.defineProperty(Dd,"__esModule",{value:!0}),Dd.Firefox120=void 0;const jd=Md(gi),Ld=ts,Ad=Ps,Nd=Md(xs),Bd=Md(Ms),Fd=Md(wa),zd=Md(Ea),Vd=Ia,Ud=Aa,$d=Ya,Gd=new Ld.Logger("Firefox120"),qd={OS:16,MIS:2048};class Hd extends Vd.HandlerInterface{static createFactory(){return()=>new Hd}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox120"}close(){if(Gd.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Gd.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"}),e.addTransceiver(r,{direction:"sendrecv",sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});const i=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const n=jd.parse(i.sdp);return Fd.extractRtpCapabilities({sdpObject:n})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return Gd.debug("getNativeSctpCapabilities()"),{numStreams:qd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Gd.debug("run()"),this._direction=e,this._remoteSdp=new Ud.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:Bd.getSendingRtpParameters("audio",d),video:Bd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Bd.getSendingRemoteRtpParameters("audio",d),video:Bd.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Gd.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){throw this.assertNotClosed(),new Ad.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Gd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Gd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Gd.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=Nd.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Bd.reduceCodecs(s.codecs,i);const o=Nd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Bd.reduceCodecs(o.codecs,i);const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(a.sender);const c=await this._pc.createOffer();let d=jd.parse(c.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});const l=(0,$d.parse)((t??[{}])[0].scalabilityMode);Gd.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);const u=a.mid;s.mid=u,d=jd.parse(this._pc.localDescription.sdp);const p=d.media[d.media.length-1];if(s.rtcp.cname=Fd.getCname({offerMediaObject:p}),t)if(1===t.length){const e=zd.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=zd.getRtpEncodings({offerMediaObject:p});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${l.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:p,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const h={type:"answer",sdp:this._remoteSdp.getSdp()};return Gd.debug("send() | calling pc.setRemoteDescription() [answer:%o]",h),await this._pc.setRemoteDescription(h),this._mapMidTransceiver.set(u,a),{localId:u,rtpParameters:s,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Gd.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();Gd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Gd.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Gd.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Gd.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Gd.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Gd.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Gd.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Gd.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Gd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%qd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=jd.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Gd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Gd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Gd.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=jd.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find(e=>String(e.mid)===o);Fd.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:jd.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Gd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Gd.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Gd.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Gd.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Gd.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Gd.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Gd.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Gd.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Gd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=jd.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Gd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=jd.parse(this._pc.localDescription.sdp));const r=Fd.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Ad.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Dd.Firefox120=Hd;var Wd={},Kd=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Jd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Qd=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Kd(r,t,i[n]);return Jd(r,t),r}}();Object.defineProperty(Wd,"__esModule",{value:!0}),Wd.Firefox60=void 0;const Xd=Qd(gi),Yd=ts,Zd=Ps,el=Qd(xs),tl=Qd(Ms),rl=Qd(wa),il=Qd(Ea),nl=Ia,sl=Aa,ol=Ya,al=new Yd.Logger("Firefox60"),cl={OS:16,MIS:2048};class dl extends nl.HandlerInterface{static createFactory(){return()=>new dl}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Firefox60"}close(){if(al.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){al.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),t=document.createElement("canvas");t.getContext("2d");const r=t.captureStream().getVideoTracks()[0];try{e.addTransceiver("audio",{direction:"sendrecv"});const i=e.addTransceiver(r,{direction:"sendrecv"}),n=i.sender.getParameters(),s=[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}];n.encodings=s,await i.sender.setParameters(n);const o=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const a=Xd.parse(o.sdp);return rl.extractRtpCapabilities({sdpObject:a})}catch(i){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw i}}async getNativeSctpCapabilities(){return al.debug("getNativeSctpCapabilities()"),{numStreams:cl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),al.debug("run()"),this._direction=e,this._remoteSdp=new sl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:tl.getSendingRtpParameters("audio",d),video:tl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:tl.getSendingRemoteRtpParameters("audio",d),video:tl.getSendingRemoteRtpParameters("video",d)},this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(al.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){throw this.assertNotClosed(),new Zd.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),al.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});al.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();al.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertNotClosed(),this.assertSendDirection(),al.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&((t=el.clone(t)).forEach((e,t)=>{e.rid=`r${t}`}),t.reverse());const n=el.clone(this._sendingRtpParametersByKind[e.kind]);n.codecs=tl.reduceCodecs(n.codecs,i);const s=el.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=tl.reduceCodecs(s.codecs,i);const o=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});if(t){const e=o.sender.getParameters();e.encodings=t,await o.sender.setParameters(e)}const a=await this._pc.createOffer();let c=Xd.parse(a.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const d=(0,ol.parse)((t??[{}])[0].scalabilityMode);al.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const l=o.mid;n.mid=l,c=Xd.parse(this._pc.localDescription.sdp);const u=c.media[c.media.length-1];if(n.rtcp.cname=rl.getCname({offerMediaObject:u}),t)if(1===t.length){const e=il.getRtpEncodings({offerMediaObject:u});Object.assign(e[0],t[0]),n.encodings=e}else n.encodings=t.reverse();else n.encodings=il.getRtpEncodings({offerMediaObject:u});if(n.encodings.length>1&&("video/vp8"===n.codecs[0].mimeType.toLowerCase()||"video/h264"===n.codecs[0].mimeType.toLowerCase()))for(const e of n.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${d.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:u,offerRtpParameters:n,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const p={type:"answer",sdp:this._remoteSdp.getSdp()};return al.debug("send() | calling pc.setRemoteDescription() [answer:%o]",p),await this._pc.setRemoteDescription(p),this._mapMidTransceiver.set(l,o),{localId:l,rtpParameters:n,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),al.debug("stopSending() [localId:%s]",e),this._closed)return;const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);const r=await this._pc.createOffer();al.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),al.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();al.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),al.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();al.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?al.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):al.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),al.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const i=r.sender.getParameters();t=i.encodings.length-1-t,i.encodings.forEach((e,r)=>{e.active=r>=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();al.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),al.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();al.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};al.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%cl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Xd.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),al.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};al.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;al.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Xd.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,o=r.get(e),a=s.media.find(e=>String(e.mid)===o);rl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:a}),n={type:"answer",sdp:Xd.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),al.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){al.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();al.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){al.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();al.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){al.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();al.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};al.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};al.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Xd.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}al.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Xd.parse(this._pc.localDescription.sdp));const r=rl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Zd.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}Wd.Firefox60=dl;var ll={},ul=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),pl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),hl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&ul(r,t,i[n]);return pl(r,t),r}}();Object.defineProperty(ll,"__esModule",{value:!0});var fl=ll.Safari12=void 0;const ml=hl(gi),gl=ts,vl=hl(xs),bl=hl(Ms),yl=hl(wa),wl=hl(Ea),_l=hl(Da),Sl=Ps,Cl=Ia,Rl=Aa,kl=Ya,Tl=new gl.Logger("Safari12"),Pl={OS:1024,MIS:1024};class Ol extends Cl.HandlerInterface{static createFactory(){return()=>new Ol}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari12"}close(){if(Tl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Tl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=ml.parse(t.sdp),i=yl.extractRtpCapabilities({sdpObject:r});return _l.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Tl.debug("getNativeSctpCapabilities()"),{numStreams:Pl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Tl.debug("run()"),this._direction=e,this._remoteSdp=new Rl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:bl.getSendingRtpParameters("audio",d),video:bl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:bl.getSendingRemoteRtpParameters("audio",d),video:bl.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Tl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){this.assertNotClosed(),Tl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Tl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Tl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Tl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=vl.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=bl.reduceCodecs(s.codecs,i);const o=vl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=bl.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=ml.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const p=(0,kl.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(Tl.debug("send() | enabling legacy simulcast"),u=ml.parse(l.sdp),d=u.media[a.idx],wl.addLegacySimulcast({offerMediaObject:d,numStreams:t.length}),l={type:"offer",sdp:ml.write(u)}),Tl.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);const h=c.mid;if(s.mid=h,u=ml.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=yl.getCname({offerMediaObject:d}),s.encodings=wl.getRtpEncodings({offerMediaObject:d}),t)for(let e=0;e<s.encodings.length;++e)t[e]&&Object.assign(s.encodings[e],t[e]);if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Tl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,c),{localId:h,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Tl.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Tl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Tl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=await this._pc.createOffer();Tl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Tl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Tl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Tl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Tl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Tl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Tl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Pl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=ml.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Tl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Tl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Tl.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=ml.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);yl.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:ml.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Tl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Tl.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Tl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Tl.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Tl.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Tl.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Tl.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Tl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Tl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=ml.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Tl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ml.parse(this._pc.localDescription.sdp));const r=yl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Sl.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}fl=ll.Safari12=Ol;var El={},Dl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),xl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Il=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Dl(r,t,i[n]);return xl(r,t),r}}();Object.defineProperty(El,"__esModule",{value:!0}),El.Safari11=void 0;const Ml=Il(gi),jl=ts,Ll=Il(xs),Al=Il(Ms),Nl=Il(wa),Bl=Il(Zc),Fl=Ia,zl=Aa,Vl=new jl.Logger("Safari11"),Ul={OS:1024,MIS:1024};class $l extends Fl.HandlerInterface{static createFactory(){return()=>new $l}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdRtpSender=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari11"}close(){if(Vl.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Vl.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Ml.parse(t.sdp);return Nl.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Vl.debug("getNativeSctpCapabilities()"),{numStreams:Ul}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Vl.debug("run()"),this._direction=e,this._remoteSdp=new zl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Al.getSendingRtpParameters("audio",d),video:Al.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Al.getSendingRemoteRtpParameters("audio",d),video:Al.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Vl.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Vl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Vl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Vl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Vl.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Vl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Vl.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let n,s=await this._pc.createOffer(),o=Ml.parse(s.sdp);const a=Ll.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Al.reduceCodecs(a.codecs);const c=Ll.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Al.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Vl.debug("send() | enabling simulcast"),o=Ml.parse(s.sdp),n=o.media.find(e=>"video"===e.type),Bl.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Ml.write(o)}),Vl.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Ml.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=Nl.getCname({offerMediaObject:n}),a.encodings=Bl.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&"video/vp8"===a.codecs[0].mimeType.toLowerCase())for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);this._nextSendLocalId++;const u=this._pc.getSenders().find(t=>t.track===e);return this._mapSendLocalIdRtpSender.set(l,u),{localId:l,rtpParameters:a,rtpSender:u}}async stopSending(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");t.track&&this._sendStream.removeTrack(t.track),this._mapSendLocalIdRtpSender.delete(e);const r=await this._pc.createOffer();Vl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Vl.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Vl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Vl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.track;await r.replaceTrack(t),i&&this._sendStream.removeTrack(i),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),Vl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.setParameters(i)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Vl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.setParameters(i)}async getSenderStats(e){this.assertSendDirection();const t=this._mapSendLocalIdRtpSender.get(e);if(!t)throw new Error("associated RTCRtpSender not found");return t.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Vl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ul.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ml.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Vl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Vl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[];for(const t of e){const{trackId:e,kind:r,rtpParameters:i,streamId:n}=t;Vl.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:i,streamId:n??i.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let i=await this._pc.createAnswer();const n=Ml.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,s=n.media.find(e=>String(e.mid)===i);Nl.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}i={type:"answer",sdp:Ml.write(n)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:n}),Vl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const r of e){const{kind:e,trackId:i,rtpParameters:n}=r,s=e,o=i,a=this._pc.getReceivers().find(e=>e.track&&e.track.id===o);if(!a)throw new Error("new RTCRtpReceiver not");this._mapRecvLocalIdInfo.set(o,{mid:s,rtpParameters:n,rtpReceiver:a}),t.push({localId:o,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Vl.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Vl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertRecvDirection();const{rtpReceiver:t}=this._mapRecvLocalIdInfo.get(e)??{};if(!t)throw new Error("associated RTCRtpReceiver not found");return t.getStats()}async pauseReceiving(e){}async resumeReceiving(e){}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Vl.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Vl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ml.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Vl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Ml.parse(this._pc.localDescription.sdp));const r=Nl.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}El.Safari11=$l;var Gl={},ql={},Hl=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Wl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Kl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Hl(r,t,i[n]);return Wl(r,t),r}}();Object.defineProperty(ql,"__esModule",{value:!0}),ql.getCapabilities=function(){const e=RTCRtpReceiver.getCapabilities(),t=Jl.clone(e);for(const e of t.codecs??[]){if(e.channels=e.numChannels,delete e.numChannels,e.mimeType=e.mimeType??`${e.kind}/${e.name}`,e.parameters){const t=e.parameters;t.apt&&(t.apt=Number(t.apt)),t["packetization-mode"]&&(t["packetization-mode"]=Number(t["packetization-mode"]))}for(const t of e.rtcpFeedback??[])t.parameter||(t.parameter="")}return t},ql.mangleRtpParameters=function(e){const t=Jl.clone(e);t.mid&&(t.muxId=t.mid,delete t.mid);for(const e of t.codecs)e.channels&&(e.numChannels=e.channels,delete e.channels),e.mimeType&&!e.name&&(e.name=e.mimeType.split("/")[1]),delete e.mimeType;return t};const Jl=Kl(xs);var Ql=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Xl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Yl=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Ql(r,t,i[n]);return Xl(r,t),r}}();Object.defineProperty(Gl,"__esModule",{value:!0}),Gl.Edge11=void 0;const Zl=ts,eu=Ps,tu=Yl(xs),ru=Yl(Ms),iu=Yl(ql),nu=Ia,su=new Zl.Logger("Edge11");class ou extends nu.HandlerInterface{static createFactory(){return()=>new ou}constructor(){super(),this._rtpSenders=new Map,this._rtpReceivers=new Map,this._nextSendLocalId=0,this._transportReady=!1}get name(){return"Edge11"}close(){su.debug("close()");try{this._iceGatherer.close()}catch(e){}try{this._iceTransport.stop()}catch(e){}try{this._dtlsTransport.stop()}catch(e){}for(const e of this._rtpSenders.values())try{e.stop()}catch(e){}for(const e of this._rtpReceivers.values())try{e.stop()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){return su.debug("getNativeRtpCapabilities()"),iu.getCapabilities()}async getNativeSctpCapabilities(){return su.debug("getNativeSctpCapabilities()"),{numStreams:{OS:0,MIS:0}}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){su.debug("run()"),this._sendingRtpParametersByKind={audio:ru.getSendingRtpParameters("audio",d),video:ru.getSendingRtpParameters("video",d)},this._remoteIceParameters=t,this._remoteIceCandidates=r,this._remoteDtlsParameters=i,this._cname=`CNAME-${tu.generateRandomNumber()}`,this.setIceGatherer({iceServers:s,iceTransportPolicy:o}),this.setIceTransport(),this.setDtlsTransport()}async updateIceServers(e){throw new eu.UnsupportedError("not supported")}async restartIce(e){if(su.debug("restartIce()"),this._remoteIceParameters=e,this._transportReady){su.debug("restartIce() | calling iceTransport.start()"),this._iceTransport.start(this._iceGatherer,e,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({})}}async getTransportStats(){return this._iceTransport.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){su.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),su.debug("send() | calling new RTCRtpSender()");const n=new RTCRtpSender(e,this._dtlsTransport),s=tu.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=ru.reduceCodecs(s.codecs,i);const o=s.codecs.some(e=>/.+\/rtx$/i.test(e.mimeType));t||(t=[{}]);for(const e of t)e.ssrc=tu.generateRandomNumber(),o&&(e.rtx={ssrc:tu.generateRandomNumber()});s.encodings=t,s.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const a=iu.mangleRtpParameters(s);su.debug("send() | calling rtpSender.send() [params:%o]",a),await n.send(a);const c=String(this._nextSendLocalId);return this._nextSendLocalId++,this._rtpSenders.set(c,n),{localId:c,rtpParameters:s,rtpSender:n}}async stopSending(e){su.debug("stopSending() [localId:%s]",e);const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");this._rtpSenders.delete(e);try{su.debug("stopSending() | calling rtpSender.stop()"),t.stop()}catch(e){throw su.warn("stopSending() | rtpSender.stop() failed:%o",e),e}}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){t?su.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):su.debug("replaceTrack() [localId:%s, no track]",e);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");r.setTrack(t)}async setMaxSpatialLayer(e,t){su.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.setParameters(i)}async setRtpEncodingParameters(e,t){su.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const i=r.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.setParameters(i)}async getSenderStats(e){const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");return t.getStats()}async sendDataChannel(e){throw new eu.UnsupportedError("not implemented")}async receive(e){const t=[];for(const t of e){const{trackId:e,kind:r}=t;su.debug("receive() [trackId:%s, kind:%s]",e,r)}this._transportReady||await this.setupTransport({localDtlsRole:"server"});for(const r of e){const{trackId:e,kind:i,rtpParameters:n}=r;su.debug("receive() | calling new RTCRtpReceiver()");const s=new RTCRtpReceiver(this._dtlsTransport,i);s.addEventListener("error",e=>{su.error('rtpReceiver "error" event [event:%o]',e)});const o=iu.mangleRtpParameters(n);su.debug("receive() | calling rtpReceiver.receive() [params:%o]",o),await s.receive(o);const a=e;this._rtpReceivers.set(a,s),t.push({localId:a,track:s.track,rtpReceiver:s})}return t}async stopReceiving(e){for(const t of e){su.debug("stopReceiving() [localId:%s]",t);const e=this._rtpReceivers.get(t);if(!e)throw new Error("RTCRtpReceiver not found");this._rtpReceivers.delete(t);try{su.debug("stopReceiving() | calling rtpReceiver.stop()"),e.stop()}catch(e){su.warn("stopReceiving() | rtpReceiver.stop() failed:%o",e)}}}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){const t=this._rtpReceivers.get(e);if(!t)throw new Error("RTCRtpReceiver not found");return t.getStats()}async receiveDataChannel(e){throw new eu.UnsupportedError("not implemented")}setIceGatherer({iceServers:e,iceTransportPolicy:t}){const r=new RTCIceGatherer({iceServers:e??[],gatherPolicy:t??"all"});r.addEventListener("error",e=>{su.error('iceGatherer "error" event [event:%o]',e)});try{r.gather()}catch(e){su.debug("setIceGatherer() | iceGatherer.gather() failed: %s",e.toString())}this._iceGatherer=r}setIceTransport(){const e=new RTCIceTransport(this._iceGatherer);e.addEventListener("statechange",()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}),e.addEventListener("icestatechange",()=>{switch(e.state){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}}),e.addEventListener("candidatepairchange",e=>{su.debug('iceTransport "candidatepairchange" event [pair:%o]',e.pair)}),this._iceTransport=e}setDtlsTransport(){const e=new RTCDtlsTransport(this._iceTransport);e.addEventListener("statechange",()=>{su.debug('dtlsTransport "statechange" event [state:%s]',e.state)}),e.addEventListener("dtlsstatechange",()=>{su.debug('dtlsTransport "dtlsstatechange" event [state:%s]',e.state),"closed"===e.state&&this.emit("@connectionstatechange","closed")}),e.addEventListener("error",e=>{su.error('dtlsTransport "error" event [event:%o]',e)}),this._dtlsTransport=e}async setupTransport({localDtlsRole:e}){su.debug("setupTransport()");const t=this._dtlsTransport.getLocalParameters();t.role=e,await new Promise((e,r)=>{this.safeEmit("@connect",{dtlsParameters:t},e,r)}),this._iceTransport.start(this._iceGatherer,this._remoteIceParameters,"controlling");for(const e of this._remoteIceCandidates)this._iceTransport.addRemoteCandidate(e);this._iceTransport.addRemoteCandidate({}),this._remoteDtlsParameters.fingerprints=this._remoteDtlsParameters.fingerprints.filter(e=>"sha-256"===e.algorithm||"sha-384"===e.algorithm||"sha-512"===e.algorithm),this._dtlsTransport.start(this._remoteDtlsParameters),this._transportReady=!0}}Gl.Edge11=ou;var au={},cu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),du=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),lu=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&cu(r,t,i[n]);return du(r,t),r}}();Object.defineProperty(au,"__esModule",{value:!0}),au.ReactNativeUnifiedPlan=void 0;const uu=lu(gi),pu=ts,hu=lu(xs),fu=lu(Ms),mu=lu(wa),gu=lu(Ea),vu=lu(Da),bu=Ps,yu=Ia,wu=Aa,_u=Ya,Su=new pu.Logger("ReactNativeUnifiedPlan"),Cu={OS:1024,MIS:1024};class Ru extends yu.HandlerInterface{static createFactory(){return()=>new Ru}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNativeUnifiedPlan"}close(){if(Su.debug("close()"),!this._closed){if(this._closed=!0,this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Su.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=await e.createOffer();try{e.close()}catch(e){}const r=uu.parse(t.sdp),i=mu.extractRtpCapabilities({sdpObject:r});return vu.addNackSuppportForOpus(i),i}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Su.debug("getNativeSctpCapabilities()"),{numStreams:Cu}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Su.debug("run()"),this._direction=e,this._remoteSdp=new wu.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:fu.getSendingRtpParameters("audio",d),video:fu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:fu.getSendingRemoteRtpParameters("audio",d),video:fu.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Su.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){this.assertNotClosed(),Su.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Su.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Su.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Su.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){this.assertNotClosed(),this.assertSendDirection(),Su.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach((e,t)=>{e.rid=`r${t}`});const s=hu.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=fu.reduceCodecs(s.codecs,i);const o=hu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=fu.reduceCodecs(o.codecs,i);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});n&&n(c.sender);let d,l=await this._pc.createOffer(),u=uu.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let p=!1;const h=(0,_u.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===s.codecs[0].mimeType.toLowerCase()&&(Su.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,u=uu.parse(l.sdp),d=u.media[a.idx],gu.addLegacySimulcast({offerMediaObject:d,numStreams:h.spatialLayers}),l={type:"offer",sdp:uu.write(u)}),Su.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);let f=c.mid??void 0;if(f||Su.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),s.mid=f,u=uu.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=mu.getCname({offerMediaObject:d}),t)if(1===t.length){let e=gu.getRtpEncodings({offerMediaObject:d});Object.assign(e[0],t[0]),p&&(e=[e[0]]),s.encodings=e}else s.encodings=t;else s.encodings=gu.getRtpEncodings({offerMediaObject:d});if(s.encodings.length>1&&("video/vp8"===s.codecs[0].mimeType.toLowerCase()||"video/h264"===s.codecs[0].mimeType.toLowerCase()))for(const e of s.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${h.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:d,reuseMid:a.reuseMid,offerRtpParameters:s,answerRtpParameters:o,codecOptions:r,extmapAllowMixed:!0});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Su.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),await this._pc.setRemoteDescription(m),f||(f=c.mid,s.mid=f),this._mapMidTransceiver.set(f,c),{localId:f,rtpParameters:s,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;Su.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=await this._pc.createOffer();Su.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Su.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=await this._pc.createOffer();Su.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Su.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";const r=await this._pc.createOffer();Su.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Su.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Su.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");await r.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),Su.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Su.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Su.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]={...e,...t}}),await r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=await this._pc.createOffer();Su.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Su.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Cu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=uu.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Su.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Su.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n,streamId:s}=t;Su.debug("receive() [trackId:%s, kind:%s]",e,i);const o=n.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:i,offerRtpParameters:n,streamId:s??n.rtcp.cname,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);for(const t of e){const{trackId:e,onRtpReceiver:i}=t;if(i){const t=r.get(e),n=this._pc.getTransceivers().find(e=>e.mid===t);if(!n)throw new Error("transceiver not found");i(n.receiver)}}let n=await this._pc.createAnswer();const s=uu.parse(n.sdp);for(const t of e){const{trackId:e,rtpParameters:i}=t,n=r.get(e),o=s.media.find(e=>String(e.mid)===n);mu.applyCodecParameters({offerRtpParameters:i,answerMediaObject:o})}n={type:"answer",sdp:uu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Su.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{trackId:e}=i,n=r.get(e),s=this._pc.getTransceivers().find(e=>e.mid===n);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(n,s),t.push({localId:n,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Su.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Su.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Su.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Su.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Su.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Su.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertNotClosed(),this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Su.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Su.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=uu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Su.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=uu.parse(this._pc.localDescription.sdp));const r=mu.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new bu.InvalidStateError("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}au.ReactNativeUnifiedPlan=Ru;var ku={},Tu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Pu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ou=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Tu(r,t,i[n]);return Pu(r,t),r}}();Object.defineProperty(ku,"__esModule",{value:!0}),ku.ReactNative=void 0;const Eu=Ou(gi),Du=ts,xu=Ps,Iu=Ou(xs),Mu=Ou(Ms),ju=Ou(wa),Lu=Ou(Zc),Au=Ia,Nu=Aa,Bu=new Du.Logger("ReactNative"),Fu={OS:1024,MIS:1024};class zu extends Au.HandlerInterface{static createFactory(){return()=>new zu}constructor(){super(),this._sendStream=new MediaStream,this._mapSendLocalIdTrack=new Map,this._nextSendLocalId=0,this._mapRecvLocalIdInfo=new Map,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"ReactNative"}close(){if(Bu.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Bu.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b"});try{const t=await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});try{e.close()}catch(e){}const r=Eu.parse(t.sdp);return ju.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Bu.debug("getNativeSctpCapabilities()"),{numStreams:Fu}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Bu.debug("run()"),this._direction=e,this._remoteSdp=new Nu.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,planB:!0}),this._sendingRtpParametersByKind={audio:Mu.getSendingRtpParameters("audio",d),video:Mu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Mu.getSendingRemoteRtpParameters("audio",d),video:Mu.getSendingRemoteRtpParameters("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection({iceServers:s??[],iceTransportPolicy:o??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"plan-b",...a},c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Bu.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}async updateIceServers(e){Bu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Bu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Bu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Bu.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),await this._pc.setLocalDescription(t)}}async getTransportStats(){return this._pc.getStats()}async send({track:e,encodings:t,codecOptions:r,codec:i}){this.assertSendDirection(),Bu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),i&&Bu.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let n,s=await this._pc.createOffer(),o=Eu.parse(s.sdp);const a=Iu.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Mu.reduceCodecs(a.codecs);const c=Iu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Mu.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Bu.debug("send() | enabling simulcast"),o=Eu.parse(s.sdp),n=o.media.find(e=>"video"===e.type),Lu.addLegacySimulcast({offerMediaObject:n,track:e,numStreams:t.length}),s={type:"offer",sdp:Eu.write(o)}),Bu.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Eu.parse(this._pc.localDescription.sdp),n=o.media.find(t=>t.type===e.kind),a.rtcp.cname=ju.getCname({offerMediaObject:n}),a.encodings=Lu.getRtpEncodings({offerMediaObject:n,track:e}),t)for(let e=0;e<a.encodings.length;++e)t[e]&&Object.assign(a.encodings[e],t[e]);if(a.encodings.length>1&&("video/vp8"===a.codecs[0].mimeType.toLowerCase()||"video/h264"===a.codecs[0].mimeType.toLowerCase()))for(const e of a.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:n,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("send() | calling pc.setRemoteDescription() [answer:%o]",d),await this._pc.setRemoteDescription(d);const l=String(this._nextSendLocalId);return this._nextSendLocalId++,this._mapSendLocalIdTrack.set(l,e),{localId:l,rtpParameters:a}}async stopSending(e){this.assertSendDirection(),Bu.debug("stopSending() [localId:%s]",e);const t=this._mapSendLocalIdTrack.get(e);if(!t)throw new Error("track not found");this._mapSendLocalIdTrack.delete(e),this._sendStream.removeTrack(t),this._pc.addStream(this._sendStream);const r=await this._pc.createOffer();Bu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Bu.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const i={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new xu.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new xu.UnsupportedError("not implemented")}async setRtpEncodingParameters(e,t){throw new xu.UnsupportedError("not implemented")}async getSenderStats(e){throw new xu.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:n};Bu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(i,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Fu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Eu.parse(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Bu.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Bu.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:o,sctpStreamParameters:{streamId:s.id,ordered:s.ordered,maxPacketLifeTime:s.maxPacketLifeTime,maxRetransmits:s.maxRetransmits}}}async receive(e){this.assertRecvDirection();const t=[],r=new Map;for(const t of e){const{trackId:e,kind:i,rtpParameters:n}=t;Bu.debug("receive() [trackId:%s, kind:%s]",e,i);const s=i;let o=t.streamId??n.rtcp.cname;Bu.debug("receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc"),o+=`-hack-${Iu.generateRandomNumber()}`,r.set(e,o),this._remoteSdp.receive({mid:s,kind:i,offerRtpParameters:n,streamId:o,trackId:e})}const i={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",i),await this._pc.setRemoteDescription(i);let n=await this._pc.createAnswer();const s=Eu.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,i=e,n=s.media.find(e=>String(e.mid)===i);ju.applyCodecParameters({offerRtpParameters:r,answerMediaObject:n})}n={type:"answer",sdp:Eu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Bu.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const i of e){const{kind:e,trackId:n,rtpParameters:s}=i,o=n,a=e,c=r.get(n),d=this._pc.getRemoteStreams().find(e=>e.id===c).getTrackById(o);if(!d)throw new Error("remote track not found");this._mapRecvLocalIdInfo.set(o,{mid:a,rtpParameters:s}),t.push({localId:o,track:d})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Bu.debug("stopReceiving() [localId:%s]",t);const{mid:e,rtpParameters:r}=this._mapRecvLocalIdInfo.get(t)??{};this._mapRecvLocalIdInfo.delete(t),this._remoteSdp.planBStopReceiving({mid:e,offerRtpParameters:r})}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Bu.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new xu.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:i,ordered:n,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:i,ordered:n,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Bu.debug("receiveDataChannel() [options:%o]",a);const c=this._pc.createDataChannel(t,a);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation({oldDataChannelSpec:!0});const e={type:"offer",sdp:this._remoteSdp.getSdp()};Bu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Eu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Bu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:c}}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Eu.parse(this._pc.localDescription.sdp));const r=ju.extractDtlsParameters({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),await new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}ku.ReactNative=zu;var Vu=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),Uu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),$u=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&Vu(r,t,i[n]);return Uu(r,t),r}}();Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.Device=void 0,Yn.detectDevice=lp;const Gu=es,qu=ts,Hu=as,Wu=Ps,Ku=$u(xs),Ju=$u(Ms),Qu=Co,Xu=ya,Yu=bc,Zu=Ac,ep=Yc,tp=fd,rp=Dd,ip=Wd,np=ll,sp=El,op=Gl,ap=au,cp=ku,dp=new qu.Logger("Device");function lp(e){if(!e&&"object"==typeof navigator&&"ReactNative"===navigator.product)return dp.debug("detectDevice() | React-Native detected"),"undefined"==typeof RTCPeerConnection?void dp.warn("detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?"):"undefined"!=typeof RTCRtpTransceiver?(dp.debug("detectDevice() | ReactNative UnifiedPlan handler chosen"),"ReactNativeUnifiedPlan"):(dp.debug("detectDevice() | ReactNative PlanB handler chosen"),"ReactNative");if(e||"object"==typeof navigator&&"string"==typeof navigator.userAgent){e??(e=navigator.userAgent);const t=new Gu.UAParser(e);dp.debug("detectDevice() | browser detected [userAgent:%s, parsed:%o]",e,t.getResult());const r=t.getBrowser(),i=r.name?.toLowerCase(),n=parseInt(r.major??"0"),s=t.getEngine(),o=s.name?.toLowerCase(),a=t.getOS(),c=a.name?.toLowerCase(),d=parseFloat(a.version??"0"),l=t.getDevice(),u=l.model?.toLowerCase(),p="ios"===c||"ipad"===u,h=i&&["chrome","chromium","mobile chrome","chrome webview","chrome headless"].includes(i),f=i&&["firefox","mobile firefox","mobile focus"].includes(i),m=i&&["safari","mobile safari"].includes(i),g=i&&["edge"].includes(i);if((h||g)&&!p&&n>=111)return"Chrome111";if(h&&!p&&n>=74||g&&!p&&n>=88)return"Chrome74";if(h&&!p&&n>=70)return"Chrome70";if(h&&!p&&n>=67)return"Chrome67";if(h&&!p&&n>=55)return"Chrome55";if(f&&!p&&n>=120)return"Firefox120";if(f&&!p&&n>=60)return"Firefox60";if(f&&p&&d>=14.3)return"Safari12";if(m&&n>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(m&&n>=11)return"Safari11";if(g&&!p&&n>=11&&n<=18)return"Edge11";if("webkit"===o&&p&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if("blink"===o){const t=e.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(t){const e=Number(t[1]);return e>=111?"Chrome111":e>=74?"Chrome74":e>=70?"Chrome70":e>=67?"Chrome67":"Chrome55"}return"Chrome111"}return void dp.warn("detectDevice() | browser not supported [name:%s, version:%s]",i,n)}dp.warn("detectDevice() | unknown device")}Yn.Device=class{constructor({handlerName:e,handlerFactory:t}={}){if(this._loaded=!1,this._observer=new Hu.EnhancedEventEmitter,dp.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)dp.debug("constructor() | handler given: %s",e);else{if(!(e=lp()))throw new Wu.UnsupportedError("device not supported");dp.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=Xu.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=Yu.Chrome74.createFactory();break;case"Chrome70":this._handlerFactory=Zu.Chrome70.createFactory();break;case"Chrome67":this._handlerFactory=ep.Chrome67.createFactory();break;case"Chrome55":this._handlerFactory=tp.Chrome55.createFactory();break;case"Firefox120":this._handlerFactory=rp.Firefox120.createFactory();break;case"Firefox60":this._handlerFactory=ip.Firefox60.createFactory();break;case"Safari12":this._handlerFactory=np.Safari12.createFactory();break;case"Safari11":this._handlerFactory=sp.Safari11.createFactory();break;case"Edge11":this._handlerFactory=op.Edge11.createFactory();break;case"ReactNativeUnifiedPlan":this._handlerFactory=ap.ReactNativeUnifiedPlan.createFactory();break;case"ReactNative":this._handlerFactory=cp.ReactNative.createFactory();break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const r=this._handlerFactory();this._handlerName=r.name,r.close(),this._extendedRtpCapabilities=void 0,this._recvRtpCapabilities=void 0,this._canProduceByKind={audio:!1,video:!1},this._sctpCapabilities=void 0}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e}){let t;dp.debug("load() [routerRtpCapabilities:%o]",e);try{if(this._loaded)throw new Wu.InvalidStateError("already loaded");const r=Ku.clone(e);Ju.validateRtpCapabilities(r),t=this._handlerFactory();const i=await t.getNativeRtpCapabilities();dp.debug("load() | got native RTP capabilities:%o",i);const n=Ku.clone(i);Ju.validateRtpCapabilities(n),this._extendedRtpCapabilities=Ju.getExtendedRtpCapabilities(n,r),dp.debug("load() | got extended RTP capabilities:%o",this._extendedRtpCapabilities),this._canProduceByKind.audio=Ju.canSend("audio",this._extendedRtpCapabilities),this._canProduceByKind.video=Ju.canSend("video",this._extendedRtpCapabilities),this._recvRtpCapabilities=Ju.getRecvRtpCapabilities(this._extendedRtpCapabilities),Ju.validateRtpCapabilities(this._recvRtpCapabilities),dp.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._sctpCapabilities=await t.getNativeSctpCapabilities(),dp.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),Ju.validateSctpCapabilities(this._sctpCapabilities),dp.debug("load() succeeded"),this._loaded=!0,t.close()}catch(e){throw t&&t.close(),e}}canProduce(e){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");if("audio"!==e&&"video"!==e)throw new TypeError(`invalid kind "${e}"`);return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return dp.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return dp.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l}){if(!this._loaded)throw new Wu.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(i))throw new TypeError("missing iceCandidates");if("object"!=typeof n)throw new TypeError("missing dtlsParameters");if(s&&"object"!=typeof s)throw new TypeError("wrong sctpParameters");if(l&&"object"!=typeof l)throw new TypeError("if given, appData must be an object");const u=new Qu.Transport({direction:e,id:t,iceParameters:r,iceCandidates:i,dtlsParameters:n,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l,handlerFactory:this._handlerFactory,extendedRtpCapabilities:this._extendedRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",u),u}};var up={},pp={};Object.defineProperty(pp,"__esModule",{value:!0});var hp={};Object.defineProperty(hp,"__esModule",{value:!0}),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__exportStar||function(e,r){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(r,i)||t(r,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),r(Yn,e),r(Co,e),r(Ao,e),r(Vo,e),r(Ho,e),r(Xo,e),r(pp,e),r(hp,e),r(Ia,e),r(Ps,e)}(up),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),r=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=a&&a.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(i){if(i&&i.__esModule)return i;var n={};if(null!=i)for(var s=e(i),o=0;o<s.length;o++)"default"!==s[o]&&t(n,i,s[o]);return r(n,i),n}}(),n=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.debug=e.parseScalabilityMode=e.detectDevice=e.Device=e.version=e.types=void 0;const s=n(Xn);e.debug=s.default;const o=Yn;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return o.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return o.detectDevice}});const c=i(up);e.types=c,e.version="3.7.18";var d=Ya;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return d.parse}})}(Wn);var fp={exports:{}};!function(e,t){!function(r,i){var n="function",s="undefined",o="object",a="string",c="major",d="model",l="name",u="type",p="vendor",h="version",f="architecture",m="console",g="mobile",v="tablet",b="smarttv",y="wearable",w="embedded",_="Amazon",S="Apple",C="ASUS",R="BlackBerry",k="Browser",T="Chrome",P="Firefox",O="Google",E="Huawei",D="LG",x="Microsoft",I="Motorola",M="Opera",j="Samsung",L="Sharp",A="Sony",N="Xiaomi",B="Zebra",F="Facebook",z="Chromium OS",V="Mac OS",U=" Browser",$=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},G=function(e,t){return typeof e===a&&-1!==q(t).indexOf(q(e))},q=function(e){return e.toLowerCase()},H=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===s?e:e.substring(0,500)},W=function(e,t){for(var r,s,a,c,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=s=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(a=0;a<h.length;a++)l=d[++s],typeof(c=h[a])===o&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):i:this[c[0]]=l?c[1].call(this,l,c[2]):i:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):i):this[c]=l||i;u+=2}},K=function(e,t){for(var r in t)if(typeof t[r]===o&&t[r].length>0){for(var n=0;n<t[r].length;n++)if(G(t[r][n],e))return"?"===r?i:r}else if(G(t[r],e))return"?"===r?i:r;return t.hasOwnProperty("*")?t["*"]:e},J={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Q={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,h],[/opios[\/ ]+([\w\.]+)/i],[h,[l,M+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[l,M+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[l,M]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[l,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[l,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[l,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[l,"UC"+k]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[l,"Smart Lenovo "+k]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+k],h],[/\bfocus\/([\w\.]+)/i],[h,[l,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[l,M+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[l,M+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[l,"MIUI"+U]],[/fxios\/([\w\.-]+)/i],[h,[l,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[l,"360"]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+U],h],[/samsungbrowser\/([\w\.]+)/i],[h,[l,j+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[l,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,F],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[l,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[l,T+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,T+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[l,"Android "+k]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[h,K,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[l,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[l,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,q]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",q]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,q]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[p,j],[u,v]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[d,[p,j],[u,g]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[p,S],[u,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[p,S],[u,v]],[/(macintosh);/i],[d,[p,S]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[p,L],[u,g]],[/(?:honor)([-\w ]+)[;\)]/i],[d,[p,"Honor"],[u,g]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[p,E],[u,v]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[p,E],[u,g]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,g]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[p,N],[u,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[p,"OPPO"],[u,g]],[/\b(opd2\d{3}a?) bui/i],[d,[p,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[p,"Vivo"],[u,g]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[d,[p,"Realme"],[u,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[p,I],[u,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[p,I],[u,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[p,D],[u,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[p,D],[u,g]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[p,"Lenovo"],[u,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[p,"Nokia"],[u,g]],[/(pixel c)\b/i],[d,[p,O],[u,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[p,O],[u,g]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[p,A],[u,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[p,A],[u,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[p,"OnePlus"],[u,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[p,_],[u,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[p,_],[u,g]],[/(playbook);[-\w\),; ]+(rim)/i],[d,p,[u,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[p,R],[u,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[p,C],[u,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[p,C],[u,g]],[/(nexus 9)/i],[d,[p,"HTC"],[u,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[d,/_/g," "],[u,g]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[d,[p,"TCL"],[u,v]],[/(itel) ((\w+))/i],[[p,q],d,[u,K,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[p,"Acer"],[u,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[p,"Meizu"],[u,g]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[d,[p,"Ulefone"],[u,g]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[d,[p,"Energizer"],[u,g]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[d,[p,"Cat"],[u,g]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[d,[p,"Smartfren"],[u,g]],[/droid.+; (a(?:015|06[35]|142p?))/i],[d,[p,"Nothing"],[u,g]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,d,[u,g]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,d,[u,v]],[/(surface duo)/i],[d,[p,x],[u,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[p,"Fairphone"],[u,g]],[/(u304aa)/i],[d,[p,"AT&T"],[u,g]],[/\bsie-(\w*)/i],[d,[p,"Siemens"],[u,g]],[/\b(rct\w+) b/i],[d,[p,"RCA"],[u,v]],[/\b(venue[\d ]{2,7}) b/i],[d,[p,"Dell"],[u,v]],[/\b(q(?:mv|ta)\w+) b/i],[d,[p,"Verizon"],[u,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[p,"Barnes & Noble"],[u,v]],[/\b(tm\d{3}\w+) b/i],[d,[p,"NuVision"],[u,v]],[/\b(k88) b/i],[d,[p,"ZTE"],[u,v]],[/\b(nx\d{3}j) b/i],[d,[p,"ZTE"],[u,g]],[/\b(gen\d{3}) b.+49h/i],[d,[p,"Swiss"],[u,g]],[/\b(zur\d{3}) b/i],[d,[p,"Swiss"],[u,v]],[/\b((zeki)?tb.*\b) b/i],[d,[p,"Zeki"],[u,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],d,[u,v]],[/\b(ns-?\w{0,9}) b/i],[d,[p,"Insignia"],[u,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[p,"NextBook"],[u,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],d,[u,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],d,[u,g]],[/\b(ph-1) /i],[d,[p,"Essential"],[u,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[p,"Envizen"],[u,v]],[/\b(trio[-\w\. ]+) b/i],[d,[p,"MachSpeed"],[u,v]],[/\btu_(1491) b/i],[d,[p,"Rotor"],[u,v]],[/(shield[\w ]+) b/i],[d,[p,"Nvidia"],[u,v]],[/(sprint) (\w+)/i],[p,d,[u,g]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[p,x],[u,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[p,B],[u,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[p,B],[u,g]],[/smart-tv.+(samsung)/i],[p,[u,b]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[p,j],[u,b]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,D],[u,b]],[/(apple) ?tv/i],[p,[d,S+" TV"],[u,b]],[/crkey/i],[[d,T+"cast"],[p,O],[u,b]],[/droid.+aft(\w+)( bui|\))/i],[d,[p,_],[u,b]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[p,L],[u,b]],[/(bravia[\w ]+)( bui|\))/i],[d,[p,A],[u,b]],[/(mitv-\w{5}) bui/i],[d,[p,N],[u,b]],[/Hbbtv.*(technisat) (.*);/i],[p,d,[u,b]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,H],[d,H],[u,b]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,b]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,d,[u,m]],[/droid.+; (shield) bui/i],[d,[p,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[d,[p,A],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[p,x],[u,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[d,[p,j],[u,y]],[/((pebble))app/i],[p,d,[u,y]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[p,S],[u,y]],[/droid.+; (glass) \d/i],[d,[p,O],[u,y]],[/droid.+; (wt63?0{2,3})\)/i],[d,[p,B],[u,y]],[/droid.+; (glass) \d/i],[d,[p,O],[u,y]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,d,[u,y]],[/; (quest( \d| pro)?)/i],[d,[p,F],[u,y]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[u,w]],[/(aeobc)\b/i],[d,[p,_],[u,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[d,[u,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,g]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[l,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[l,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[l,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,h],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[h,K,J]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,K,J],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,V],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,h],[/\(bb(10);/i],[h,[l,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[l,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[l,T+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,z],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,h],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,h]]},X=function(e,t){if(typeof e===o&&(t=e,e=i),!(this instanceof X))return new X(e,t).getResult();var m=typeof r!==s&&r.navigator?r.navigator:i,b=e||(m&&m.userAgent?m.userAgent:""),y=m&&m.userAgentData?m.userAgentData:i,w=t?function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r}(Q,t):Q,_=m&&m.userAgent==b;return this.getBrowser=function(){var e,t={};return t[l]=i,t[h]=i,W.call(t,b,w.browser),t[c]=typeof(e=t[h])===a?e.replace(/[^\d\.]/g,"").split(".")[0]:i,_&&m&&m.brave&&typeof m.brave.isBrave==n&&(t[l]="Brave"),t},this.getCPU=function(){var e={};return e[f]=i,W.call(e,b,w.cpu),e},this.getDevice=function(){var e={};return e[p]=i,e[d]=i,e[u]=i,W.call(e,b,w.device),_&&!e[u]&&y&&y.mobile&&(e[u]=g),_&&"Macintosh"==e[d]&&m&&typeof m.standalone!==s&&m.maxTouchPoints&&m.maxTouchPoints>2&&(e[d]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.engine),e},this.getOS=function(){var e={};return e[l]=i,e[h]=i,W.call(e,b,w.os),_&&!e[l]&&y&&y.platform&&"Unknown"!=y.platform&&(e[l]=y.platform.replace(/chrome os/i,z).replace(/macos/i,V)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return b},this.setUA=function(e){return b=typeof e===a&&e.length>500?H(e,500):e,this},this.setUA(b),this};X.VERSION="1.0.40",X.BROWSER=$([l,h,c]),X.CPU=$([f]),X.DEVICE=$([d,p,u,m,g,b,v,y,w]),X.ENGINE=X.OS=$([l,h]),e.exports&&(t=e.exports=X),t.UAParser=X;var Y=typeof r!==s&&(r.jQuery||r.Zepto);if(Y&&!Y.ua){var Z=new X;Y.ua=Z.getResult(),Y.ua.get=function(){return Z.getUA()},Y.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var r in t)Y.ua[r]=t[r]}}}("object"==typeof window?window:a)}(fp,fp.exports);var mp,gp=fp.exports;function vp(){}function bp(){bp.init.call(this)}function yp(e){return void 0===e._maxListeners?bp.defaultMaxListeners:e._maxListeners}function wp(e,t,r,i){var n,s,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]):(s=e._events=new vp,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(n=yp(e))&&n>0&&o.length>n){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=s[t]=r,++e._eventsCount;return e}function _p(e,t,r){var i=!1;function n(){e.removeListener(t,n),i||(i=!0,r.apply(e,arguments))}return n.listener=r,n}function Sp(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Cp(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}vp.prototype=Object.create(null),bp.EventEmitter=bp,bp.usingDomains=!1,bp.prototype.domain=void 0,bp.prototype._events=void 0,bp.prototype._maxListeners=void 0,bp.defaultMaxListeners=10,bp.init=function(){this.domain=null,bp.usingDomains&&(!mp.active||this instanceof mp.Domain||(this.domain=mp.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new vp,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},bp.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},bp.prototype.getMaxListeners=function(){return yp(this)},bp.prototype.emit=function(e){var t,r,i,n,s,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,n=Cp(e,i),s=0;s<i;++s)n[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,i){if(t)e.call(r,i);else for(var n=e.length,s=Cp(e,n),o=0;o<n;++o)s[o].call(r,i)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,i,n){if(t)e.call(r,i,n);else for(var s=e.length,o=Cp(e,s),a=0;a<s;++a)o[a].call(r,i,n)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,i,n,s){if(t)e.call(r,i,n,s);else for(var o=e.length,a=Cp(e,o),c=0;c<o;++c)a[c].call(r,i,n,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(n=new Array(i-1),s=1;s<i;s++)n[s-1]=arguments[s];!function(e,t,r,i){if(t)e.apply(r,i);else for(var n=e.length,s=Cp(e,n),o=0;o<n;++o)s[o].apply(r,i)}(r,l,this,n)}return!0},bp.prototype.addListener=function(e,t){return wp(this,e,t,!1)},bp.prototype.on=bp.prototype.addListener,bp.prototype.prependListener=function(e,t){return wp(this,e,t,!0)},bp.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,_p(this,e,t)),this},bp.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,_p(this,e,t)),this},bp.prototype.removeListener=function(e,t){var r,i,n,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0===--this._eventsCount?this._events=new vp:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(n=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,n=s;break}if(n<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new vp,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,n=e.length;i<n;r+=1,i+=1)e[r]=e[i];e.pop()}(r,n);i.removeListener&&this.emit("removeListener",e,o||t)}return this},bp.prototype.off=function(e,t){return this.removeListener(e,t)},bp.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new vp,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new vp:delete r[e]),this;if(0===arguments.length){for(var i,n=Object.keys(r),s=0;s<n.length;++s)"removeListener"!==(i=n[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new vp,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},bp.prototype.listeners=function(e){var t,r,i=this._events;return r=i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[],r},bp.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Sp.call(e,t)},bp.prototype.listenerCount=Sp,bp.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const Rp=Object.create(null);Rp.open="0",Rp.close="1",Rp.ping="2",Rp.pong="3",Rp.message="4",Rp.upgrade="5",Rp.noop="6";const kp=Object.create(null);Object.keys(Rp).forEach(e=>{kp[Rp[e]]=e});const Tp={type:"error",data:"parser error"},Pp="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Op="function"==typeof ArrayBuffer,Ep=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Dp=({type:e,data:t},r,i)=>Pp&&t instanceof Blob?r?i(t):xp(t,i):Op&&(t instanceof ArrayBuffer||Ep(t))?r?i(t):xp(new Blob([t]),i):i(Rp[e]+(t||"")),xp=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Ip(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Mp;const jp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Lp="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let ID=0;ID<64;ID++)Lp[jp.charCodeAt(ID)]=ID;const Ap="function"==typeof ArrayBuffer,Np=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Fp(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Bp(e.substring(1),t)};return kp[r]?e.length>1?{type:kp[r],data:e.substring(1)}:{type:kp[r]}:Tp},Bp=(e,t)=>{if(Ap){const r=(e=>{let t,r,i,n,s,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=Lp[e.charCodeAt(t)],i=Lp[e.charCodeAt(t+1)],n=Lp[e.charCodeAt(t+2)],s=Lp[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|n>>2,l[c++]=(3&n)<<6|63&s;return d})(e);return Fp(r,t)}return{base64:!0,data:e}},Fp=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,zp=String.fromCharCode(30);function Vp(){return new TransformStream({transform(e,t){!function(e,t){Pp&&e.data instanceof Blob?e.data.arrayBuffer().then(Ip).then(t):Op&&(e.data instanceof ArrayBuffer||Ep(e.data))?t(Ip(e.data)):Dp(e,!1,e=>{Mp||(Mp=new TextEncoder),t(Mp.encode(e))})}(e,r=>{const i=r.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}let Up;function $p(e){return e.reduce((e,t)=>e+t.length,0)}function Gp(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let n=0;n<t;n++)r[n]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function qp(e){if(e)return function(e){for(var t in qp.prototype)e[t]=qp.prototype[t];return e}(e)}qp.prototype.on=qp.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},qp.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},qp.prototype.off=qp.prototype.removeListener=qp.prototype.removeAllListeners=qp.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<i.length;n++)if((r=i[n])===t||r.fn===t){i.splice(n,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},qp.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var n=(r=r.slice(0)).length;i<n;++i)r[i].apply(this,t)}return this},qp.prototype.emitReserved=qp.prototype.emit,qp.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},qp.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Hp="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Wp(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const Kp=Hp.setTimeout,Jp=Hp.clearTimeout;function Qp(e,t){t.useNativeTimers?(e.setTimeoutFn=Kp.bind(Hp),e.clearTimeoutFn=Jp.bind(Hp)):(e.setTimeoutFn=Hp.setTimeout.bind(Hp),e.clearTimeoutFn=Hp.clearTimeout.bind(Hp))}function Xp(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,n=e.length;i<n;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}class Yp extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class Zp extends qp{constructor(e){super(),this.writable=!1,Qp(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Yp(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Np(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const eh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),th={};let rh,ih=0,nh=0;function sh(e){let t="";do{t=eh[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function oh(){const e=sh(+new Date);return e!==rh?(ih=0,rh=e):e+"."+sh(ih++)}for(;nh<64;nh++)th[eh[nh]]=nh;let ah=!1;try{ah="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(MD){}const ch=ah;function dh(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||ch))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Hp[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function lh(){}const uh=null!=new dh({xdomain:!1}).responseType;let ph=class e extends qp{constructor(e,t){super(),Qp(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var t;const r=Wp(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this.opts.xd;const i=this.xhr=new dh(r);try{i.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{i.setRequestHeader("Accept","*/*")}catch(e){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(i.timeout=this.opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(i)),4===i.readyState&&(200===i.status||1223===i.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof i.status?i.status:0)},0))},i.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=e.requestsCount++,e.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=lh,t)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete e.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};if(ph.requestsCount=0,ph.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",hh);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Hp?"pagehide":"unload",hh,!1)}function hh(){for(let e in ph.requests)ph.requests.hasOwnProperty(e)&&ph.requests[e].abort()}const fh="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),mh=Hp.WebSocket||Hp.MozWebSocket,gh="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const vh={websocket:class extends Zp{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=gh?{}:Wp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=gh?new mh(e,t,r):t?new mh(e,t):new mh(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;Dp(r,this.supportsBinary,e=>{try{this.ws.send(e)}catch(e){}i&&fh(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=oh()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!mh}},webtransport:class extends Zp{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const t=function(e,t){Up||(Up=new TextDecoder);const r=[];let i=0,n=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===i){if($p(r)<1)break;const e=Gp(r,1);s=!(128&~e[0]),n=127&e[0],i=n<126?3:126===n?1:2}else if(1===i){if($p(r)<2)break;const e=Gp(r,2);n=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if($p(r)<8)break;const e=Gp(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Tp);break}n=s*Math.pow(2,32)+t.getUint32(4),i=3}else{if($p(r)<n)break;const e=Gp(r,n);a.enqueue(Np(s?e:Up.decode(e),t)),i=0}if(0===n||n>e){a.enqueue(Tp);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=Vp();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const n=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),n())}).catch(e=>{})};n();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this.writer.write(r).then(()=>{i&&fh(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends Zp{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=uh&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(zp),i=[];for(let e=0;e<r.length;e++){const n=Np(r[e],t);if(i.push(n),"error"===n.type)break}return i})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let n=0;e.forEach((e,s)=>{Dp(e,!1,e=>{i[s]=e,++n===r&&t(i.join(zp))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=oh()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new ph(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}},bh=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,yh=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function wh(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let n=bh.exec(e||""),s={},o=14;for(;o--;)s[yh[o]]=n[o]||"";return-1!=r&&-1!=i&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,s.query),s}let _h=class e extends qp{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=wh(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=wh(t.host).host),Qp(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,i=r.length;e<i;e++){let i=r[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new vh[e](r)}open(){let t;if(this.opts.rememberUpgrade&&e.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(e){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",e=>this.onClose("transport close",e))}probe(t){let r=this.createTransport(t),i=!1;e.priorWebsocketSuccess=!1;const n=()=>{i||(r.send([{type:"ping",data:"probe"}]),r.once("packet",t=>{if(!i)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;e.priorWebsocketSuccess="websocket"===r.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(l(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=r.name,this.emitReserved("upgradeError",e)}}))};function s(){i||(i=!0,l(),r.close(),r=null)}const o=e=>{const t=new Error("probe error: "+e);t.transport=r.name,s(),this.emitReserved("upgradeError",t)};function a(){o("transport closed")}function c(){o("socket closed")}function d(e){r&&e.name!==r.name&&s()}const l=()=>{r.removeListener("open",n),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",n),r.once("error",o),r.once("close",a),this.once("close",c),this.once("upgrading",d),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{i||r.open()},200):r.open()}onOpen(){if(this.readyState="open",e.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=Xp(r)),t>0&&e>this.maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const n={type:e,data:t,options:r};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}onError(t){e.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};_h.protocol=4;const Sh="function"==typeof ArrayBuffer,Ch=Object.prototype.toString,Rh="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ch.call(Blob),kh="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ch.call(File);function Th(e){return Sh&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Rh&&e instanceof Blob||kh&&e instanceof File}function Ph(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ph(e[t]))return!0;return!1}if(Th(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ph(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Ph(e[t]))return!0;return!1}function Oh(e){const t=[],r=e.data,i=e;return i.data=Eh(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Eh(e,t){if(!e)return e;if(Th(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Eh(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Eh(e[i],t));return r}return e}function Dh(e,t){return e.data=xh(e.data,t),delete e.attachments,e}function xh(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=xh(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=xh(e[r],t));return e}const Ih=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Mh;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Mh||(Mh={}));function jh(e){return"[object Object]"===Object.prototype.toString.call(e)}class Lh extends qp{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Mh.BINARY_EVENT;r||t.type===Mh.BINARY_ACK?(t.type=r?Mh.EVENT:Mh.ACK,this.reconstructor=new Ah(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Th(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Mh[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Mh.BINARY_EVENT||r.type===Mh.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(i,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(n)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!Lh.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Mh.CONNECT:return jh(t);case Mh.DISCONNECT:return void 0===t;case Mh.CONNECT_ERROR:return"string"==typeof t||jh(t);case Mh.EVENT:case Mh.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ih.indexOf(t[0]));case Mh.ACK:case Mh.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ah{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Dh(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Nh=Object.freeze({__proto__:null,Decoder:Lh,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Mh.EVENT&&e.type!==Mh.ACK||!Ph(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Mh.EVENT?Mh.BINARY_EVENT:Mh.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Mh.BINARY_EVENT&&e.type!==Mh.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Oh(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Mh},protocol:5});function Bh(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Fh=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class zh extends qp{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Bh(e,"open",this.onopen.bind(this)),Bh(e,"packet",this.onpacket.bind(this)),Bh(e,"error",this.onerror.bind(this)),Bh(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Fh.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Mh.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise((i,n)=>{t.push((e,t)=>r?e?n(e):i(t):i(e)),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Mh.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Mh.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Mh.EVENT:case Mh.BINARY_EVENT:this.onevent(e);break;case Mh.ACK:case Mh.BINARY_ACK:this.onack(e);break;case Mh.DISCONNECT:this.ondisconnect();break;case Mh.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Mh.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Mh.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function Vh(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Vh.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},Vh.prototype.reset=function(){this.attempts=0},Vh.prototype.setMin=function(e){this.ms=e},Vh.prototype.setMax=function(e){this.max=e},Vh.prototype.setJitter=function(e){this.jitter=e};class Uh extends qp{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Qp(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new Vh({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Nh;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new _h(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Bh(t,"open",function(){r.onopen(),e&&e()}),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=Bh(t,"error",n);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(i),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Bh(e,"ping",this.onping.bind(this)),Bh(e,"data",this.ondata.bind(this)),Bh(e,"error",this.onerror.bind(this)),Bh(e,"close",this.onclose.bind(this)),Bh(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){fh(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new zh(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const $h={};function Gh(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=wh(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+t,i.href=i.protocol+"://"+n+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,n=r.id,s=r.path,o=$h[n]&&s in $h[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Uh(i,t):($h[n]||($h[n]=new Uh(i,t)),a=$h[n]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(Gh,{Manager:Uh,Socket:zh,io:Gh,connect:Gh});const qh=new URLSearchParams(window.location.search).has("debug");class Hh{constructor(){this._isEnabled=!1,this._isEnabled=qh}isEnabled(){return this._isEnabled}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}info(...e){if(this._isEnabled)return console.info(...e)}warn(...e){if(this._isEnabled)return console.warn(...e)}error(...e){if(this._isEnabled)return console.error(...e)}withDebugLogger(e){return this._debugger=e,this}debug(...e){if(!this._isEnabled||!this._debugger)return;const t=[];e.forEach(e=>{if("function"==typeof e){const r=e();t.push(r)}else t.push(e)}),this._debugger.print(...t)}}function Wh(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,oi.default;const Kh={id:mi(),connectionNumber:0},Jh=()=>{};let Qh=Jh;const Xh=function(e,t=console){const r=[];let i,n,s,o,a,c,d,l,u,p,h,f,m=0,g=!1,v=0;const b={connected:!1,trace:(...e)=>{if(e.push(Date.now()),"customEvent"===e[0]&&"roomSessionId"===e[2].type){const t=c&&c[2].value.roomSessionId,r=e[2].value.roomSessionId;c=e,g&&r&&r!==t&&(null==i||i.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?n=e:"customEvent"===e[0]&&"displayName"===e[2].type?o=e:"customEvent"===e[0]&&"userRole"===e[2].type?a=e:"customEvent"===e[0]&&"deviceId"===e[2].type?l=e:"customEvent"===e[0]&&"roomProduct"===e[2].type?u=e:"customEvent"===e[0]&&"roomMode"===e[2].type?p=e:"customEvent"===e[0]&&"sfuServer"===e[2].type?h=e:"customEvent"===e[0]&&"featureFlags"===e[2].type&&(f=e);(null==i?void 0:i.readyState)===WebSocket.OPEN?(m=0,i.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==i?void 0:i.readyState)===WebSocket.CLOSED&&d&&setTimeout(()=>{i.readyState===WebSocket.CLOSED&&d&&b.connect()},1e3*m)},close:()=>{d=!1,null==i||i.close()},connect:()=>{d=!0,m+=1,null==i||i.close(),b.connected=!0,i=new WebSocket(e+window.location.pathname,"1.0"),i.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},i.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),Qh()},i.onopen=()=>{for(Kh.connectionNumber++,i.send(JSON.stringify(["clientInfo",null,Kh])),n&&i.send(JSON.stringify(n)),s&&i.send(JSON.stringify(s)),c&&i.send(JSON.stringify(c)),o&&i.send(JSON.stringify(o)),a&&i.send(JSON.stringify(a)),l&&i.send(JSON.stringify(l)),p&&i.send(JSON.stringify(p)),u&&i.send(JSON.stringify(u)),h&&i.send(JSON.stringify(h)),f&&i.send(JSON.stringify(f));r.length;)i.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),Yh=di(Xh.trace,1e4,[""]);Qh=(null==Yh?void 0:Yh.resetDelta)||Jh;const Zh={sendEvent:(e,t)=>{Xh.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{Zh.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{Zh.sendEvent("video_muted",{muted:e})},server:Xh};let ef=[],tf=0;const rf=new WeakMap,nf=e=>{ef=ef.filter(t=>t!==e)};if(window.RTCPeerConnection){const jD=window.RTCPeerConnection;function LD(e){const t=new jD(e);ef.push(t),rf.set(t,{index:tf++});const r=()=>{"closed"===t.connectionState&&(nf(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}LD.prototype=jD.prototype,window.RTCPeerConnection=LD}const sf=new WeakMap;const of=()=>Promise.all(ef.map(e=>Wh(void 0,void 0,void 0,function*(){let t=sf.get(e);t||(t={ssrcToTrackId:{}},sf.set(e,t));try{const r=yield e.getStats();let i=null;if(r.forEach(e=>{if(!("inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||e.trackIdentifier||t.ssrcToTrackId[e.ssrc])){if(e.mediaSourceId){const i=r.get(e.mediaSourceId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}if(!t.ssrcToTrackId[e.ssrc]&&e.trackId){const i=r.get(e.trackId);i&&i.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=i.trackIdentifier)}t.ssrcToTrackId[e.ssrc]||(i||(i=[]),i.push(e.ssrc))}}),i){const r=[...e.getSenders(),...e.getReceivers()];(yield Promise.all(r.map(e=>e.getStats()))).forEach((e,i)=>{e.forEach(e=>{"inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||(t.ssrcToTrackId[e.ssrc]=r[i].track.id)})}),i.forEach(e=>{t.ssrcToTrackId[e]||(t.ssrcToTrackId[e]="?"+e)})}return[e,r,t]}catch(r){return Zh.sendEvent("trackSsrcLookupFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message}),[e,[],t]}})));function af(e,t,r){return Wh(this,arguments,void 0,function*(e,{logger:t,interval:r},i){const n=af.bind(null,e,{interval:r,logger:t});try{const t=e.getClients(),a=t.find(e=>e.isLocalClient&&!e.isPresentation)||{id:"unknown"};let c=e.statsByView[a.id];c||(c={tracks:{},candidatePairs:{},pressure:null},e.statsByView[a.id]=c),c.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return i?e.statsByView:(e.subscriptions.forEach(r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)}),void(e.nextTimeout=setTimeout(n,r)));if(e.lastUpdateTime=Date.now(),(yield of()).forEach(([i,n,s])=>{const o=(e=>{var t;return null===(t=rf.get(e))||void 0===t?void 0:t.index})(i);"closed"===i.connectionState&&(n=new Map,nf(i)),s.previousSSRCs=s.currentSSRCs||{},s.currentSSRCs={},n.forEach(i=>{var d,l,u;if("candidate-pair"===i.type&&/inprogress|succeeded/.test(i.state)){const t=null===(d=s._oldReport)||void 0===d?void 0:d.get(i.id),a=t?i.timestamp-t.timestamp:r,l=o+":"+i.id;let u=c.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},c.candidatePairs[l]=u),function(e,t,r,i,n){const s=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0),o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.bitrateIn=8e3*s/i,e.bitrateOut=8e3*o/i,e.state=t.state,e.roundTripTime=t.currentRoundTripTime,e.requestsSent=t.requestsSent,e.responsesReceived=t.responsesReceived,e.requestsReceived=t.requestsReceived,e.responsesSent=t.responsesSent,e.availableOutgoingBitrate=t.availableOutgoingBitrate,e.availableIncomingBitrate=t.availableIncomingBitrate;const a=n.get(t.remoteCandidateId),c=n.get(t.localCandidateId);e.usingTurn=!1,c&&/relay/i.test(c.candidateType||"")&&(e.usingTurn=!0,e.turnProtocol=c.relayProtocol),a&&c&&(e.localEp=`${c.protocol}:${c.address||c.ip}:${c.port} ${c.candidateType} (${c.networkType})`,e.remoteEp=`${a.protocol}:${a.address||a.ip}:${a.port} ${a.candidateType}`)}(u,i,t,a,n),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===i.type||"outbound-rtp"===i.type){const c=i.mediaType||i.kind,d=i.ssrc;let p=i.trackIdentifier||s.ssrcToTrackId[d],h=null===(l=s._oldReport)||void 0===l?void 0:l.get(i.id);if(h&&h.mediaSourceId!==i.mediaSourceId){const e=n.get(i.mediaSourceId);e&&e.trackIdentifier&&(p=e.trackIdentifier,s.ssrcToTrackId[d]=p)}const f=t.find(e=>{var t;return(null===(t=e[c].track)||void 0===t?void 0:t.id)===p})||a;if(!i.trackIdentifier&&s.ssrcToTrackId[d]&&(null===(u=f[c].track)||void 0===u?void 0:u.id)&&f[c].track.id!==s.ssrcToTrackId[d]&&(p=f[c].track.id,s.ssrcToTrackId[d]=f[c].track.id),s.currentSSRCs[d]=f.id,h){const e=n.get(i.transportId),t=s._oldReport.get(h.transportId);(t&&(null==e?void 0:e.selectedCandidatePairId)!==t.selectedCandidatePairId||i.bytesReceived<h.bytesReceived||i.bytesSent<h.bytesSent)&&(h=null)}const m=h?i.timestamp-h.timestamp:r,g=((e,t,r,i,n,s)=>{let o=e[i];o||(o={tracks:{},startTime:t,updated:t},e[i]=o),o.updated=t;let a=o.tracks[n];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[n]=a),a.updated=t;let c=a.ssrcs[s];return c||(c={startTime:t,updated:t,pcIndex:r},a.ssrcs[s]=c),c.updated=t,c})(e.statsByView,e.lastUpdateTime,o,f.id,p,d);!function(e,t,r,i,n){if(e.codec)return;e.kind=t.kind||t.mediaType,e.ssrc=t.ssrc,e.direction="inbound-rtp"===t.type?"in":"out";const s=t.codecId&&n.get(t.codecId);e.codec=s&&[s.mimeType,s.channels&&`${s.channels}ch`,s.clockRate,s.payloadType,t.encoderImplementation||t.decoderImplementation,s.sdpFmtpLine].filter(Boolean).join(" "),e.mid=t.mid,e.rid=t.rid}(g,i,0,0,n),function(e,t,r,i,n){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/i,"in"===e.direction){const n=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+n,e.packetRate=1e3*n/i;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/i,e.lossRatio=s/(s+n)*1e3/i;const o=t.bytesReceived-((null==r?void 0:r.bytesReceived)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesReceived&&(a=t.headerBytesReceived-((null==r?void 0:r.headerBytesReceived)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;if(e.bitrate=8e3*c/i,e.mediaRatio=o/c,"audio"===t.kind){const i=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=i/o}const d=(t.jitterBufferDelay||0)-((null==r?void 0:r.jitterBufferDelay)||0),l=(t.jitterBufferEmittedCount||0)-((null==r?void 0:r.jitterBufferEmittedCount)||0);e.jitter=l?d/l:0}else{const s=t.packetsSent-((null==r?void 0:r.packetsSent)||0);e.packetCount=(e.packetCount||0)+s,e.packetRate=1e3*s/i;const o=t.bytesSent-((null==r?void 0:r.bytesSent)||0);e.byteCount=(e.byteCount||0)+o;let a=0;t.headerBytesSent&&(a=t.headerBytesSent-((null==r?void 0:r.headerBytesSent)||0),e.headerByteCount=(e.headerByteCount||0)+a);const c=o+a;e.bitrate=8e3*c/i,e.mediaRatio=o/c;const d=t.totalPacketSendDelay-((null==r?void 0:r.totalPacketSendDelay)||0);e.sendDelay=d/s;const l=t.retransmittedPacketsSent-((null==r?void 0:r.retransmittedPacketsSent)||0);if(e.retransRatio=l/s*1e3/i,t.remoteId){const r=n.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,i,h,m,n),"video"===c&&function(e,t,r,i,n){e.width=t.frameWidth,e.height=t.frameHeight,e.qualityLimitationReason=t.qualityLimitationReason||"";const s=t.pliCount-((null==r?void 0:r.pliCount)||0);e.pliCount=(e.pliCount||0)+s,e.pliRate=1e3*s/i;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/i,"in"===e.direction){const n=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+n,e.kfRate=1e3*n/i;const s=t.framesDecoded-((null==r?void 0:r.framesDecoded)||0);e.frameCount=(e.frameCount||0)+s;const o=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=o/s,e.fps=1e3*s/i}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/i;const o=t.framesEncoded-((null==r?void 0:r.framesEncoded)||0);e.frameCount=(e.frameCount||0)+o;const a=t.qpSum-((null==r?void 0:r.qpSum)||0);e.qpf=a/o,e.fps=1e3*o/i;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=n.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,i,h,m,n),"audio"===c&&function(e,t,r){const i=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+i,"in"===e.direction){const i=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),n=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(i/n);const s=t.totalSamplesReceived||0,o=t.concealmentEvents||0,a=s-((null==r?void 0:r.totalSamplesReceived)||0),c=t.concealedSamples||0,d=c-((null==r?void 0:r.concealedSamples)||0),l=(t.silentConcealedSamples||0)-((null==r?void 0:r.silentConcealedSamples)||0),u=(t.insertedSamplesForDeceleration||0)-((null==r?void 0:r.insertedSamplesForDeceleration)||0),p=(t.removedSamplesForAcceleration||0)-((null==r?void 0:r.removedSamplesForAcceleration)||0);e.audioSamples=s,e.audioConcealmentEvents=o,e.audioConcealedSamples=c,e.audioConcealment=d?d/a:0,e.audioSilentConcealment=l?l/a:0,e.audioAcceleration=p?p/a:0,e.audioDeceleration=u?u/a:0}}(g,i,h)}}),s._oldReport=n,Object.keys(s.previousSSRCs).filter(e=>!s.currentSSRCs[e]).forEach(t=>{const r=s.previousSSRCs[t];if(r){const i=e.statsByView[r];i&&Object.values(i.tracks).forEach(e=>{e.ssrcs[t]&&delete e.ssrcs[t]})}})}),s=e.statsByView,o=e.lastUpdateTime,Object.entries(s).forEach(([e,t])=>{t.updated<o?delete s[e]:Object.entries(t.tracks).forEach(([e,r])=>{r.updated<o?delete t.tracks[e]:Object.entries(r.ssrcs).forEach(([e,t])=>{t.updated<o&&delete r.ssrcs[e]})})}),Object.entries((null==c?void 0:c.candidatePairs)||{}).forEach(([t,r])=>{const i=r.lastRtcStatsTime===e.lastUpdateTime;r.active=i,i||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete c.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)}),i)return e.statsByView;e.subscriptions.forEach(r=>{var i;return null===(i=r.onUpdatedStats)||void 0===i?void 0:i.call(r,e.statsByView,t)})}catch(r){t.warn(r),e.numFailedStatsReports++,Zh.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}var s,o;e.nextTimeout=setTimeout(n,r)})}const cf={};function df(e,t=cf,r=window.document){e.forEach(({hostnamePattern:e,token:i})=>{const n=`${e}-${i}`;if(!t[n]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=i,r.head.append(e),t[n]=!0}})}const lf={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const uf={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},pf={interval:2e3,logger:new Hh},hf=()=>{var e;return null===(e=uf.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function ff(e,{interval:t,logger:r}){const i=af.bind(null,e,{interval:t,logger:r});let n;try{n=function(e,{sampleRate:t,originTrials:r}=lf,i=globalThis.window){let n;if(df(r),"PressureObserver"in i)return n=new i.PressureObserver(e,{sampleRate:t}),n.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{n.unobserve("cpu")}}}(t=>e.lastPressureObserverRecord=t.pop())}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(i,t),{getUpdatedStats:()=>i(!0),stop:()=>{clearTimeout(e.nextTimeout),n&&n.stop()}}}var mf;const gf=null!==(mf=oi.default)&&void 0!==mf?mf:oi,vf=new Hh,bf=gf.browserDetails.browser,yf=gf.browserDetails.version;function wf(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),i=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);r||(r=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),i=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<r.length;e++)t=t.replace(new RegExp(i[e],"g"),r[e]);return t}function _f(e){return"firefox"!==bf?e:Jr.splitLines(e.trim()).map(e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e).join("\r\n")+"\r\n"}function Sf(e){return function(e,t,r=!1,i=!1){var n,s;try{const o=xi(e);if((null===(n=null==o?void 0:o.ext)||void 0===n?void 0:n.length)&&o.ext.length>0)return e;if((null==o?void 0:o.media.length)<1)return e;const a=null==o?void 0:o.media.flatMap(e=>e.ext||[]),c=(null===(s=a.find(e=>e.uri===t))||void 0===s?void 0:s.value)||[...new Set([0,15,...a.map(e=>e.value)])].sort((e,t)=>e-t).find((e,t,r)=>e+1!==r[t+1])+1;return o.media.forEach(e=>{var n;(r&&"audio"===e.type||i&&"video"===e.type)&&((null===(n=e.ext)||void 0===n?void 0:n.find(e=>e.uri===t))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))}),Di(o)}catch(e){console.error("Error during addAbsCaptureTimeExtMap: ",e)}return e}(e,"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",!0,!0)}function Cf(e,t,r=console){const i=e.getSenders().find(e=>e.track&&"video"===e.track.kind);if(!i)return Promise.resolve();const n=i.getParameters();return n.encodings&&0===n.encodings.length?Promise.resolve():(n.encodings||(n.encodings=[{}]),0===t?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=1e3*t,i.setParameters(n).catch(e=>{r.error("setParameters err: ",e)}))}var Rf;const kf=null!==(Rf=oi.default)&&void 0!==Rf?Rf:oi,Tf=new Hh;class Pf{constructor({peerConnectionId:e,bandwidth:t,deprioritizeH264Encoding:r}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.serverReflexiveCandidateSeen=!1,this.publicHostCandidateSeen=!1,this.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise(e=>{this.registerConnected=e}),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=r}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:i}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=i,this.clientId=e,this.pc=new RTCPeerConnection(r),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}}),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach(t=>{this.pc.addTrack(t,e)}),e.getVideoTracks().forEach(t=>{this.pc.addTrack(t,e)})):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),null==t||t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach(e=>{const t=this.pc.getSenders().find(t=>t.track===e);t&&this.pc.removeTrack(t)}):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return Jr.splitSections(e).map(e=>{if("video"!==Jr.getKind(e))return e;const t=Jr.matchPrefix(e,"a=rtpmap:").map(e=>Jr.parseRtpMap(e)).filter(e=>/h264/i.test(e.name)).map(e=>""+e.payloadType);if(!t.length)return e;const r=Jr.matchPrefix(e,"m=video")[0],i=/(\s\d+)+$/i.exec(r),n=i?i[0]:"",s=[...n.split(" ").filter(e=>e&&!t.includes(e)),...t].join(" "),o=r.replace(n," "+s);return e.replace(r,o)}).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then(()=>{this.earlyIceCandidates.forEach(e=>this.pc.addIceCandidate(e)),this.earlyIceCandidates=[]})}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise(t=>{this.pending.push(()=>this.handleOffer(e).then(t))});this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==bf&&("firefox"!==bf||yf&&yf>=63||60===yf)?e:Jr.splitLines(e.trim()).filter(e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==Jr.parseExtmap(e).uri).join("\r\n")+"\r\n"}(t),t=_f(t);const r={type:e.type,sdp:t};let i;return this._setRemoteDescription(r).then(()=>this.pc.createAnswer()).then(e=>(i=e,this.pc.setLocalDescription(e))).then(()=>Cf(this.pc,this.bandwidth)).then(()=>i)}handleAnswer(e){const t=_f(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then(()=>Cf(this.pc,this.bandwidth),e=>{Tf.warn("Could not set remote description from remote answer: ",e)})}addIceCandidate(e){this.srdComplete?this.srdComplete.then(()=>{"closed"!==this.pc.signalingState&&("safari"===kf.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch(t=>{Tf.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)}))}):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){Tf.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const r=this.pc;if(!r)return!1;const i=r.getSenders();if(e||(e=(i.find(e=>e.track&&e.track.kind===t.kind)||{}).track),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const r=()=>{for(let r=0;r<i.length;r++){const n=i[r].track;if((null==n?void 0:n.id)===t.id)return Promise.resolve(t);if((null==n?void 0:n.id)===e.id)return i[r].replaceTrack(t)}return null};let n=r();if(n)return n;let s=null,o=null;n=new Promise((e,t)=>{s=e,o=t});let a=0,c=setInterval(()=>Wh(this,void 0,void 0,function*(){const e=r();if(!e)return void(3<++a&&(clearInterval(c),c=null,o("No sender track to replace")));clearInterval(c),c=null;const t=yield e;s(t)}),1e3);return n}const n=this.streams.find(e=>e.getTracks().find(e=>e.id===t.id))||this.streams[0];return n?r.addTrack(t,n):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push(()=>{this.replaceTrack(e,t)});this.isOperationPending=!0;const n=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout(()=>{r.onnegotiationneeded=n},0),"offer"===r.localDescription.type?r.createOffer().then(e=>(e.sdp=wf(r.localDescription.sdp,e.sdp),r.setLocalDescription(e))).then(()=>this._setRemoteDescription(r.remoteDescription)):this._setRemoteDescription(r.remoteDescription).then(()=>r.createAnswer()).then(e=>(e.sdp=wf(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&Cf(this.pc,this.bandwidth)):this.pending.push(()=>this.changeBandwidth(e)))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter(e=>{var r,i,n,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(i=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===i?void 0:i.kind)&&!t.includes(null===(s=null===(n=null==e?void 0:e.receiver)||void 0===n?void 0:n.track)||void 0===s?void 0:s.id)&&!t.includes(null===(a=null===(o=null==e?void 0:e.sender)||void 0===o?void 0:o.track)||void 0===a?void 0:a.id)}).forEach(t=>{t.direction=e?"sendonly":"sendrecv"})}}const Of=400;var Ef;const Df=null!==(Ef=oi.default)&&void 0!==Ef?Ef:oi;const xf="fetch_mediaserver_config",If="start_screenshare",Mf="stop_screenshare",jf="audio_enabled",Lf="client_left",Af="mediaserver_config",Nf="new_client",Bf="screenshare_started",Ff="screenshare_stopped",zf="room_joined",Vf="video_enabled",Uf="ice_candidate",$f="ice_endofcandidates",Gf="ready_to_receive_offer",qf="sdp_answer",Hf="sdp_offer",Wf="pending_client_left",Kf="media_quality_changed",Jf="client_connection_status_changed",Qf="stream_added",Xf="rtc_manager_created",Yf="rtc_manager_destroyed",Zf="local_stream_track_added",em="local_stream_track_removed",tm="connecting",rm="connection_failed",im="connection_successful",nm="connection_disconnected",sm="camera",om="screen_share";const am="[a-fA-F\\d:]",cm=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${am})|(?<=${am})(?=\\s|$))`:"",dm="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",lm="[a-fA-F\\d]{1,4}",um=`\n(?:\n(?:${lm}:){7}(?:${lm}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${lm}:){6}(?:${dm}|:${lm}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${lm}:){5}(?::${dm}|(?::${lm}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${lm}:){4}(?:(?::${lm}){0,1}:${dm}|(?::${lm}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${lm}:){3}(?:(?::${lm}){0,2}:${dm}|(?::${lm}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${lm}:){2}(?:(?::${lm}){0,3}:${dm}|(?::${lm}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${lm}:){1}(?:(?::${lm}){0,4}:${dm}|(?::${lm}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${lm}){0,5}:${dm}|(?::${lm}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),pm=new RegExp(`(?:^${dm}$)|(?:^${um}$)`),hm=new RegExp(`^${dm}$`),fm=new RegExp(`^${um}$`),mm=e=>e&&e.exact?pm:new RegExp(`(?:${cm(e)}${dm}${cm(e)})|(?:${cm(e)}${um}${cm(e)})`,"g");mm.v4=e=>e&&e.exact?hm:new RegExp(`${cm(e)}${dm}${cm(e)}`,"g"),mm.v6=e=>e&&e.exact?fm:new RegExp(`${cm(e)}${um}${cm(e)}`,"g");var gm="connection_blocked_by_network",vm="ice_ipv6_seen",bm="ice_mdns_seen",ym="ice_no_public_ip_gathered",wm="ice_no_public_ip_gathered_3sec",_m="ice_restart",Sm="microphone_not_working",Cm="microphone_stopped_working",Rm="camera_stopped_working",km="new_pc",Tm="sfu_connection_open",Pm="sfu_connection_closed",Om="sfu_connection_info",Em="dominant_speaker",Dm="pc_sld_failure",xm="pc_on_answer_failure",Im="pc_on_offer_failure";class Mm extends Error{constructor(e){super(e.message),this.name="AssertionError",this.code="ERR_ASSERTION",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,Error.captureStackTrace&&Error.captureStackTrace(this,e.stackStartFn)}}function jm(e){if(e.message instanceof Error)throw e.message;throw new Mm(e)}function Lm(...e){!function(e,t,r,i){if(!r){let n=!1;if(0===t)n=!0,i="No value argument passed to `assert.ok()`";else if(i instanceof Error)throw i;const s=new Mm({actual:r,expected:!0,message:i,operator:"==",stackStartFn:e});throw s.generatedMessage=n,s}}(Lm,e.length,...e)}const Am={fail:e=>{jm({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:Am.fail})},ok:Lm,notEqual:function e(t,r,i){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&jm({actual:t,expected:r,message:i,operator:"!=",stackStartFn:e})}};Am.ok=Lm;const Nm=new is("Safari17"),Bm={OS:1024,MIS:1024};class Fm extends Ma{static createFactory(){return()=>new Fm}constructor(){super(),this._closed=!1,this._mapMidTransceiver=new Map,this._sendStream=new MediaStream,this._hasDataChannelMediaSection=!1,this._nextSendSctpStreamId=0,this._transportReady=!1}get name(){return"Safari17"}close(){if(Nm.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}getNativeRtpCapabilities(){return Wh(this,void 0,void 0,function*(){Nm.debug("getNativeRtpCapabilities()");const e=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{e.addTransceiver("audio"),e.addTransceiver("video");const t=yield e.createOffer();try{e.close()}catch(e){}const r=xi(t.sdp),i=Ra({sdpObject:r});return xa(i),i}catch(t){try{e.close()}catch(e){}throw t}})}getNativeSctpCapabilities(){return Wh(this,void 0,void 0,function*(){return Nm.debug("getNativeSctpCapabilities()"),{numStreams:Bm}})}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Nm.debug("run()"),this._direction=e,this._remoteSdp=new Ka({iceParameters:t,iceCandidates:r,dtlsParameters:i,sctpParameters:n}),this._sendingRtpParametersByKind={audio:io("audio",d),video:io("video",d)},this._sendingRemoteRtpParametersByKind={audio:no("audio",d),video:no("video",d)},i.role&&"auto"!==i.role&&(this._forcedLocalDtlsRole="server"===i.role?"client":"server"),this._pc=new RTCPeerConnection(Object.assign({iceServers:null!=s?s:[],iceTransportPolicy:null!=o?o:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},a),c),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",()=>{this.emit("@connectionstatechange",this._pc.connectionState)}):this._pc.addEventListener("iceconnectionstatechange",()=>{switch(Nm.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected");break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed")}})}updateIceServers(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),Nm.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)})}restartIce(e){return Wh(this,void 0,void 0,function*(){if(this.assertNotClosed(),Nm.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=yield this._pc.createOffer({iceRestart:!0});Nm.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();Nm.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t)}})}getTransportStats(){return Wh(this,void 0,void 0,function*(){return this.assertNotClosed(),this._pc.getStats()})}send(e){return Wh(this,arguments,void 0,function*({track:e,encodings:t,codecOptions:r,codec:i,onRtpSender:n}){var s;this.assertNotClosed(),this.assertSendDirection(),Nm.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const o=Is(this._sendingRtpParametersByKind[e.kind]);o.codecs=so(o.codecs,i),t&&t.length>1&&t.every(({rid:e})=>!e)&&(t=t.map((e,t)=>(e.rid=`r${t}`,e))),t&&(o.encodings||(o.encodings=[]),Object.assign(o.encodings,t));const a=Za((null!=t?t:[{}])[0].scalabilityMode);if(o.encodings&&o.encodings.length>1&&("video/vp8"===o.codecs[0].mimeType.toLowerCase()||"video/h264"===o.codecs[0].mimeType.toLowerCase()))for(const e of o.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${a.temporalLayers}`:e.scalabilityMode="L1T3";const c=Is(this._sendingRemoteRtpParametersByKind[e.kind]);c.codecs=so(c.codecs,i);const d=this._remoteSdp.getNextMediaSectionIdx(),l=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:"video"===e.kind?t:void 0});n&&n(l.sender);const u=yield this._pc.createOffer(),p=xi(u.sdp);let h=p.media[d.idx];this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:p})),Nm.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),yield this._pc.setLocalDescription(u);const f=l.mid;o.mid=f,h=p.media[d.idx],o.rtcp.cname=Ta({offerMediaObject:h}),this._remoteSdp.send({offerMediaObject:h,reuseMid:d.reuseMid,offerRtpParameters:o,answerRtpParameters:c,codecOptions:r});const m={type:"answer",sdp:this._remoteSdp.getSdp()};return Nm.debug("send() | calling pc.setRemoteDescription() [answer:%o]",m),yield this._pc.setRemoteDescription(m),this._mapMidTransceiver.set(f,l),{localId:f,rtpParameters:o,rtpSender:l.sender}})}stopSending(e){return Wh(this,void 0,void 0,function*(){if(this.assertSendDirection(),this._closed)return;Nm.debug("stopSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender);if(this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch(e){}const r=yield this._pc.createOffer();Nm.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)})}pauseSending(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("pauseSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);const r=yield this._pc.createOffer();Nm.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)})}resumeSending(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("resumeSending() [localId:%s]",e);const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);const r=yield this._pc.createOffer();Nm.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),yield this._pc.setLocalDescription(r);const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i)})}replaceTrack(e,t){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),t?Nm.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Nm.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");yield r.sender.replaceTrack(t)})}setMaxSpatialLayer(e,t){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{e.active=r<=t}),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();Nm.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)})}setRtpEncodingParameters(e,t){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection(),Nm.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((e,r)=>{i.encodings[r]=Object.assign(Object.assign({},e),t)}),yield r.sender.setParameters(i),this._remoteSdp.muxMediaSectionSimulcast(e,i.encodings);const n=yield this._pc.createOffer();Nm.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",n),yield this._pc.setLocalDescription(n);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",s),yield this._pc.setRemoteDescription(s)})}getSenderStats(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertSendDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()})}sendDataChannel(e){return Wh(this,arguments,void 0,function*({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:i,protocol:n}){var s;this.assertNotClosed(),this.assertSendDirection();const o={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:n};Nm.debug("sendDataChannel() [options:%o]",o);const a=this._pc.createDataChannel(i,o);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Bm.MIS,!this._hasDataChannelMediaSection){const e=yield this._pc.createOffer(),t=xi(e.sdp),r=t.media.find(e=>"application"===e.type);this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(s=this._forcedLocalDtlsRole)&&void 0!==s?s:"client",localSdpObject:t})),Nm.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),yield this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const i={type:"answer",sdp:this._remoteSdp.getSdp()};Nm.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",i),yield this._pc.setRemoteDescription(i),this._hasDataChannelMediaSection=!0}return{dataChannel:a,sctpStreamParameters:{streamId:o.id,ordered:o.ordered,maxPacketLifeTime:o.maxPacketLifeTime,maxRetransmits:o.maxRetransmits}}})}receive(e){return Wh(this,void 0,void 0,function*(){var t,r;this.assertNotClosed(),this.assertRecvDirection();const i=[],n=new Map;for(const r of e){const{trackId:e,kind:i,rtpParameters:s,streamId:o}=r;Nm.debug("receive() [trackId:%s, kind:%s]",e,i);const a=null!==(t=s.mid)&&void 0!==t?t:String(this._mapMidTransceiver.size);n.set(e,a),this._remoteSdp.receive({mid:a,kind:i,offerRtpParameters:s,streamId:null!=o?o:s.rtcp.cname,trackId:e})}const s={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),yield this._pc.setRemoteDescription(s);for(const t of e){const{trackId:e,onRtpReceiver:r}=t;if(r){const t=n.get(e),i=this._pc.getTransceivers().find(e=>e.mid===t);if(!i)throw new Error("transceiver not found");r(i.receiver)}}let o=yield this._pc.createAnswer();const a=xi(o.sdp);for(const t of e){const{trackId:e,rtpParameters:r}=t,i=n.get(e),s=a.media.find(e=>String(e.mid)===i);Pa({offerRtpParameters:r,answerMediaObject:s})}o={type:"answer",sdp:Di(a)},this._transportReady||(yield this.setupTransport({localDtlsRole:null!==(r=this._forcedLocalDtlsRole)&&void 0!==r?r:"client",localSdpObject:a})),Nm.debug("receive() | calling pc.setLocalDescription() [answer:%o]",o),yield this._pc.setLocalDescription(o);for(const t of e){const{trackId:e}=t,r=n.get(e),s=this._pc.getTransceivers().find(e=>e.mid===r);if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(r,s),i.push({localId:r,track:s.receiver.track,rtpReceiver:s.receiver})}return i})}stopReceiving(e){return Wh(this,void 0,void 0,function*(){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Nm.debug("stopReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(e.mid)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();Nm.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r);for(const t of e)this._mapMidTransceiver.delete(t)})}pauseReceiving(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Nm.debug("pauseReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="inactive",this._remoteSdp.pauseMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();Nm.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)})}resumeReceiving(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertRecvDirection();for(const t of e){Nm.debug("resumeReceiving() [localId:%s]",t);const e=this._mapMidTransceiver.get(t);if(!e)throw new Error("associated RTCRtpTransceiver not found");e.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(t)}const t={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),yield this._pc.setRemoteDescription(t);const r=yield this._pc.createAnswer();Nm.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",r),yield this._pc.setLocalDescription(r)})}getReceiverStats(e){return Wh(this,void 0,void 0,function*(){this.assertNotClosed(),this.assertRecvDirection();const t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()})}receiveDataChannel(e){return Wh(this,arguments,void 0,function*({sctpStreamParameters:e,label:t,protocol:r}){var i;this.assertNotClosed(),this.assertRecvDirection();const{streamId:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a}=e,c={negotiated:!0,id:n,ordered:s,maxPacketLifeTime:o,maxRetransmits:a,protocol:r};Nm.debug("receiveDataChannel() [options:%o]",c);const d=this._pc.createDataChannel(t,c);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();const e={type:"offer",sdp:this._remoteSdp.getSdp()};Nm.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),yield this._pc.setRemoteDescription(e);const t=yield this._pc.createAnswer();if(!this._transportReady){const e=xi(t.sdp);yield this.setupTransport({localDtlsRole:null!==(i=this._forcedLocalDtlsRole)&&void 0!==i?i:"client",localSdpObject:e})}Nm.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]",t),yield this._pc.setLocalDescription(t),this._hasDataChannelMediaSection=!0}return{dataChannel:d}})}setupTransport(e){return Wh(this,arguments,void 0,function*({localDtlsRole:e,localSdpObject:t}){t||(t=xi(this._pc.localDescription.sdp));const r=ka({sdpObject:t});r.role=e,this._remoteSdp.updateDtlsRole("client"===e?"server":"client"),yield new Promise((e,t)=>{this.safeEmit("@connect",{dtlsParameters:r},e,t)}),this._transportReady=!0})}assertNotClosed(){if(this._closed)throw new Os("method called in a closed handler")}assertSendDirection(){if("send"!==this._direction)throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if("recv"!==this._direction)throw new Error('method can just be called for handlers with "recv" direction')}}const zm={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},Vm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},Um={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},$m={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2",maxBitrate:1e6}]},Gm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2_KEY",maxBitrate:125e4}]},qm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2",maxBitrate:5e5}]},Hm={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2_KEY",maxBitrate:65e4}]},Wm={encodings:[{}]},Km={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},Jm={encodings:[{scaleResolutionDownBy:4,dtx:!0,maxBitrate:15e4},{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},Qm={encodings:[{scalabilityMode:"L2T2_KEY",dtx:!0,maxBitrate:15e5}]},Xm={encodings:[{dtx:!0}]},Ym=(e,t,r,i=!1)=>{const{lowDataModeEnabled:n,simulcastScreenshareOn:s,vp9On:o,svcKeyScalabilityModeOn:a}=r;if("audio"===e)return zm;const c="chrome"===oi.browserDetails.browser&&o;return t?eg({isVp9Available:c,isSomeoneAlreadyPresenting:i,simulcastScreenshareOn:s}):Zm({lowBandwidth:n,isVp9Available:c,svcKeyScalabilityModeOn:a})},Zm=({lowBandwidth:e,isVp9Available:t,svcKeyScalabilityModeOn:r})=>e?t?r?Hm:qm:Um:t?r?Gm:$m:Vm,eg=({isVp9Available:e,isSomeoneAlreadyPresenting:t,simulcastScreenshareOn:r})=>t?e?Qm:Jm:e?Xm:r?Km:Wm;var tg;!function(e){e.H264="video/h264",e.VP9="video/vp9"}(tg||(tg={}));function rg(e,t){const r=e.find(({mimeType:e})=>e.toLowerCase()===t);return r?[...e].sort((e,i)=>e.mimeType.toLowerCase()===t?-1:"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===r.preferredPayloadType?i.mimeType.toLowerCase()===t?1:-1:0):e}function ig(e){return Wh(this,void 0,void 0,function*(){const t=yield Promise.all(e.map(({mimeType:e})=>function(e){return Wh(this,void 0,void 0,function*(){const{powerEfficient:t}=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{width:1280,height:720,bitrate:2580,framerate:24,contentType:e}});return t})}(e).then(t=>[e,t]))),r=Object.fromEntries(t);return e.sort((e,t)=>{const i=r[e.mimeType];return i===r[t.mimeType]?0:i?-1:1})})}function ng(e,t){return Wh(this,void 0,void 0,function*(){return e=function(e,t){const r=e.map(({mimeType:e})=>e).filter((e,t,r)=>r.indexOf(e)===t),i=function(e,{vp9On:t,av1On:r}){return t&&e.unshift("video/vp9"),r&&e.unshift("video/av1"),e}(r,t);return e.sort((e,t)=>{const r=i.indexOf(e.mimeType.toLowerCase()),n=i.indexOf(t.mimeType.toLowerCase());return(r>=0?r:Number.MAX_VALUE)-(n>=0?n:Number.MAX_VALUE)})}(e,t),t.preferHardwareDecodingOn&&(e=yield ig(e)),e})}const sg=new Hh;class og extends bp{constructor(e){super(),this.reconnectThresholdInMs=0,this._socket=e,this._clients={},this._signalDisconnectTime=void 0,this.rtcManager=void 0,this.metrics={roomJoinedLate:0,pendingClientCanceled:0,evaluationFailed:0,roomJoined:0},e.on("disconnect",()=>{this._signalDisconnectTime=Date.now()}),e.on(zf,e=>this._onRoomJoined(e)),e.on(Nf,e=>this._onNewClient(e)),e.on(Lf,e=>this._onClientLeft(e)),e.on(Wf,e=>this._onPendingClientLeft(e)),e.on(jf,e=>this._onAudioEnabled(e)),e.on(Vf,e=>this._onVideoEnabled(e)),e.on(Bf,e=>this._onScreenshareChanged(e,!0)),e.on(Ff,e=>this._onScreenshareChanged(e,!1))}_onRoomJoined(e){return Wh(this,void 0,void 0,function*(){var t;if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),null==e?void 0:e.error)return void this.emit(zf,e);if(!e.selfId)return void this.emit(zf,e);const r=null===(t=e.room.clients.find(t=>e.selfId===t.id))||void 0===t?void 0:t.deviceId;if(!r)return void this.emit(zf,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave)),void this.emit(zf,e);const i=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>i)return this._resetClientState(e),this.emit(zf,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter(e=>!(e.deviceId===r&&e.isPendingToLeave));const n=yield hf();e.room.clients.forEach(t=>{var r;try{if(t.id===e.selfId)return;if(!this._clients[t.id])return void this._addClientToState(t);if(!(null===(r=this.rtcManager)||void 0===r?void 0:r.hasClient(t.id)))return;if(this._hasClientStateChanged({clientId:t.id,webcam:t.isVideoEnabled,mic:t.isAudioEnabled,screenShare:t.streams.length>1}))return;if(this._wasClientSendingMedia(t.id)&&!this._isClientMediaActive(n,t.id))return;t.mergeWithOldClientState=!0}catch(e){sg.error("Failed to evaluate if we should merge client state %o",e),this.metrics.evaluationFailed++}}),e.room.clients.forEach(e=>{e.isPendingToLeave&&this._onPendingClientLeft({clientId:e.id})}),this.metrics.roomJoined++,this.emit(zf,e)})}_onClientLeft(e){var t;const{clientId:r}=e,i=this._clients[r];i&&(clearTimeout(i.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(Lf,e)}_onPendingClientLeft(e){const{clientId:t}=e,r=this._clients[t];r?r.isPendingToLeave||(r.isPendingToLeave=!0,this._wasClientSendingMedia(t)&&(r.checkActiveMediaAttempts=0,this._abortIfNotActive(e))):sg.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,i=this._clients[t];if(i&&i.isPendingToLeave)return clearTimeout(i.timeoutHandler),i.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach(e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(Lf,{clientId:e.clientId})}),this._addClientToState(e.client),this.emit(Nf,e)}_abortIfNotActive(e){return Wh(this,void 0,void 0,function*(){const{clientId:t}=e;let r=this._clients[t];if(!(null==r?void 0:r.isPendingToLeave))return;if(r.checkActiveMediaAttempts++,r.checkActiveMediaAttempts>3)return;(yield this._checkIsActive(t))?r.timeoutHandler=setTimeout(()=>this._abortIfNotActive(e),500):(r=this._clients[t],(null==r?void 0:r.isPendingToLeave)&&(clearTimeout(r.timeoutHandler),delete this._clients[t],this.emit(Lf,e)))})}_checkIsActive(e){return Wh(this,void 0,void 0,function*(){const t=yield hf();return this._isClientMediaActive(t,e)})}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let i=!1;return r&&Object.entries(r.tracks).forEach(([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach(e=>{(e.bitrate||0)>0&&(i=!0)})}),i}_onAudioEnabled(e){const{clientId:t,isAudioEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isAudioEnabled:r})}_onVideoEnabled(e){const{clientId:t,isVideoEnabled:r}=e;this._clients[t]=Object.assign(Object.assign({},this._clients[t]||{}),{isVideoEnabled:r})}_onScreenshareChanged(e,t){const{clientId:r}=e;this._clients[r]=Object.assign(Object.assign({},this._clients[r]||{}),{isScreenshareEnabled:t})}_hasClientStateChanged({clientId:e,webcam:t,mic:r,screenShare:i}){const n=this._clients[e];if(!n)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==n.isVideoEnabled||(r!==n.isAudioEnabled||i!==n.isScreenshareEnabled)}_addClientToState(e){this._clients[e.id]=Object.assign(Object.assign({},this._clients[e.id]||{}),{isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled,isScreenshareEnabled:e.streams.length>1,deviceId:e.deviceId,isPendingToLeave:e.isPendingToLeave,clientId:e.id})}_wasClientSendingMedia(e){const t=this._clients[e];if(!t)throw new Error(`Client ${e} not found in ReconnectManager state`);return t.isAudioEnabled||t.isVideoEnabled||t.isScreenshareEnabled}_getPendingClientsByDeviceId(e){return Object.values(this._clients).filter(t=>t.deviceId===e&&t.isPendingToLeave)}_resetClientState(e){this._clients={},e.room.clients.forEach(t=>{t.id!==e.selfId&&this._addClientToState(t)})}}var ag;const cg=null!==(ag=oi.default)&&void 0!==ag?ag:oi;class dg{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=Gh(e,Object.assign({path:"/protocol/socket.io/v4",randomizationFactor:.5,reconnectionDelay:250,reconnectionDelayMax:5e3,timeout:5e3,transports:["websocket"],withCredentials:!0},t)),this._socket.io.on("reconnect",()=>{this._socket.sendBuffer=[]}),this._socket.io.on("reconnect_attempt",()=>{this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==cg.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]}),r&&(this._reconnectManager=new og(this._socket)),this._socket.on("connect",()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0,this.noopKeepaliveInterval||(this.noopKeepaliveInterval=setInterval(()=>{try{this._socket.connected&&this._socket.io.engine.sendPacket("noop")}catch(e){}},2e3)))}),this._socket.on("disconnect",()=>{this.disconnectTimestamp=Date.now(),this.noopKeepaliveInterval&&(clearInterval(this.noopKeepaliveInterval),this.noopKeepaliveInterval=null)})}setRtcManager(e){this._reconnectManager&&(this._reconnectManager.rtcManager=e)}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}disconnectOnConnect(){this._socket.once("connect",()=>{this._socket.disconnect()})}emit(e,...t){this._socket.emit.apply(this._socket,arguments)}emitIfConnected(e,t){this.isConnected()&&this.emit(e,t)}getTransport(){return this._socket&&this._socket.io&&this._socket.io.engine&&this._socket.io.engine.transport&&this._socket.io.engine.transport.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){const r=[zf,Lf,Nf];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.off(e,t)})}onEngineEvent(e,t){var r;return null===(r=this._socket.io)||void 0===r||r.on(e,t),()=>{var r;null===(r=this._socket.io)||void 0===r||r.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}_interceptEvent(e,t){return this._reconnectManager&&this._reconnectManager.on(e,t),()=>{this._reconnectManager&&this._reconnectManager.removeListener(e,t)}}getGlitchFreeMetrics(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.metrics}getReconnectThreshold(){var e;return null===(e=this._reconnectManager)||void 0===e?void 0:e.reconnectThresholdInMs}}const lg=(e,t)=>{if(!t.useOnlyTURN)return;e.iceTransportPolicy="relay";const r={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[t.useOnlyTURN];r&&(e.iceServers=e.iceServers.filter(e=>e.url&&e.url.match(r)||e.urls&&(e.urls=(e.urls.some?e.urls:[e.urls]).filter(e=>e.match(r)),e.urls.length>0)?e:void 0))},ug=(e,t)=>{if(t&&e){const r=t,i=r.indexOf(":")>0?"":":443",n=":"+r+i;return e.map(e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,n)),t.urls&&(t.urls=t.urls.map(e=>e.replace(/:[^?]*/,n))),t})}return e},pg=[{pattern:/^(?:([^.]+)[.])?(server:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?(localhost:?\d*)/,separator:"."},{pattern:/^(?:([^.]+)[.])?((\d+[.]){3}:?\d*)$/,separator:"."},{pattern:/^(?:([^.]+)-)?(ip-[^.]*[.](?:hereby[.]dev|rfc1918[.]disappear[.]at)(?::\d+|))$/,separator:"-"},{pattern:/^(?:([^.]+)[.])?((:?[^.]+[.]){1,}[^.]+)$/,separator:"."}];function hg({host:e="whereby.com",protocol:t="https:"}={}){let r="",i=e,n=".";for(const{separator:t,pattern:s}of pg){const o=s.exec(e);if(o){r=o[1]||"",i=o[2],n=t;break}}const s=r?`${r}${n}${i}`:i;return{domain:i,domainWithSeparator:`${n}${i}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${i}`,subdomain:r}}var fg,mg;hg(window&&window.location);const gg=null!==(fg=oi.default)&&void 0!==fg?fg:oi,vg=new Hh,bg=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=tm,this.stream=null,this.streamId=null}setup(e){return this.stream=e,this.streamId=e.id,this.setVideoEnabled(this.isVideoEnabled&&e.getVideoTracks().length>0),this.setAudioEnabled(this.isAudioEnabled&&e.getAudioTracks().length>0),this}setStatus(e){return this.status=e,this}setVideoEnabled(e){this.isVideoEnabled=e,this.stream&&this.stream.getVideoTracks().forEach(t=>{t.enabled=e})}setAudioEnabled(e){this.isAudioEnabled=e,this.stream&&this.stream.getAudioTracks().forEach(t=>{t.enabled=e})}static getCameraId(){return"0"}static getTypeFromId(e){return"0"===""+e?sm:om}}.getCameraId(),yg=gg.browserDetails.browser,wg=gg.browserDetails.version;"firefox"===yg&&gg.browserShim&&"shimGetDisplayMedia"in gg.browserShim&&(null===(mg=gg.browserShim)||void 0===mg||mg.shimGetDisplayMedia(window,"screen"));let _g=!1;"chrome"===yg&&window.document.addEventListener("beforeunload",()=>{_g=!0});class Sg{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s}){const{name:o,session:a,iceServers:c,turnServers:d,sfuServer:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._roomName=o,this._roomSessionId=a&&a.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._screenshareVideoTrackIds=[],this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction=null,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._isAudioOnlyMode=!1,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{Zh.sendEvent("audio_ended",{unloading:_g}),this._emit(Cm,{})},this._videoTrackOnEnded=()=>{Zh.sendEvent("video_ended",{unloading:_g}),this._emit(Rm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:u}),this.totalSessionsCreated=0}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._roomName===t&&r===!!this._sfuServer}supportsScreenShareAudio(){return!0}addNewStream(e,t,r,i,n=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===bg){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=n.find(e=>"audio"===e.kind);t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=n.find(e=>"video"===e.kind);e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const i=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",i),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",i)})}this._screenshareVideoTrackIds.push(t.getVideoTracks()[0].id),this._shareScreen(e,t)}}replaceTrack(e,t){return"audio"!==t.kind||t.effectTrack||this._monitorAudioTrack(t),"video"!==t.kind||t.effectTrack||this._monitorVideoTrack(t),this._replaceTrackToPeerConnections(e,t)}disconnectAll(){Object.keys(this.peerConnections).forEach(e=>{this.disconnect(e)}),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._socketListenerDeregisterFunctions=[],this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null)}fixChromeAudio(e){if("chrome"!==yg)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then(e=>{const i=e.getAudioTracks()[0];return i.enabled=r.enabled,t.removeTrack(r),t.addTrack(i),this.replaceTrack(r,i)}):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(Af,e=>{e.error?vg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(Gf,e=>{this._connect(e.clientId)}),this._serverSocket.on(Uf,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):vg.warn("No RTCPeerConnection on ICE_CANDIDATE",e)}),this._serverSocket.on($f,e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):vg.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)}),this._serverSocket.on(Hf,e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void vg.warn("No RTCPeerConnection on SDP_OFFER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=(t=i.handleOffer(n).then(t=>{this._emitServerEvent(qf,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})})).catch)||void 0===r||r.call(t,e=>{this._emit(Im,e)})}),this._serverSocket.on(qf,e=>{var t,r;const i=this._getSession(e.clientId);if(!i)return void vg.warn("No RTCPeerConnection on SDP_ANSWER",e);const n=this._transformIncomingSdp(e.message,i.pc);null===(r=null===(t=i.handleAnswer(n))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,e=>{this._emit(xm,e)})}),this._serverSocket.on(zf,e=>{var t,r;if(null==e?void 0:e.error)return;if(null!==(r=null===(t=null==e?void 0:e.room)||void 0===t?void 0:t.sfuServer)&&void 0!==r&&r||!this._wasScreenSharing)return;const i=Object.keys(this.localStreams).find(e=>e!==bg);if(!i)return;const n=this.localStreams[i];if(!n)return void vg.warn("screenshare stream %s not found",i);const s=n.getAudioTracks().length>0;this._emitServerEvent(If,{streamId:i,hasAudioTrack:s})})]}sendAudioMutedStats(e){Zh.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){Zh.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){Zh.sendEvent(e,t)}rtcStatsDisconnect(){Zh.server.close()}rtcStatsReconnect(){Zh.server.connected||Zh.server.connect()}setAudioOnly(e){this._isAudioOnlyMode=e,this._forEachPeerConnection(e=>{e.hasConnectedPeerConnection()&&this._withForcedRenegotiation(e,()=>e.setAudioOnly(this._isAudioOnlyMode,this._screenshareVideoTrackIds))})}setRemoteScreenshareVideoTrackIds(e=[]){const t=this._getFirstLocalNonCameraStream();this._screenshareVideoTrackIds=[...(null==t?void 0:t.track)?[t.track.id]:[],...e]}setRoomSessionId(e){this._roomSessionId=e}_setConnectionStatus(e,t,r){const i=e.connectionStatus;i!==t&&e.peerConnectionId!==this._selfId&&(i===nm&&t===tm||(e.connectionStatus=t,setTimeout(()=>{this._emit(Jf,{streamIds:e.streamIds,clientId:r,status:t,previous:i})},0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach(e=>{e.jitterBufferTarget=Of,e.playoutDelayHint=.4})}catch(e){vg.error("Error during setting jitter buffer target:",e)}}_emitServerEvent(e,t,r){this._serverSocket.emit(e,t,r)}_emit(e,t){this._emitter.emit(e,t)}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let r=this.peerConnections[e];if(void 0===r){const i="safari"===yg&&wg&&wg>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new Pf({peerConnectionId:e,bandwidth:t,deprioritizeH264Encoding:i}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[bg]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter(e=>e!==bg)}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e,t){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:r,peerConnectionId:i,shouldAddLocalVideo:n}){if(!i)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(i,t),o={optional:[]};"chrome"===yg&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:i}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};var c,d;a.iceServers=ug(a.iceServers,this._features.turnServerOverrideHost),c=a,(d=this._features).addGoogleStunServers&&(c.iceServers=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"},...c.iceServers]),d.addCloudflareStunServers&&(c.iceServers=[{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"},...c.iceServers]),lg(a,this._features),"chrome"===yg&&(a.sdpSemantics="unified-plan");const l=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:n,clientId:e});setTimeout(()=>this._emit(km),0),l.ontrack=t=>{const r=t.streams[0];"default"===r.id&&0===r.getAudioTracks().length||-1===s.streamIds.indexOf(r.id)&&(s.streamIds.push(r.id),this._emit(Qf,{clientId:e,stream:r}),s.connectionStatus===im&&setTimeout(()=>{this._emit(Jf,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:tm})},0))},l.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(l.iceConnectionState){case"checking":t=tm;break;case"connected":case"completed":t=im,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach(e=>{"function"==typeof e&&e()}),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(l.iceConnectionState.match(/connected|completed/)||"chrome"===yg&&l.localDescription&&"answer"===l.localDescription.type)&&(s.wasEverConnected=!0),this._isAudioOnlyMode&&s.setAudioOnly(!0,this._screenshareVideoTrackIds),s.registerConnected();break;case"disconnected":t=nm,setTimeout(()=>{"disconnected"===l.iceConnectionState&&this._maybeRestartIce(e,s)},2e3);break;case"failed":t=rm,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(gm);break;default:return}this._setConnectionStatus(s,t,e)},l.onconnectionstate=()=>{switch(l.connectionState){case"connected":setTimeout(()=>{(function(e){if("chrome"!==Df.browserDetails.browser||Df.browserDetails.browser<58||"closed"===e.signalingState)return Promise.resolve(!1);const t=e.getSenders().some(e=>e.track&&"audio"===e.track.kind),r=e.getReceivers().some(e=>e.track&&"audio"===e.track.kind);return e.getStats(null).then(e=>{let i=!1;return e.forEach(e=>{"outbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!t?"inbound-rtp"!==e.type||"audio"!==e.kind&&"audio"!==e.mediaType||!r||0===e.bytesReceived&&(i="inbound"):0===e.bytesSent&&(i="outbound")}),i})})(s.pc).then(t=>{!1!==t&&this._emit(Sm,{failureDirection:t,clientId:e})})},3e3),s.registerConnected();break;case"failed":const t=rm;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(gm),this._setConnectionStatus(s,t,e)}};const u=this.localStreams[bg];return n&&u&&s.addStream(u),n&&Object.keys(this.localStreams).forEach(e=>{if(e===bg)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then(()=>{this._emitServerEvent(If,{receiverId:s.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(s,()=>s.addStream(t))})}),s}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):vg.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.values(this.peerConnections).forEach(t=>{e(t)})}_addStreamToPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.addStream(e))})}_addTrackToPeerConnections(e,t){this._forEachPeerConnection(r=>{this._withForcedRenegotiation(r,()=>r.addTrack(e,t))})}_replaceTrackToPeerConnections(e,t){const r=[];return this._forEachPeerConnection(i=>{if(!i.hasConnectedPeerConnection()){vg.info("Session doesn't have a connected PeerConnection, adding pending action!");const n=this._pendingActionsForConnectedPeerConnections;if(!n)return void vg.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise((r,s)=>{n.push(()=>{const n=i.replaceTrack(e,t);if(!n)return vg.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");n.then(e=>r(e)).catch(e=>s(e))})});return void r.push(s)}const n=i.replaceTrack(e,t);n?r.push(n):vg.error("replaceTrack returned false!")}),Promise.all(r)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeStream(e))})}_removeTrackFromPeerConnections(e){this._forEachPeerConnection(t=>{this._withForcedRenegotiation(t,()=>t.removeTrack(e))})}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,mediaserverConfigTtlSeconds:i}){this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._mediaserverConfigTtlSeconds=i,this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitServerEvent(xf),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_connect(e){let t=this._getSession(e),r=t&&t.bandwidth||0;return t?(vg.warn("Replacing peer session",e),this._cleanup(e)):r=this._changeBandwidthForAllClients(!0),t=this._createP2pSession({clientId:e,initialBandwidth:r,shouldAddLocalVideo:!0,isOfferer:!0}),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const r=t.pc;"disconnected"!==r.iceConnectionState&&"failed"!==r.iceConnectionState||"offer"===r.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,t.serverReflexiveCandidateSeen=!1,t.publicHostCandidateSeen=!1,t.ipv6HostCandidateSeen=!1,this.ipv6HostCandidateTeredoSeen=!1,this.ipv6HostCandidate6to4Seen=!1,this.mdnsHostCandidateSeen=!1,this._emit(_m),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e){return Wh(this,void 0,void 0,function*(){const{p2pVp9On:t,p2pAv1On:r,redOn:i,preferP2pHardwareDecodingOn:n}=this._features;if(t||r||i||n)try{const s=e.getTransceivers().filter(e=>{var t,r;return"audio"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});s.forEach(e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(i&&"audio/red"===t.codecs[e].mimeType.toLowerCase()){t.codecs.unshift(t.codecs.splice(e,1)[0]);break}void 0!==e.setCodecPreferences&&e.setCodecPreferences(t.codecs)});const o=e.getTransceivers().filter(e=>{var t,r;return"video"===(null===(r=null===(t=null==e?void 0:e.sender)||void 0===t?void 0:t.track)||void 0===r?void 0:r.kind)});yield Promise.all(o.map(e=>Wh(this,void 0,void 0,function*(){if(void 0===RTCRtpReceiver.getCapabilities)return;if(void 0===e.setCodecPreferences)return;const i=RTCRtpReceiver.getCapabilities("video");(t||r||n)&&(i.codecs=yield ng(i.codecs,{vp9On:t,av1On:r,preferHardwareDecodingOn:t||n})),e.setCodecPreferences(i.codecs)})))}catch(e){vg.error("Error during setting setCodecPreferences:",e)}})}_negotiatePeerConnection(e,t,r){if(!t)return void vg.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const i=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push(()=>{this._negotiatePeerConnection(e,t,r)});t.isOperationPending=!0;const{p2pVp9On:n,redOn:s,rtpAbsCaptureTimeOn:o,cleanSdpOn:a}=this._features;this._setCodecPreferences(i).then(()=>i.createOffer(r||this.offerOptions).then(t=>{o&&(t.sdp=Sf(t.sdp)),(n||s)&&"firefox"===yg&&(t.sdp=function(e,t,r){var i,n;try{const s=xi(e);if(Array.isArray(null==s?void 0:s.media)){const e=s.media.find(e=>"audio"===e.type);if(Array.isArray(null==e?void 0:e.rtp)){const t=e.rtp;for(let n=0;n<t.length;n++)if(r&&"red"===t[n].codec){const r=null===(i=e.payloads)||void 0===i?void 0:i.split(" "),s=null==r?void 0:r.indexOf(""+t[n].payload);s&&-1!==s&&s>=0&&(null==r||r.unshift(r.splice(s,1)[0]),e.payloads=null==r?void 0:r.join(" "))}}const o=s.media.find(e=>"video"===e.type);if(Array.isArray(null==o?void 0:o.rtp)){const e=o.rtp;for(let r=0;r<e.length;r++)if(t&&"VP9"===e[r].codec){const t=null===(n=o.payloads)||void 0===n?void 0:n.split(" "),i=null==t?void 0:t.indexOf(""+e[r].payload);i&&-1!==i&&i>=0&&(null==t||t.unshift(t.splice(i,1)[0]),o.payloads=null==t?void 0:t.join(" "))}}}return Di(s)}catch(e){vf.error("setCodecPreferenceSDP error:",e)}}(t.sdp,n,s)),a&&(t.sdp=function(e){try{const t=xi(e);return t.media.forEach(e=>{const t={};e.payloads&&(e.payloads=(""+e.payloads).split(" ").filter(e=>!t[e]&&(t[e]=!0)).join(" "));const r={};e.rtp=e.rtp.filter(e=>!e.payload||t[e.payload]&&!r[e.payload]&&(r[e.payload]=!0));const i={};e.fmtp&&(e.fmtp=e.fmtp.filter(e=>!e.payload||t[e.payload]&&!i[e.payload]&&(i[e.payload]=!0)));const n={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter(e=>!e.payload||t[e.payload]&&!n[e.payload+e.type+e.subtype]&&(n[e.payload+e.type+e.subtype]=!0)))}),Di(t)}catch(e){}return e}(t.sdp)),i.setLocalDescription(t).catch(e=>{throw vg.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(Dm,e),e}).then(()=>{this._emitServerEvent(Hf,{receiverId:e,message:this._transformOutgoingSdp(t)})})}).catch(e=>{vg.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,i=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout(()=>r.onnegotiationneeded=i,0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);const r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:0,2:384,3:256,4:192,5:128,6:128,7:64}[t];return void 0===r?0:(this._forEachPeerConnection(e=>{e.changeBandwidth(r)}),r)}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:i=!1}){const n=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:i}),s=n.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[bg];return r&&o&&!o.getVideoTracks().length&&this._stoppedVideoTrack&&s.addTrack(this._stoppedVideoTrack,o),s.onicegatheringstatechange=e=>{switch(e.target.iceGatheringState){case"gathering":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=setTimeout(()=>{n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(wm)},3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,i;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(i=null==t?void 0:t.candidate)||void 0===i?void 0:i.address;try{if(mm.v4({exact:!0}).test(e)){Bn(e).isPublicIp&&(n.publicHostCandidateSeen=!0)}else if(mm.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new Ii.Address6(e.replace(/^\[(.*)\]/,"$1"));n.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(n.publicHostCandidateSeen=!0),t.isTeredo()&&(n.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(n.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&Hn(t,4)&&(n.mdnsHostCandidateSeen=!0)}}catch(e){vg.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":n.serverReflexiveCandidateSeen||(n.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":n.relayCandidateSeen||(n.relayCandidateSeen=!0)}this._emitServerEvent(Uf,{receiverId:e,message:t.candidate})}else this._emitServerEvent($f,{receiverId:e}),n.publicHostCandidateSeen||n.relayCandidateSeen||n.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(ym),n.ipv6HostCandidateSeen&&this._emit(vm,{teredoSeen:n.ipv6HostCandidateTeredoSeen,sixtofourSeen:n.ipv6HostCandidate6to4Seen}),n.mdnsHostCandidateSeen&&this._emit(bm)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&n.connectionStatus&&this._negotiatePeerConnection(e,n)},n}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let i=this._getSession(t);if(i&&e!==t)return i;let n=i&&i.bandwidth||0;return i?(vg.warn("Replacing peer session",t),this._cleanup(t)):n=this._changeBandwidthForAllClients(!0),i=this._createP2pSession({clientId:t,initialBandwidth:n,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(Gf,{receiverId:t}),i}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout(()=>{0===this.numberOfPeerconnections()&&this.rtcStatsDisconnect()},6e4)}updateStreamResolution(){}stopOrResumeAudio(){}_handleStopOrResumeVideo({enable:e,track:t}){e?this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(t):this._stoppedVideoTrack=t}stopOrResumeVideo(e,t){var r;if(["chrome","safari"].includes(yg))if(!1===t){const i="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emit(em,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},i)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emit(Zf,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})})}}_shareScreen(e,t){this._emitServerEvent(If,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._wasScreenSharing=!0,this._addStreamToPeerConnections(t)}removeStream(e,t,r){this._removeLocalStream(e),this._removeStreamFromPeerConnections(t),this._wasScreenSharing=!1,this._emitServerEvent(Mf,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}var Cg=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:i=1,C:n=1.2}={R:.01,Q:2,A:1.1,B:1,C:1.2}){this.R=e,this.Q=t,this.A=r,this.C=n,this.B=i,this.cov=NaN,this.x=NaN}filter(e,t=0){if(isNaN(this.x))this.x=1/this.C*e,this.cov=1/this.C*this.Q*(1/this.C);else{const r=this.predict(t),i=this.uncertainty(),n=i*this.C*(1/(this.C*i*this.C+this.Q));this.x=r+n*(e-this.C*r),this.cov=i-n*this.C*i}return this.x}predict(e=0){return this.A*this.x+this.B*e}uncertainty(){return this.A*this.cov*this.A+this.R}lastMeasurement(){return this.x}setMeasurementNoise(e){this.Q=e}setProcessNoise(e){this.R=e}},calculateStd:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,r)=>e.concat(Math.pow(r-t,2)),[]).reduce((e,t)=>e+t,0)/e.length},createACFCalculator:()=>{let e=-1,t=0,r=0;return i=>{const n=i.reduce((e,t)=>e+t,0)/i.length;if(e=e<0?n:.95*e+.05*n,++r<2)return t=n,0;const s=(n-e)*(t-e);return t=n,s}},standardDeviation:e=>{const t=e.reduce((e,t)=>e+t,0)/e.length;return{mean:t,SD:Math.sqrt(e.reduce((e,r)=>e+Math.pow(r-t,2),0)/e.length)}},variance:(e,t=!1)=>{const r=e.reduce((e,t)=>e+t,0)/e.length;return e.reduce((e,t)=>e.concat(Math.pow(t-r,2)),[]).reduce((e,t)=>e+t,0)/(e.length-(t?0:1))}});const Rg={minDecibels:-80,maxDecibels:-10,smoothingTimeConstant:.8,aggSize:1,sampleRate:10,reportRate:2,bins:32,bands:[[0,1,2,3],[4,5,6,7]],separateTrack:{autoGainControl:!1,noiseSupression:!1},binFormula:"bin",scoreFormula:"300 * bands[1].avg / Math.max(bands[1].avg + bands[0].avg, 0.01)",outFormula:"score"},kg=new Hh;const Tg=new Hh,Pg=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class Og extends bp{constructor(){super(),this._clients={},this._producers={},this._startMonitor()}close(){clearInterval(this._intervalHandle),delete this._intervalHandle,this._producers={},this._clients={}}_startMonitor(){this._intervalHandle=setInterval(()=>{Object.entries(this._producers).forEach(([e,t])=>{this._evaluateClient(e,t)})},600)}_evaluateClient(e,t){this._clients[e]||(this._clients[e]={audio:{currentQuality:Pg.ok,trend:[]},video:{currentQuality:Pg.ok,trend:[]}}),this._evaluateProducer(e,Object.values(t).filter(e=>"audio"===e.kind),"audio"),this._evaluateProducer(e,Object.values(t).filter(e=>"video"===e.kind),"video")}_evaluateProducer(e,t,r){if(0===t.length)return;const i=t.reduce((e,t)=>e+t.score,0)/t.length,n=this._evaluateScore(i);this._updateTrend(n,this._clients[e][r])&&this.emit(Kf,{clientId:e,kind:r,quality:n})}_updateTrend(e,t){return t.trend.push(e),t.trend.length>3&&t.trend.shift(),!(e===t.currentQuality||!t.trend.every(e=>e!==t.currentQuality))&&(t.currentQuality=e,!0)}addProducer(e,t){e&&t&&"string"==typeof e&&"string"==typeof t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Tg.warn("Missing clientId or producerId")}removeProducer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addConsumer(e,t){e&&t?(this._producers[e]||(this._producers[e]={}),this._producers[e][t]={}):Tg.warn("Missing clientId or consumerId")}removeConsumer(e,t){delete this._producers[e][t],0===Object.keys(this._producers[e]).length&&delete this._producers[e]}addProducerScore(e,t,r,i){Array.isArray(i)&&0!==i.length&&!i.some(e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.map(e=>e.score))}:Tg.warn("Unexpected producer score format")}addConsumerScore(e,t,r,i){i&&i.hasOwnProperty("producerScores")&&Array.isArray(i.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(i.producerScores)}:Tg.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?Pg.warning:e<=7&&e>0?Pg.critical:Pg.ok}_calcAvgProducerScore(e){try{if(!Array.isArray(e)||0===e.length)return 0;let t=0,r=0;return e.forEach(e=>{e>0&&(t+=e,r++)}),0===t||0===r?0:t/r}catch(e){return Tg.error(e),0}}}class Eg{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?Eg._handleRequest(t):t.response?Eg._handleResponse(t):t.message?Eg._handleMessage(t):void 0}static _handleRequest(e){const t={request:!0};if("string"==typeof e.method&&"number"==typeof e.id)return t.id=e.id,t.method=e.method,t.data=e.data||{},t}static _handleResponse(e){const t={response:!0};if("number"==typeof e.id)return t.id=e.id,e.ok?(t.ok=!0,t.data=e.data||{}):(t.ok=!1,t.errorCode=e.errorCode,t.errorReason=e.errorReason),t}static _handleMessage(e){const t={message:!0};if("string"==typeof e.method)return t.method=e.method,t.data=e.data||{},t}static createRequest(e,t){return{request:!0,id:Math.round(1e7*Math.random()),method:e,data:t||{}}}static createSuccessResponse(e,t){return{response:!0,id:e.id,ok:!0,data:t||{}}}static createErrorResponse(e,t,r){return{response:!0,id:e.id,errorCode:t,errorReason:r}}static createMessage(e,t){return{message:!0,method:e,data:t||{}}}}const Dg=new Hh;class xg extends bp{constructor(e,t="whereby-sfu#v4"){super(),this.socket=null,this.wsUrl=e,this.protocol=t,this.sents=new Map,this._setupSocket()}_setupSocket(){this.socket=new WebSocket(this.wsUrl,this.protocol),this.socket.onopen=this._onOpen.bind(this),this.socket.onmessage=this._onMessage.bind(this),this.socket.onclose=this._onClose.bind(this),this.socket.onerror=this._onError.bind(this)}_tearDown(){null!==this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket=null,this.sents.forEach(e=>e.close()),this.emit("close"))}close(){var e;null===(e=this.socket)||void 0===e||e.close()}_onOpen(){Dg.info("Connected"),this.emit("open")}_onMessage(e){const t=Eg.parse(e.data);Dg.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){Dg.info("Disconnected"),this._tearDown()}_onError(e){Dg.info("Error",e)}_handleResponse(e){const t=this.sents.get(e.id);if(e.ok)t.resolve(e.data);else{const r=new Error(e.errorReason);t.reject(r)}}send(e){try{this.socket&&this.socket.send(JSON.stringify(e))}catch(e){}}message(e,t={}){const r=Eg.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const i=Eg.createRequest(e,t);return this.send(i),new Promise((e,t)=>{const n={id:i.id,method:i.method,resolve:t=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),e(t))},reject:e=>{this.sents.delete(i.id)&&(clearTimeout(n.timer),t(e))},timer:setTimeout(()=>{this.sents.delete(i.id)&&t(new Error("request timeout"))},r),close:()=>{clearTimeout(n.timer),t(new Error("transport closed"))}};this.sents.set(i.id,n)})}}function Ig(e){let t,r,i,n,s=[];const o=e=>{s=function(e){return"string"==typeof e?e.split(",").filter(Boolean).map(e=>{const[t,r]=/\|/.test(e)?e.split("|"):["",e];return{host:r,dc:t}}):e.filter(e=>e.host).map(e=>({host:e.host,dc:e.dc||""}))}(e)};let a=!1,c=!1;const d=()=>{if(a)return void(c=!0);a=!0,c=!1;let o=s;if(t){const e=Date.now();e-3e3>(r||0)&&((!n||(i||0)>n)&&e-3e3>(i||0))||(o=[{host:t.host,dc:t.dc}])}const l={};let u=0;o.forEach(({dc:e})=>{void 0===l[e]&&(l[e]=u++)});let p=0;const h={};let f,m=o.length,g=!1,v=!1;const b=n,y=()=>{var t;m--,0!==m||g||(a=!1,c?setTimeout(d,0):null===(t=e.onFailed)||void 0===t||t.call(e))},w=[];o.forEach(({host:i,dc:s},d)=>{if(d>0){p+=500;const e=(h[s]||0)+2e3;p=Math.max(p,e)}h[s]=p,w.push(setTimeout(()=>{var u;if(w.shift(),v)return;if(b!==n)return y(),void w.forEach(e=>{clearTimeout(e),y()});const p=new xg((null===(u=e.getUrlForHost)||void 0===u?void 0:u.call(e,i))||i);let h=!1;p.on("open",()=>{setTimeout(()=>{var r;if(!h)if(f||v)p.close();else{f=p,v=!0;const n=[...new Set(o.slice(0,d).filter(e=>e.host!==i).map(e=>e.host))],u=[...new Set(o.slice(0,d).filter(e=>e.dc!==s).map(e=>e.dc))];t=t?Object.assign(Object.assign({},t),{host:i,dc:s,failedHosts:[...new Set([...n,...t.failedHosts])].filter(e=>e!==i&&!t.usedHosts.includes(e)),failedDCs:[...new Set([...u,...t.failedDCs])].filter(e=>e!==s&&!t.usedDCs.includes(e)),usedHosts:[...new Set([...t.usedHosts,i])],usedDCs:[...new Set([...t.usedDCs,s])],numConnections:t.numConnections+1}):{host:i,dc:s,initialHost:i,initialDC:s,initialHostIndex:d,initialDCIndex:l[s],failedHosts:n,failedDCs:u,usedHosts:[i],usedDCs:[s],numConnections:1,numUsedDCs:1,numUsedHosts:1,numFailedDCs:0,numFailedHosts:0},t.numUsedDCs=t.usedDCs.length,t.numUsedHosts=t.usedHosts.length,t.numFailedDCs=t.failedDCs.length,t.numFailedHosts=t.failedHosts.length,c=!1,a=!1,null===(r=e.onConnected)||void 0===r||r.call(e,p,t)}},100)}),p.on("close",()=>{var t;h=!0,p===f&&(f=void 0,r=Date.now(),g=!0,null===(t=e.onDisconnected)||void 0===t||t.call(e)),y()})},p))})};o(e.initialHostList);return{connect:d,updateHostList:o,networkIsUp:()=>{i=Math.max(Date.now(),i||0)},networkIsPossiblyDown:()=>{n=Date.now()}}}var Mg;const jg=null!==(Mg=oi.default)&&void 0!==Mg?Mg:oi,Lg=new Hh,Ag=jg.browserDetails.browser;let Ng=!1;const Bg=mi(),Fg=mi();"chrome"===Ag&&window.document.addEventListener("beforeunload",()=>Ng=!0);class zg{constructor({selfId:e,room:t,emitter:r,serverSocket:i,webrtcProvider:n,features:s,eventClaim:o}){const{session:a,iceServers:c,turnServers:d,sfuServer:l,sfuServers:u,mediaserverConfigTtlSeconds:p}=t;this._selfId=e,this._room=t,this._roomSessionId=null==a?void 0:a.id,this._emitter=r,this._serverSocket=i,this._webrtcProvider=n,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDevice=(e=>{var t;if(e.isNodeSdk)return new Wn.Device({handlerFactory:fl.createFactory()});let r=Wn.detectDevice()||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);if("Safari12"===r&&"object"==typeof navigator&&"string"==typeof navigator.userAgent){const i=new gp.UAParser(navigator.userAgent).getBrowser();parseInt(null!==(t=i.major)&&void 0!==t?t:"0")>=17&&e.safari17HandlerOn&&(r="Safari17")}return/iphone|ipad/i.test(navigator.userAgent)&&(r=e.safari17HandlerOn?"Safari17":"Safari12"),"Safari17"===r?new Wn.Device({handlerFactory:Fm.createFactory()}):new Wn.Device({handlerName:r})})(s),this._routerRtpCapabilities=null,this._sendTransport=null,this._receiveTransport=null,this._clientStates=new Map,this._streamIdToVideoConsumerId=new Map,this._streamIdToVideoResolution=new Map,this._consumers=new Map,this._dataConsumers=new Map,this._localStreamDeregisterFunction=null,this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._micProducer=null,this._micProducerPromise=null,this._micPaused=!1,this._micScoreProducer=null,this._micScoreProducerPromise=null,this._webcamProducer=null,this._webcamProducerPromise=null,this._webcamPaused=!1,this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._sndTransportIceRestartPromise=null,this._rcvTransportIceRestartPromise=null,this._colocation=null,this._stopCameraTimeout=null,this._audioTrackOnEnded=()=>{Zh.sendEvent("audio_ended",{unloading:Ng}),this._emitToPWA(Cm,{})},this._videoTrackOnEnded=()=>{Zh.sendEvent("video_ended",{unloading:Ng}),this._emitToPWA(Rm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,sfuServers:u,iceServers:(null==c?void 0:c.iceServers)||[],turnServers:d||[],mediaserverConfigTtlSeconds:p}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._isConnectingOrConnected=!1,this._qualityMonitor=new Og,this._qualityMonitor.on(Kf,e=>{this._emitToPWA(Kf,e)}),this._networkIsDetectedUpBySignal=!1}_updateAndScheduleMediaServersRefresh({iceServers:e,turnServers:t,sfuServer:r,sfuServers:i,mediaserverConfigTtlSeconds:n}){var s,o,a;this._iceServers=e,this._turnServers=t,this._sfuServer=r,this._sfuServers=i,!i&&(null==r?void 0:r.fallbackServers)&&(this._sfuServers=r.fallbackServers.map(e=>({host:e.host||e.fqdn,dc:e.dc}))),this._mediaserverConfigTtlSeconds=n,null===(s=this._vegaConnectionManager)||void 0===s||s.updateHostList(this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||r.url);const c={iceServers:this._features.turnServersOn?this._turnServers:this._iceServers};c.iceServers=ug(c.iceServers,this._features.turnServerOverrideHost),null===(o=this._sendTransport)||void 0===o||o.updateIceServers(c),null===(a=this._receiveTransport)||void 0===a||a.updateIceServers(c),this._clearMediaServersRefresh(),n&&(this._fetchMediaServersTimer=setTimeout(()=>this._emitToSignal(xf),1e3*n))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}_onNetworkIsDetectedUpBySignal(){var e;this._networkIsDetectedUpBySignal||(this._networkIsDetectedUpBySignal=!0,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsUp())}_onNetworkIsDetectedPossiblyDownBySignal(){var e;this._networkIsDetectedUpBySignal&&(this._networkIsDetectedUpBySignal=!1,null===(e=this._vegaConnectionManager)||void 0===e||e.networkIsPossiblyDown())}setupSocketListeners(){this._socketListenerDeregisterFunctions.push(()=>this._clearMediaServersRefresh(),this._serverSocket.on(Af,e=>{e.error?Lg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)}),this._serverSocket.on(zf,e=>{(null==e?void 0:e.error)||(this._screenVideoTrack&&this._emitScreenshareStarted(),this._features.sfuReconnectV2On&&this._reconnect&&this._connect())}),this._serverSocket.on("connect",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.onEngineEvent("packet",()=>this._onNetworkIsDetectedUpBySignal()),this._serverSocket.on("disconnect",()=>this._onNetworkIsDetectedPossiblyDownBySignal())),this._connect()}_emitScreenshareStarted(){this._emitToSignal(If,{streamId:Fg,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(this._features.sfuReconnectV2On){if(this._isConnectingOrConnected)return;if(!this._serverSocket.isConnected()){const e=this._serverSocket.getReconnectThreshold();if(!e)return;if(Date.now()>(this._serverSocket.disconnectTimestamp||0)+e)return}this._reconnectTimeOut&&clearTimeout(this._reconnectTimeOut)}if(!this._vegaConnectionManager){const e=this._features.sfuServersOverride||this._sfuServers||this._features.sfuServerOverrideHost||this._sfuServer.url;this._vegaConnectionManager=Ig({initialHostList:e,getUrlForHost:e=>{const t=new URLSearchParams(Object.assign({clientId:this._selfId,organizationId:this._room.organizationId,roomName:this._room.name,eventClaim:this._room.isClaimed?this._eventClaim:null,lowBw:"true"},Object.keys(this._features||{}).filter(e=>this._features[e]&&/^sfu/.test(e)).reduce((e,t)=>Object.assign(Object.assign({},e),{[t]:this._features[t]}),{})));return`wss://${e}?${t.toString()}`},onConnected:(e,t)=>{this._vegaConnection=e,this._vegaConnection.on("message",e=>this._onMessage(e)),this._emitToPWA(Om,t),this._join()},onDisconnected:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()},onFailed:()=>{this._vegaConnection=null,this._isConnectingOrConnected=!1,this._onClose()}})}this._vegaConnectionManager.connect(),this._isConnectingOrConnected=!0}_onClose(){var e,t;Lg.info("_onClose()"),null===(e=this._sendTransport)||void 0===e||e.close(),null===(t=this._receiveTransport)||void 0===t||t.close(),this._sendTransport=null,this._receiveTransport=null,this._streamIdToVideoConsumerId.clear(),this._streamIdToVideoResolution.clear(),this._reconnect&&(this._reconnectTimeOut=setTimeout(()=>this._connect(),1e3)),this._qualityMonitor.close(),this._emitToPWA(Pm)}_join(){return Wh(this,void 0,void 0,function*(){var e,t;Lg.info("join()"),this._emitToPWA(Tm);try{const{routerRtpCapabilities:r}=yield this._vegaConnection.request("getCapabilities");if(!this._routerRtpCapabilities){const t=((e,t)=>{const{vp9On:r,h264On:i}=t,n="chrome"===oi.browserDetails.browser;if(!(null==e?void 0:e.codecs))return e;if(r&&n){const t=rg(e.codecs,tg.VP9);return Object.assign(Object.assign({},e),{codecs:t})}if(i){const t=rg(e.codecs,tg.H264);return Object.assign(Object.assign({},e),{codecs:t})}return e})(r,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}));this._routerRtpCapabilities=t,yield null===(e=this._mediasoupDevice)||void 0===e?void 0:e.load({routerRtpCapabilities:t})}this._vegaConnection.message("setCapabilities",{rtpCapabilities:null===(t=this._mediasoupDevice)||void 0===t?void 0:t.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const i=[];!this._micTrack||this._micProducer||this._micProducerPromise||i.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||i.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||i.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||i.push(this._internalSendScreenAudio()),yield Promise.all(i)}catch(e){Lg.error("_join() [error:%o]",e)}})}_createTransport(e){return Wh(this,void 0,void 0,function*(){var t;const r=e?"createSendTransport":"createRecvTransport",i=yield this._vegaConnection.request("createTransport",{producing:e,consuming:!e,enableTcp:!0,enableUdp:!0,preferUdp:!0,sctpParameters:{enableSctp:!0,numSctpStreams:{OS:1024,MIS:1024},maxSctpMessageSize:262144,sctpSendBufferSize:262144}});i.iceServers=ug(this._features.turnServersOn?this._turnServers:this._iceServers,this._features.turnServerOverrideHost),lg(i,this._features);const n=null===(t=this._mediasoupDevice)||void 0===t?void 0:t[r](i),s=t=>Wh(this,void 0,void 0,function*(){if(Lg.info(`Transport ConnectionStateChanged ${t}`),"disconnected"===t||"failed"===t)if(e){if(this._sndTransportIceRestartPromise)return;this._sndTransportIceRestartPromise=this._restartIce(n).finally(()=>{this._sndTransportIceRestartPromise=null})}else{if(this._rcvTransportIceRestartPromise)return;this._rcvTransportIceRestartPromise=this._restartIce(n).finally(()=>{this._rcvTransportIceRestartPromise=null})}});null==n||n.on("connect",({dtlsParameters:e},t)=>{var r;null===(r=this._vegaConnection)||void 0===r||r.message("connectTransport",{transportId:n.id,dtlsParameters:e}),t()}).on("connectionstatechange",s),null==n||n.observer.once("close",()=>{n.removeListener("connectionstatechange",s)}),e?(null==n||n.on("produce",(e,t,r)=>Wh(this,[e,t,r],void 0,function*({kind:e,rtpParameters:t,appData:r},i,s){var o;try{const{paused:s}=r,{id:a}=yield null===(o=this._vegaConnection)||void 0===o?void 0:o.request("produce",{transportId:n.id,kind:e,rtpParameters:t,paused:s,appData:r});i({id:a})}catch(e){s(e)}})),null==n||n.on("producedata",(e,t,r)=>Wh(this,[e,t,r],void 0,function*({appData:e,sctpStreamParameters:t},r,i){var s;try{const{id:i}=yield null===(s=this._vegaConnection)||void 0===s?void 0:s.request("produceData",{transportId:n.id,sctpStreamParameters:t,appData:e});r({id:i})}catch(e){i(e)}})),this._sendTransport=n):this._receiveTransport=n})}_restartIce(e){return Wh(this,arguments,void 0,function*(e,t=0){if(!e||!("closed"in e)||!("connectionState"in e))return void Lg.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void Lg.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void Lg.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,i=Date.now();if(Number.isFinite(r)&&i-r<3500)return;if(e.appData.iceRestartStarted=i,5<=t)return void Lg.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void Lg.info("_restartIce: Connection is undefined");const{iceParameters:n}=yield this._vegaConnection.request("restartIce",{transportId:e.id});Lg.info("_restartIce: ICE restart iceParameters received from SFU: ",n);const s=yield e.restartIce({iceParameters:n}).then(()=>null).catch(e=>e);if(s)switch(Lg.error(`_restartIce: ICE restart failed: ${s}`),s.message){case"missing transportId":case"no such transport":break;default:yield new Promise(e=>{setTimeout(()=>{e(void 0)},Math.min(3500*Math.pow(2,t),6e4))}),yield this._restartIce(e,t+1)}else yield new Promise(e=>{setTimeout(()=>{e(void 0)},6e4*Math.min(8,t+1))}),"failed"!==e.connectionState&&"disconnected"!==e.connectionState||(yield this._restartIce(e,t+1))})}_internalSendMic(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSendMic()"),this._micProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._micTrack||!this._sendTransport||this._micProducer)return void(this._micProducerPromise=null);const e=this._micPaused,t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._micTrack,disableTrackOnPause:!1,stopTracks:!1},Ym("audio",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:Bg,sourceClientId:this._selfId,screenShare:!1,source:"mic",paused:e}}));e?t.pause():t.resume(),this._micProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",()=>{var e;Lg.info('micProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._micProducer=null,this._micProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)}),this._micTrack!==this._micProducer.track&&(yield this._replaceMicTrack()),this._micPaused!==this._micProducer.paused&&this._pauseResumeMic()}catch(e){Lg.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}}))()})}_internalSetupMicScore(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._micProducer||!this._colocation||this._micScoreProducer)return void(this._micScoreProducerPromise=null);const e=yield this._sendTransport.produceData({ordered:!1,maxPacketLifeTime:3e3,label:"micscore",appData:{producerId:this._micProducer.id,clientId:this._selfId}});this._micScoreProducer=e,e.observer.once("close",()=>{var t;Lg.info('micScoreProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeDataProducers",{dataProducerIds:[e.id]})),this._micScoreProducer=null,this._micScoreProducerPromise=null})}catch(e){Lg.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}}))()})}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){return Wh(this,void 0,void 0,function*(){var e;Lg.info("_replaceMicTrack()"),this._micTrack&&this._micProducer&&!this._micProducer.closed&&this._micProducer.track!==this._micTrack&&(yield this._micProducer.replaceTrack({track:this._micTrack}),null===(e=this._micAnalyser)||void 0===e||e.setTrack(this._micTrack),yield this._replaceMicTrack())})}_pauseResumeMic(){var e,t;Lg.info("_pauseResumeMic()"),this._micProducer&&!this._micProducer.closed&&this._micPaused!==this._micProducer.paused&&(this._micPaused?(this._micProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._micProducer.id]})):(this._micProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._micProducer.id]})),this._pauseResumeMic())}_sendMic(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendMic() [track:%o]",e),this._micTrack=e,this._micProducer?yield this._replaceMicTrack():this._micProducerPromise?void 0:this._sendTransport?yield this._internalSendMic():void 0})}_sendMicScore(e){if(!isNaN(e)&&isFinite(e))if(this._micScoreProducer){if(this._micScoreProducer.closed)return void this._stopMicScoreProducer();try{this._micScoreProducer.send(JSON.stringify({score:e}))}catch(e){Lg.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_internalSendWebcam(){return Wh(this,void 0,void 0,function*(){var e;Lg.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>Wh(this,void 0,void 0,function*(){var e;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},Ym("video",!1,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:Bg,sourceClientId:this._selfId,screenShare:!1,source:"webcam",paused:t}}));t?r.pause():r.resume(),this._webcamProducer=r,this._qualityMonitor.addProducer(this._selfId,r.id),r.observer.once("close",()=>{var e;Lg.info('webcamProducer "close" event'),r.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[r.id]})),this._webcamProducer=null,this._webcamProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,r.id)}),this._webcamTrack&&this._webcamTrack!==(null===(e=this._webcamProducer)||void 0===e?void 0:e.track)&&(this._webcamProducerPromise=null,this._replaceWebcamTrack()),this._webcamPaused!==this._webcamProducer.paused&&this._pauseResumeWebcam()}catch(e){Lg.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null)}}))())})}_replaceWebcamTrack(){return Wh(this,void 0,void 0,function*(){Lg.info("_replaceWebcamTrack()"),this._sendTransport&&this._webcamTrack&&!this._webcamProducerPromise&&(this._webcamProducer||!this._webcamTrack.enabled?this._webcamProducer.track!==this._webcamTrack&&(yield this._webcamProducer.replaceTrack({track:this._webcamTrack}),yield this._replaceWebcamTrack()):yield this._internalSendWebcam())})}_pauseResumeWebcam(){var e,t;Lg.info("_pauseResumeWebcam()"),this._webcamProducer&&!this._webcamProducer.closed&&this._webcamPaused!==this._webcamProducer.paused&&(this._webcamPaused?(this._webcamProducer.pause(),null===(e=this._vegaConnection)||void 0===e||e.message("pauseProducers",{producerIds:[this._webcamProducer.id]})):(this._webcamProducer.resume(),null===(t=this._vegaConnection)||void 0===t||t.message("resumeProducers",{producerIds:[this._webcamProducer.id]})),this._pauseResumeWebcam())}_sendWebcam(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendWebcam() [track:%o]",e),this._webcamTrack=e,this._webcamProducer?yield this._replaceWebcamTrack():this._webcamProducerPromise?void 0:this._sendTransport?yield this._internalSendWebcam():void 0})}_internalSendScreenVideo(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1},Ym("video",!0,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}),this._getIsSomeoneAlreadyPresenting())),{appData:{streamId:Fg,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",()=>{var t;Lg.info('screenVideoProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)}),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack())}catch(e){Lg.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null)}}))()})}_replaceScreenVideoTrack(){return Wh(this,void 0,void 0,function*(){Lg.info("_replaceScreenVideoTrack()"),this._screenVideoTrack&&this._screenVideoProducer&&!this._screenVideoProducer.closed&&this._screenVideoProducer.track!==this._screenVideoTrack&&(yield this._screenVideoProducer.replaceTrack({track:this._screenVideoTrack}),yield this._replaceScreenVideoTrack())})}_sendScreenVideo(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendScreenVideo() [track:%o]",e),this._screenVideoTrack=e,this._screenVideoProducer?yield this._replaceScreenVideoTrack():this._screenVideoProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenVideo():void 0})}_internalSendScreenAudio(){return Wh(this,void 0,void 0,function*(){Lg.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>Wh(this,void 0,void 0,function*(){try{if(!this._screenAudioTrack||!this._sendTransport||this._screenAudioProducer)return void(this._screenAudioProducerPromise=null);const e=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenAudioTrack,disableTrackOnPause:!1,stopTracks:!1},Ym("audio",!0,Object.assign(Object.assign({},this._features),{vp9On:this._features.sfuVp9On}))),{appData:{streamId:Fg,sourceClientId:this._selfId,screenShare:!0,source:"screenaudio",paused:!1}}));this._screenAudioProducer=e,this._qualityMonitor.addProducer(this._selfId,e.id),e.observer.once("close",()=>{var t;Lg.info('screenAudioProducer "close" event'),e.appData.localClosed&&(null===(t=this._vegaConnection)||void 0===t||t.message("closeProducers",{producerIds:[e.id]})),this._screenAudioProducer=null,this._screenAudioProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,e.id)}),this._screenAudioTrack!==this._screenAudioProducer.track&&(yield this._replaceScreenAudioTrack())}catch(e){Lg.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}}))()})}_replaceScreenAudioTrack(){return Wh(this,void 0,void 0,function*(){Lg.info("_replaceScreenAudioTrack()"),this._screenAudioTrack&&this._screenAudioProducer&&!this._screenAudioProducer.closed&&this._screenAudioProducer.track!==this._screenAudioTrack&&(yield this._screenAudioProducer.replaceTrack({track:this._screenAudioTrack}),yield this._replaceScreenAudioTrack())})}_sendScreenAudio(e){return Wh(this,void 0,void 0,function*(){return Lg.info("_sendScreenAudio() [track:%o]",e),this._screenAudioTrack=e,this._screenAudioProducer?yield this._replaceScreenAudioTrack():this._screenAudioProducerPromise?void 0:this._sendTransport?yield this._internalSendScreenAudio():void 0})}_stopProducer(e){Lg.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}_getIsSomeoneAlreadyPresenting(){return!![...this._clientStates.values()].find(e=>e.hasAcceptedScreenStream&&e.screenStream)}isInitializedWith({selfId:e,roomName:t,isSfu:r}){return this._selfId===e&&this._room.name===t&&Boolean(r)}setEventClaim(e){var t;this._eventClaim=e,null===(t=this._vegaConnection)||void 0===t||t.message("eventClaim",{eventClaim:e})}setColocation(e){var t;this._colocation=e,null===(t=this._vegaConnection)||void 0===t||t.message("setColocation",{colocation:e}),e||!this._micScoreProducer||this._micScoreProducerPromise||this._stopMicScoreProducer(),this._syncMicAnalyser(),Zh.sendEvent("colocation_changed",{colocation:e})}setAudioOnly(e){var t;null===(t=this._vegaConnection)||void 0===t||t.message(e?"enableAudioOnly":"disableAudioOnly")}setRemoteScreenshareVideoTrackIds(){}setRoomSessionId(e){this._roomSessionId=e}disconnect(e,t,r){var i;Lg.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r);const n=this._clientStates.get(e);n&&(n.hasAcceptedWebcamStream=!1,n.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)),r&&(this._eventClaim=r,null===(i=this._vegaConnection)||void 0===i||i.message("eventClaim",{eventClaim:r}))}replaceTrack(e,t){"audio"===t.kind&&(t.effectTrack||this._monitorAudioTrack(t),this._micTrack=t,this._replaceMicTrack()),"video"===t.kind&&(t.effectTrack||this._monitorVideoTrack(t),this._webcamTrack=t,this._replaceWebcamTrack())}removeStream(e,t,r){Lg.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(Mf,{streamId:Fg,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null}_onMicAnalyserScoreUpdated(e){var t,r;null===(r=null===(t=this._micAnalyserDebugger)||void 0===t?void 0:t.onScoreUpdated)||void 0===r||r.call(t,e),this._sendMicScore(this._micPaused?0:e.out)}addNewStream(e,t,r,i,n=[]){if("0"===e){this._micPaused=r,this._webcamPaused=i;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=n.find(e=>"video"===e.kind);t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=n.find(e=>"audio"===e.kind);e&&this._monitorAudioTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const o=e=>{const{enable:t,track:r}=e.detail;this._webcamPaused=!t,this._pauseResumeWebcam(),this._handleStopOrResumeVideo({enable:t,track:r})};t.addEventListener("stopresumevideo",o),this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",o)}}else{const e=t.getVideoTracks()[0],r=t.getAudioTracks()[0];e&&this._sendScreenVideo(e),r&&this._sendScreenAudio(r),this._emitScreenshareStarted()}}_syncMicAnalyser(){if(!this._micTrack||!this._colocation||this._micAnalyser)return this._micAnalyser&&!this._colocation?(this._micAnalyser.close(),void(this._micAnalyser=null)):void 0;this._micAnalyser=function({micTrack:e,params:t,onScoreUpdated:r}){const i=new AudioContext;let n=null,s=null,o=null,a=!1;const c=e=>Wh(this,void 0,void 0,function*(){if(o&&a&&o.stop(),a=!1,e&&t.separateTrack)try{const r=yield navigator.mediaDevices.getUserMedia({audio:Object.assign({deviceId:null==o?void 0:o.getSettings().deviceId},t.separateTrack),video:!1});e=r.getAudioTracks()[0],a=!0}catch(e){kg.warn("unable to fetch new track for colocation speaker analysis, using current",e)}if(o=e,s&&(s.disconnect(),s=null),e){const t=new MediaStream([e]);s=i.createMediaStreamSource(t),s.connect(n)}});let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},Rg),e),!n||n.fftSize!==2*t.bins){let e=null;n&&(e=o,c(null)),n=i.createAnalyser(),n.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(n.frequencyBinCount),a=[];n.minDecibels=t.minDecibels,n.maxDecibels=t.maxDecibels,n.smoothingTimeConstant=t.smoothingTimeConstant;const l=t.initScript&&new Function("f","setTrack","lastTrack",t.initScript.join("\n")),u=t.scoreScript&&new Function("bins","g","f",t.scoreScript.join("\n")),p=t.scoreFormula&&new Function("bands",`return ${t.scoreFormula}`),h=t.outFormula&&new Function("score","avg","max","scores",`return ${t.outFormula}`),f=t.binFormula&&new Function("bin","index",`return ${t.binFormula}`);let m=0;const g=l&&l(Cg,c,o);d=setInterval(()=>{n.getByteFrequencyData(s);let e=0;if(p){const r=t.bands.map(e=>{const t=e.map(e=>f(s[e]/255,e));return{avg:t.reduce((e,t)=>e+t,0)/e.length,min:t.reduce((e,t)=>Math.min(e,t/255),Number.MAX_VALUE),max:t.reduce((e,t)=>Math.max(e,t/255),0)}});e=p(r)||0}else u&&(e=u(s,g,Cg),isNaN(e)&&(e=0));if(a.push(e),a.length>t.aggSize&&a.shift(),m++,m>=t.reportRate){m=0;const t=a.reduce((e,t)=>Math.max(e,t),0),i=a.reduce((e,t)=>e+t,0)/a.length,n=h(e,i,t,a);r({bins:s,score:e,max:t,avg:i,out:n})}},1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),i.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){Lg.info("stopOrResumeAudio() [enabled:%s]",t),this._micPaused=!t,this._pauseResumeMic()}_handleStopOrResumeVideo({enable:e,track:t}){e?this._sendWebcam(t):this._webcamProducer&&!this._webcamProducer.closed&&this._webcamProducer.track===t&&(this._stopProducer(this._webcamProducer),this._webcamProducer=null,this._webcamTrack=null)}stopOrResumeVideo(e,t){var r;if(Lg.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(Ag))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then(r=>{const i=r.getVideoTracks()[0];e.addTrack(i),this._monitorVideoTrack(i),this._emitToPWA(Zf,{streamId:e.id,tracks:[i],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:i})})}}else{clearTimeout(this._stopCameraTimeout);const i="ended"===(null===(r=e.getVideoTracks().find(e=>!e.enabled))||void 0===r?void 0:r.readyState)?0:5e3;this._stopCameraTimeout=setTimeout(()=>{e.getVideoTracks().forEach(r=>{!1===r.enabled&&(r.stop(),e.removeTrack(r),this._emitToPWA(em,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))})},i)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){Lg.info("acceptNewStream()",{streamId:e,clientId:t});const r=this._getOrCreateClientState(t);e!==t?(r.hasAcceptedScreenStream=!0,r.hasEmittedScreenStream=!1):(r.hasAcceptedWebcamStream=!0,r.hasEmittedWebcamStream=!1),this._syncIncomingStreamsWithPWA(t)}updateStreamResolution(e,t,{width:r,height:i}){var n,s;Lg.info("updateStreamResolution()",{streamId:e,width:r,height:i});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:i});const c=function(e){let t=0;return e.forEach(e=>{var r,i;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(i=e._appData)||void 0===i?void 0:i.source)||t++}),t}(this._consumers),d=function(e){var t,r,i;return/T3/.test((null===(i=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===i?void 0:i.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:i,uncappedSingleRemoteVideoOn:n}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=i-1;return s<100&&(a=Math.max(i-2,0)),r>8&&0===o&&(a=Math.max(i-2,0)),r<4&&s>300&&0===o&&(o=1),n&&1===r&&(o=2,a=i-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:i},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(n=this._features)||void 0===n?void 0:n.uncappedSingleRemoteVideoOn});a.appData.spatialLayer===l&&a.appData.temporalLayer===u||(a.appData.spatialLayer=l,a.appData.temporalLayer=u,null===(s=this._vegaConnection)||void 0===s||s.message("setConsumersPreferredLayers",{consumerIds:[o],spatialLayer:l,temporalLayer:u}))}disconnectAll(){var e,t,r,i;this._reconnect=!1,this._reconnectTimeOut&&(clearTimeout(this._reconnectTimeOut),this._reconnectTimeOut=null),this._socketListenerDeregisterFunctions.forEach(e=>{e()}),this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null),this._socketListenerDeregisterFunctions=[],null===(e=this._vegaConnection)||void 0===e||e.removeAllListeners(),null===(t=this._vegaConnection)||void 0===t||t.close(),null===(r=this._sendTransport)||void 0===r||r.close(),null===(i=this._receiveTransport)||void 0===i||i.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDevice=null}sendAudioMutedStats(e){Zh.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){Zh.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){Zh.sendEvent(e,t)}rtcStatsDisconnect(){Zh.server.close()}rtcStatsReconnect(){Zh.server.connected||Zh.server.connect()}_monitorAudioTrack(e){var t,r;(null===(t=this._audioTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._audioTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._audioTrackOnEnded),e.addEventListener("ended",this._audioTrackOnEnded),this._audioTrackBeingMonitored=e)}_monitorVideoTrack(e){var t,r;(null===(t=this._videoTrackBeingMonitored)||void 0===t?void 0:t.id)!==e.id&&(null===(r=this._videoTrackBeingMonitored)||void 0===r||r.removeEventListener("ended",this._videoTrackOnEnded),e.addEventListener("ended",this._videoTrackOnEnded),this._videoTrackBeingMonitored=e)}_onMessage(e){return Wh(this,void 0,void 0,function*(){const{method:t,data:r}=e;return Promise.resolve().then(()=>{switch(t){case"consumerReady":return this._onConsumerReady(r);case"consumerClosed":return this._onConsumerClosed(r);case"consumerPaused":return this._onConsumerPaused(r);case"consumerResumed":return this._onConsumerResumed(r);case"dataConsumerReady":return this._onDataConsumerReady(r);case"dataConsumerClosed":return this._onDataConsumerClosed(r);case"dominantSpeaker":return this._onDominantSpeaker(r);case"consumerScore":return this._onConsumerScore(r);case"producerScore":return this._onProducerScore(r);default:return void Lg.info(`unknown message method "${t}"`)}}).catch(e=>{Lg.error('"message" failed [error:%o]',e)})})}_onConsumerReady(e){return Wh(this,void 0,void 0,function*(){Lg.info("_onConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consume(e);if(t.pause(),t.appData.localPaused=!0,t.appData.spatialLayer=2,this._consumers.set(t.id,t),this._qualityMonitor.addConsumer(t.appData.sourceClientId,t.id),t.observer.once("close",()=>{this._consumers.delete(t.id),this._qualityMonitor.removeConsumer(t.appData.sourceClientId,t.id),this._consumerClosedCleanup(t)}),this._features.increaseIncomingMediaBufferOn&&t.rtpReceiver)try{t.rtpReceiver.jitterBufferTarget=Of,t.rtpReceiver.playoutDelayHint=.4}catch(e){Lg.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:i,streamId:n}=t.appData,s=this._getOrCreateClientState(r);i?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=n):(s.hasEmittedWebcamStream=!1,s.camStreamId=n);let o=i?s.screenStream:s.webcamStream;o&&o.inboundId===n||(o=new MediaStream,o.inboundId=n,i?s.screenStream=o:s.webcamStream=o),"video"===t.kind&&this._streamIdToVideoConsumerId.set(o.id,t.id),o.addTrack(t.track),this._syncIncomingStreamsWithPWA(r);const a=this._streamIdToVideoResolution.get(o.id);a&&(this.updateStreamResolution(o.id,null,a),this._streamIdToVideoResolution.delete(o.id))})}_onConsumerClosed(e){return Wh(this,arguments,void 0,function*({consumerId:e,reason:t}){var r;Lg.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()})}_onConsumerPaused({consumerId:e}){Lg.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){Lg.info("_onConsumerResumed()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!1,t.appData.localPaused||t.resume())}_onConsumerScore({consumerId:e,kind:t,score:r}){Lg.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:i}}=this._consumers.get(e)||{appData:{}};i&&this._qualityMonitor.addConsumerScore(i,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){Lg.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach(i=>{(null==i?void 0:i.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)})}_onDataConsumerReady(e){return Wh(this,void 0,void 0,function*(){Lg.info("_onDataConsumerReady()",{id:e.id,producerId:e.producerId});const t=yield this._receiveTransport.consumeData(e);this._dataConsumers.set(t.id,t),t.once("close",()=>{this._dataConsumers.delete(t.id)});const{clientId:r}=t.appData;t.on("message",e=>{var r;if(!this._micAnalyserDebugger)return;if("string"!=typeof e)return;const{score:i}=JSON.parse(e);i&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,i))}),this._syncIncomingStreamsWithPWA(r)})}_onDataConsumerClosed(e){return Wh(this,arguments,void 0,function*({dataConsumerId:e,reason:t}){Lg.info("_onDataConsumerClosed()",{dataConsumerId:e,reason:t});const r=this._dataConsumers.get(e);null==r||r.close()})}_onDominantSpeaker({consumerId:e}){const t=this._consumers.get(e);if(!t)return;const{sourceClientId:r}=t.appData;this._emitToPWA(Em,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,i=this._getOrCreateClientState(t),n=r?i.screenStream:i.webcamStream;n&&(n.removeTrack(e.track),0===n.getTracks().length&&(this._streamIdToVideoConsumerId.delete(n.id),this._streamIdToVideoResolution.delete(n.id),r?(i.screenStream=void 0,i.hasEmittedScreenStream=!1,i.screenShareStreamId=void 0):(i.hasEmittedWebcamStream=!1,i.camStreamId=void 0)))}_syncIncomingStreamsWithPWA(e){var t,r;const i=this._getOrCreateClientState(e),{webcamStream:n,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=i,p=[],h=[];this._consumers.forEach(t=>{if(t.appData.sourceClientId!==e)return;const r=t.appData.screenShare?d:c;!t.appData.localPaused!==r&&(r?(t.appData.remotePaused||t.resume(),t.appData.localPaused=!1,h.push(t.id)):(t.pause(),t.appData.localPaused=!0,p.push(t.id)))}),p.length>0&&(null===(t=this._vegaConnection)||void 0===t||t.message("pauseConsumers",{consumerIds:p})),h.length>0&&(null===(r=this._vegaConnection)||void 0===r||r.message("resumeConsumers",{consumerIds:h})),n&&!o&&c&&(this._emitToPWA(Qf,{clientId:e,stream:n,streamId:u,streamType:"webcam"}),i.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(Qf,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),i.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1},this._clientStates.set(e,t)),t}_emitToPWA(e,t){this._emitter.emit(e,t)}_emitToSignal(e,t,r){this._serverSocket.emit(e,t,r)}shouldAcceptStreamsFromBothSides(){return!0}setMicAnalyserDebugger(e){this._micAnalyserDebugger=e}setMicAnalyserParams(e){var t;null===(t=this._micAnalyser)||void 0===t||t.setParams(e)}hasClient(e){return this._clientStates.has(e)}}class Vg{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:i}){this.emitter=e,this.currentManager=null,t.on(zf,({room:n,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:n,emitter:e,serverSocket:t,webrtcProvider:r,features:i,eventClaim:a},d=!!n.sfuServer;if(Ug=d?"group":"normal",this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:n.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(Yf)}let l=null;l=d?new zg(c):new Sg(c),l.rtcStatsReconnect(),l.setupSocketListeners(),e.emit(Xf,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)})}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(Yf))}}let Ug="";const $g=()=>Ug,Gg=new Hh,qg={print:(...e)=>console.debug(e[0],...e.slice(1))};Gg.withDebugLogger(qg);const Hg=new class{constructor(){this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD=.04,this.END_PACKET_LOSS_PERIOD_THRESHOLD=.005,this.INTERVAL_DIFF_THRESHOLD_MS=4e3,this.STALE_MEASUREMENT_TIMEOUT_MS=1e4,this.MINIMUM_INTERVAL_MS=3e4,this.ssrcsHistory=new Map,this.staleMeasurementTimeouts=new Map}addPacketLossMeasurement(e,t,r){this.handleStaleMeasurements(e);const i=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let n=this.ssrcsHistory.get(e);if(!n)return n={id:e,hasActivePacketLoss:i,currPeriod:i?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,n);n.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(n,r),n.prevIntervalInMs&&n.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):i&&(n.hasActivePacketLoss=!0,n.currPeriod={begin:r})}hasPeriodicPacketLoss(e,t){const r=this.ssrcsHistory.get(e);return r&&this.prevIntervalExceeded(r,t)?(this.ssrcsHistory.delete(r.id),!1):(null==r?void 0:r.hasPeriodicPacketLoss)||!1}prevIntervalExceeded(e,t){if(e.prevPeriod&&e.prevIntervalInMs){return t>this.calculatePeriodCenterTimestamp(e.prevPeriod)+e.prevIntervalInMs+this.INTERVAL_DIFF_THRESHOLD_MS}return!1}handleStaleMeasurements(e){const t=this.staleMeasurementTimeouts.get(e);t&&clearTimeout(t),this.staleMeasurementTimeouts.set(e,setTimeout(()=>{Gg.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)},this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(Gg.debug("endPacketLossPeriod() [ssrcId: %s, timestamp: %s]",e.id,t),!e.currPeriod)throw new Error("No packet loss period for "+e.id);e.prevPeriod?(e.currPeriod.end=t,this.addNewPacketLossInterval(e)):e.prevPeriod=Object.assign(Object.assign({},e.currPeriod),{end:t}),delete e.currPeriod,e.hasActivePacketLoss=!1}addNewPacketLossInterval(e){if(Gg.debug("addNewPacketLossInterval() [ssrcId: %s, prevIntervalInMs: %s]",e.id,e.prevIntervalInMs),!e.currPeriod||!e.prevPeriod)throw new Error("missing period timestamps");const t=this.calculatePeriodCenterTimestamp(e.prevPeriod),r=this.calculatePeriodCenterTimestamp(e.currPeriod)-t;if(e.prevIntervalInMs){const t=Math.abs(e.prevIntervalInMs-r);e.hasPeriodicPacketLoss=t<this.INTERVAL_DIFF_THRESHOLD_MS,Gg.debug("addNewPacketLossInterval() [hasPeriodicPacketLoss: %s, intervalDiffInMs: %s]",t<this.INTERVAL_DIFF_THRESHOLD_MS,t)}e.prevIntervalInMs=r,e.prevPeriod=e.currPeriod}calculatePeriodCenterTimestamp(e){if(!e.end)throw new Error("Missing period end timestamp");return e.begin+(e.end-e.begin)/2}},Wg=[{id:"desync",enabled:({client:e,track:t,stats:r})=>!e.isLocalClient&&"audio"===(null==t?void 0:t.kind)&&"object"==typeof(null==r?void 0:r.tracks)&&Object.keys(r.tracks).length>1,check:({stats:e})=>{if(!e)return!1;const t={audio:0,video:0};Object.values(e.tracks).flatMap(e=>Object.values(e.ssrcs)).forEach(e=>{"audio"===e.kind&&e.jitter&&e.jitter>t.audio&&(t.audio=e.jitter),"video"===e.kind&&e.jitter&&e.jitter>t.video&&(t.video=e.jitter)});return Math.abs(1e3*t.audio-1e3*t.video)>500}},{id:"no-track",enabled:()=>!0,check:({client:e,clients:t,kind:r,track:i})=>{if(!i&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return!i}},{id:"ended-track",enabled:({track:e})=>!!e,check:({track:e})=>"ended"===(null==e?void 0:e.readyState)},{id:"no-track-stats",enabled:({hasLiveTrack:e})=>e,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(0===i.length&&!e.isLocalClient&&"video"===r){const e=t.find(e=>e.isLocalClient);if(e)return!e.isAudioOnlyModeEnabled}return 0===i.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let i=!1;if(r.forEach(e=>{i=i||((null==e?void 0:e.bitrate)||0)>0}),!i&&e.isLocalClient){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}return!i}},{id:"denoiser-context-suspended",enabled:({client:e,kind:t})=>{var r,i;return e.isLocalClient&&"audio"===t&&!!(null===(i=null===(r=e.audio)||void 0===r?void 0:r.track)||void 0===i?void 0:i._denoiserCtx)},check:({track:e})=>{var t;return!(!e||!("_denoiserCtx"in e))&&"suspended"===(null===(t=e._denoiserCtx)||void 0===t?void 0:t.state)}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!i.isPresentation,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&(((null==e?void 0:e.height)||0)<200&&e.bitrate<3e4)},{id:"quality-limitation-bw",enabled:({hasLiveTrack:e,stats:t,client:r,clients:i,kind:n})=>{if("normal"===$g()){if(i.filter(e=>!e.isLocalClient).some(e=>e.isAudioOnlyModeEnabled))return!1}return e&&r.isLocalClient&&"video"===n&&!!t},check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"bandwidth"===e.qualityLimitationReason))},{id:"quality-limitation-cpu",enabled:({hasLiveTrack:e,stats:t,client:r,kind:i})=>e&&r.isLocalClient&&"video"===i&&!!t,check:({stats:e})=>!!e&&!!Object.values(e.tracks).find(e=>Object.values(e.ssrcs).find(e=>"cpu"===e.qualityLimitationReason))},{id:"high-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>2},{id:"extreme-plirate",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.height,check:({ssrc0:e})=>((null==e?void 0:e.pliRate)||0)>5},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"in"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.lossRatio)||0)>.1},{id:"high-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.02},{id:"extreme-packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&"out"===t.direction,check:({ssrc0:e})=>((null==e?void 0:e.fractionLost)||0)>.1},{id:"fps-below-20",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.height)||0)>180&&((null==e?void 0:e.fps)||0)<20},{id:"fps-below-10",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:i})=>e&&!!t&&!!t.height&&"video"===r&&!i.isPresentation,check:({ssrc0:e})=>((null==e?void 0:e.fps)||0)<10},{id:"bad-network",enabled:({hasLiveTrack:e,ssrcs:t})=>e&&t.length>0,check:({client:e,clients:t,kind:r,ssrcs:i})=>{if(!i.some(e=>((null==e?void 0:e.bitrate)||0)>0)&&e.isLocalClient&&"video"===r){const e=t.filter(e=>!e.isLocalClient);if(e.length>0)return!e.every(e=>e.isAudioOnlyModeEnabled)}const n=i[0];return!!n&&(0===n.bitrate||(n.lossRatio||0)>.03||(n.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==n?void 0:n.bitrate)&&n.bitrate<3e4||"in"===n.direction&&!!n.pliRate&&n.pliRate>2)}},{id:"periodic-packet-loss",enabled:({client:e,hasLiveTrack:t,ssrc0:r})=>e.isLocalClient&&t&&!!(null==r?void 0:r.ssrc)&&"out"===(null==r?void 0:r.direction)&&((null==r?void 0:r.bitrate)||0)>0,check:({ssrc0:e})=>!(!e||!e.ssrc)&&(Hg.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),Hg.hasPeriodicPacketLoss(e.ssrc,Date.now()))},{id:"cpu-pressure-serious",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"serious"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"cpu-pressure-critical",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},check:({stats:e})=>{var t;return"critical"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)}},{id:"concealed",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===(null==e?void 0:e.direction)&&((null==e?void 0:e.audioLevel)||0)>=.001&&((null==e?void 0:e.audioConcealment)||0)>=.1},{id:"decelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&((null==e?void 0:e.audioDeceleration)||0)>=.1},{id:"accelerated",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&"audio"===r,check:({ssrc0:e})=>!!(null==e?void 0:e.bitrate)&&"in"===e.direction&&(e.audioLevel||0)>=.001&&(e.audioAcceleration||0)>=.1}];let Kg=[],Jg=null;const Qg=[{id:"bitrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&!!t&&!!r,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+((null==t?void 0:t.bitrate)||0),0)},{id:"pixelrate",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.fps||0)*(t.width||0)*(t.height||0),0)},{id:"height",enabled:({hasLiveTrack:e,track:t,trackStats:r,ssrc0:i,kind:n})=>e&&"video"===n&&!!r&&!!t&&!!i&&!!i.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>Math.max(e,t.fps>0?t.height:0),0)},{id:"sourceHeight",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.sourceHeight&&"out"===r.direction,value:({ssrc0:e})=>null==e?void 0:e.sourceHeight},{id:"packetloss",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate,value:({ssrc0:e})=>("in"===(null==e?void 0:e.direction)?e.lossRatio:null==e?void 0:e.fractionLost)||0},{id:"jitter",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"in"===t.direction,value:({ssrc0:e})=>null==e?void 0:e.jitter},{id:"mos",enabled:({hasLiveTrack:e,ssrc0:t})=>e&&!!t&&!!t.bitrate&&"out"===t.direction,value:({ssrc0:e})=>{const t=((null==e?void 0:e.roundTripTime)||0)+2*((null==e?void 0:e.jitter)||0)+10;let r=t<160?93.2-t/40:93.2-(t-120)/10;r-=2.5*(100*((null==e?void 0:e.fractionLost)||0));return 1+.035*r+7e-6*r*(r-60)*(100-r)}},{id:"rendered",value:()=>1},{id:"active",value:({hasLiveTrack:e,track:t,ssrc0:r})=>e&&t&&r?1:0},{id:"cpu-pressure",global:!0,enabled:({stats:e})=>{var t;return"cpu"===(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.source)},value:({stats:e})=>{var t;return{nominal:.25,fair:.5,serious:.75,critical:1}[(null===(t=null==e?void 0:e.pressure)||void 0===t?void 0:t.state)||""]||0}},{id:"turn-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>e.usingTurn)},{id:"turn-tls-usage",global:!0,enabled:({stats:e})=>!!Object.values((null==e?void 0:e.candidatePairs)||{}).length,value:({stats:e})=>Object.values((null==e?void 0:e.candidatePairs)||{}).some(e=>"tls"===e.turnProtocol)},{id:"concealment",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioConcealment},{id:"deceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioDeceleration},{id:"acceleration",enabled:({hasLiveTrack:e,ssrc0:t,kind:r})=>e&&!!t&&!!t.bitrate&&"in"===t.direction&&"audio"===r&&(t.audioLevel||0)>=.001,value:({ssrc0:e})=>null==e?void 0:e.audioAcceleration},{id:"qpf",enabled:({hasLiveTrack:e,track:t,ssrc0:r,kind:i})=>e&&"video"===i&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce((e,t)=>e+(t.qpf||0),0)}];let Xg,Yg,Zg;const ev=()=>{Xg={},Yg={},Zg={aggregated:{issues:Yg,metrics:Xg}}};function tv(e,t){Object.values(Xg).forEach(e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0}),Object.values(Yg).forEach(e=>{e.curTicks=0,e.curRegistered=0,e.active=!1}),t.find(e=>!e.isLocalClient)&&(t.forEach(r=>{const i=e[r.id];["video","audio","global"].forEach(e=>{var n,s;if(("global"!==e||r.isPresentation)&&!(null===(n=r[e])||void 0===n?void 0:n.enabled))return;if("global"===e&&!r.isLocalClient)return;let o=Zg[r.id];o||(o={issues:{},metrics:{}},Zg[r.id]=o);const a=null===(s=r[e])||void 0===s?void 0:s.track,c=!!a&&"ended"!==a.readyState,d=a&&i&&i.tracks[a.id],l=d?Object.values(d.ssrcs).sort((e,t)=>(e.height||Number.MAX_SAFE_INTEGER)-(t.height||Number.MAX_SAFE_INTEGER)):[],u=l[0],p={client:r,clients:t,kind:e,track:a,trackStats:d,stats:i,hasLiveTrack:c,ssrc0:u,ssrcs:l,issues:o.issues,metrics:o.metrics},h="global"===e?"global":`${r.isLocalClient?"loc":"rem"}-${r.isPresentation?"pres":"cam"}-${e}`;Qg.forEach(t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;if(!t.enabled||t.enabled(p)){const e=`${h}-${t.id}`;let r=o.metrics[e];const i=t.value(p);r||(r={ticks:0,sum:0,avg:0,min:i,max:i},o.metrics[e]=r),r.ticks++,r.sum+=i,r.min=Math.min(r.min,i),r.max=Math.max(r.max,i),r.avg=r.sum/r.ticks;let n=Xg[e];n||(n={ticks:0,sum:0,min:i,max:i,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},Xg[e]=n),n.ticks++,n.sum+=i,n.min=Math.min(n.min,i),n.max=Math.max(n.max,i),n.avg=n.sum/n.ticks,0===n.curTicks?(n.curMax=i,n.curMin=i,n.curSum=i):(n.curMax=Math.max(n.curMax,i),n.curMin=Math.min(n.curMin,i),n.curSum+=i),n.curTicks++}}),Wg.forEach(t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;const r=`${h}-${t.id}`,i=t.enabled(p);let n=o.issues[r],s=Yg[r];if(i){n||(n={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},o.issues[r]=n),n.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},Yg[r]=s),s.ticks++,s.curTicks++;t.check(p)?(n.registered++,n.current++,n.active||(n.active=!0,n.periods++),n.ticks===n.initial+1&&(n.initial++,s.initial++),n.current>n.longest&&(n.longest=n.current),s.active=!0,s.registered++,s.curRegistered++):(n.active=!1,n.current=0)}else n&&(n.active=!1,n.current=0)})})}),Object.values(Xg).forEach(e=>{e.curTicks&&(e.curAvg=e.curSum/e.curTicks,0===e.totTicks&&(e.totMin=e.curSum,e.totMax=e.curSum),e.totTicks++,e.totSum+=e.curSum,e.totMin=Math.min(e.totMin,e.curSum),e.totMax=Math.max(e.totMax,e.curSum),e.totAvg=e.totSum/e.totTicks)}),Object.values(Yg).forEach(e=>{e.curTicks}),Kg.forEach(r=>{var i;return null===(i=r.onUpdatedIssues)||void 0===i?void 0:i.call(r,Zg,e,t)}))}function rv(e){return Kg.push(e),Jg||(Jg=function(e,t=pf,r=uf){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=ff(r,t)),{stop(){var t;r.subscriptions=r.subscriptions.filter(t=>t!==e),r.subscriptions.length||(null===(t=r.currentMonitor)||void 0===t||t.stop(),r.currentMonitor=null)}}}({onUpdatedStats:tv}).stop),{stop(){Kg=Kg.filter(t=>t!==e),Kg.length||(null==Jg||Jg(),Jg=null,ev())}}}var iv;ev();const nv="safari"===(null!==(iv=oi.default)&&void 0!==iv?iv:oi).browserDetails.browser;function sv({disableAEC:e,disableAGC:t,hd:r,lax:i,lowDataMode:n,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=i||nv?720:{min:360,ideal:720}),a&&(!1===r?(u=360,p=270):p=360);const h={audio:Object.assign({},s.audioId&&{deviceId:s.audioId}),video:Object.assign(Object.assign({},s.videoId?{deviceId:s.videoId}:{facingMode:"user"}),{height:n?p:u,frameRate:n&&!a?15:24})};if(i)return(null===(d=h.audio)||void 0===d?void 0:d.deviceId)||(h.audio=!0),null===(l=h.video)||void 0===l||delete l.facingMode,h;if(o){const[e,t,r]=o.split(/[^\d]/g).map(e=>parseInt(e,10));e&&(h.video.width={exact:e}),t&&(h.video.height={exact:t}),r&&(h.video.frameRate={exact:r}),delete h.video.facingMode}else h.video.aspectRatio=c?16/9:4/3;return t&&(h.audio.autoGainControl=!1),e&&(h.audio.echoCancellation=!1),h}function ov({devices:e,videoId:t,audioId:r,options:i,type:n="ideal"}){const s=e.filter(e=>"audioinput"===e.kind),o=e.filter(e=>"videoinput"===e.kind),a=!r||!s.some(e=>e.deviceId===r),c=!t||!o.some(e=>e.deviceId===t),d=sv(Object.assign({preferredDeviceIds:{audioId:a?null:{[n]:r},videoId:c?null:{[n]:t}}},i));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const av=new Hh,cv=/mobi/i.test(navigator.userAgent);class dv extends Error{constructor(...e){super(...e),this.name="nodevices"}}function lv(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch(t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw av.error(`getUserMedia ${r}`),t}):Promise.reject(new dv("No provided devices"))}function uv(e,t,r,i){var n,s,o;let a={deviceId:null};return t?(a.label=t.label,t.getSettings&&(a=Object.assign(Object.assign({},a),t.getSettings())),a.deviceId?a:(t.getCapabilities&&(a.deviceId=t.getCapabilities().deviceId),a.deviceId?a:(t.label&&r&&(a.deviceId=null===(s=r.find(r=>t.label===r.label&&r.kind===e))||void 0===s?void 0:s.deviceId),a.deviceId||(a.deviceId=null===(o=t.getConstraints())||void 0===o?void 0:o.deviceId,a.broken=1),a))):(i&&r&&(a.deviceId=null===(n=r.find(t=>t.deviceId===i&&t.kind===e))||void 0===n?void 0:n.deviceId),a)}function pv(e,t){t&&"audio"!==t||e.getAudioTracks().forEach(e=>e.stop()),t&&"video"!==t||e.getVideoTracks().forEach(e=>e.stop())}function hv(e){return Wh(this,arguments,void 0,function*(e,{replaceStream:t,fallback:r=!0}={}){var i;let n,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=cv||"video"!==c,l=ov(e),u=(e,t)=>(e.details=Object.assign({constraints:l,constraint:e.constraint||(null==t?void 0:t.constraint),newConstraints:s,fallback:r,stopTracks:d},e!==n&&{error:String(n)}),e),p=t=>Wh(this,void 0,void 0,function*(){if(l.audio&&l.video){try{a=yield lv(ov(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){"NotFoundError"!==e.name&&u(e,t)}try{a||(a=yield lv(ov(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){u(e,t)}}});d&&t&&pv(t,c);try{a=yield lv(l)}catch(s){if(n=s,!r)throw u(s);if("OverconstrainedError"===s.name){o={deviceId:{videoId:null,audioId:null},width:{lax:!0},height:{lax:!0},"":{audioId:null,videoId:null,lax:!0}}[s.constraint||""]}else if("NotFoundError"===s.name)yield p(s);else if("NotAllowedError"===s.name||"NotReadableError"===s.name||"AbortError"===s.name)if(t&&!d&&(pv(t,c),o=e),"NotAllowedError"===s.name)yield p(s);else if("NotAllowedError"!==s.name){try{a=yield lv(ov(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){av.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(i=/(video|audio)/.exec(t))||void 0===i?void 0:i[0])||c||""];if(!a&&r)try{a=yield lv(ov(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){av.warn(`Re-tried ${r} with no constraints, but failed: ${""+e}`)}if(!a){const t=r?[r]:["videoId","audioId"];for(const r of t){try{a=yield lv(ov(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){av.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=ov(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield lv(s)}catch(e){throw u(e,n)}}if(!a)throw u(n);let h;return t&&(d||pv(t,c),h=function(e,t,r){const i=[];return r&&"audio"!==r||(i.push(...e.getAudioTracks()),t.getAudioTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),r&&"video"!==r||(i.push(...e.getVideoTracks()),t.getVideoTracks().forEach(t=>{t.replacement=!0,e.addTrack(t)})),i.forEach(t=>{t.replaced=!0,e.removeTrack(t)}),i}(t,a,c),a=t),{error:n&&u(n),stream:a,replacedTracks:h}})}function fv({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:i,currentSpeakerId:n}){const s=function(e,t){const[r,i]=[e,t].map(e=>e.filter(e=>e.kind&&e.deviceId).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.kind]:Object.assign(Object.assign({},e[t.kind]),{[t.deviceId]:t})}),{})),n={};return e.forEach(e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),i[e.kind]&&i[e.kind][e.deviceId]||(n[e.kind].removed[e.deviceId]=e))}),t.forEach(e=>{e.kind&&e.deviceId&&(n[e.kind]||(n[e.kind]={added:{},removed:{},changed:{}}),r[e.kind]&&r[e.kind][e.deviceId]?r[e.kind][e.deviceId].label&&r[e.kind][e.deviceId].label!==e.label&&(n[e.kind].changed[e.deviceId]=e):n[e.kind].added[e.deviceId]=e)}),n}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",i],["audiooutput",n]].forEach(([e,r])=>{const i=s[e];if(i){if(r){if(i.removed[r]&&(a[e]={deviceId:null},"audiooutput"===e)){const r=t.find(e=>"audiooutput"===e.kind);a[e]={deviceId:null==r?void 0:r.deviceId}}i.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(i.added).length>0){const[t]=Object.keys(i.added).slice(0,1),r=i.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(i.removed).length>0){const[t]=Object.keys(i.removed).slice(0,1);o[e]=i.removed[t]}}}),{addedDevices:c,changedDevices:a,removedDevices:o}}var mv;!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(mv||(mv={}));var gv={exports:{}};gv.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var vv=c(gv.exports);function bv(e,t){return function(){return e.apply(t,arguments)}}const{toString:yv}=Object.prototype,{getPrototypeOf:wv}=Object,{iterator:_v,toStringTag:Sv}=Symbol,Cv=(e=>t=>{const r=yv.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Rv=e=>(e=e.toLowerCase(),t=>Cv(t)===e),kv=e=>t=>typeof t===e,{isArray:Tv}=Array,Pv=kv("undefined");const Ov=Rv("ArrayBuffer");const Ev=kv("string"),Dv=kv("function"),xv=kv("number"),Iv=e=>null!==e&&"object"==typeof e,Mv=e=>{if("object"!==Cv(e))return!1;const t=wv(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Sv in e||_v in e)},jv=Rv("Date"),Lv=Rv("File"),Av=Rv("Blob"),Nv=Rv("FileList"),Bv=Rv("URLSearchParams"),[Fv,zv,Vv,Uv]=["ReadableStream","Request","Response","Headers"].map(Rv);function $v(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,n;if("object"!=typeof e&&(e=[e]),Tv(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{const n=r?Object.getOwnPropertyNames(e):Object.keys(e),s=n.length;let o;for(i=0;i<s;i++)o=n[i],t.call(null,e[o],o,e)}}function Gv(e,t){t=t.toLowerCase();const r=Object.keys(e);let i,n=r.length;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}const qv="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Hv=e=>!Pv(e)&&e!==qv;const Wv=(Kv="undefined"!=typeof Uint8Array&&wv(Uint8Array),e=>Kv&&e instanceof Kv);var Kv;const Jv=Rv("HTMLFormElement"),Qv=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Xv=Rv("RegExp"),Yv=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};$v(r,(r,n)=>{let s;!1!==(s=t(r,n,e))&&(i[n]=s||r)}),Object.defineProperties(e,i)};const Zv=Rv("AsyncFunction"),eb=(tb="function"==typeof setImmediate,rb=Dv(qv.postMessage),tb?setImmediate:rb?(ib=`axios@${Math.random()}`,nb=[],qv.addEventListener("message",({source:e,data:t})=>{e===qv&&t===ib&&nb.length&&nb.shift()()},!1),e=>{nb.push(e),qv.postMessage(ib,"*")}):e=>setTimeout(e));var tb,rb,ib,nb;const sb="undefined"!=typeof queueMicrotask?queueMicrotask.bind(qv):"undefined"!=typeof process&&process.nextTick||eb;var ob={isArray:Tv,isArrayBuffer:Ov,isBuffer:function(e){return null!==e&&!Pv(e)&&null!==e.constructor&&!Pv(e.constructor)&&Dv(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Dv(e.append)&&("formdata"===(t=Cv(e))||"object"===t&&Dv(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ov(e.buffer),t},isString:Ev,isNumber:xv,isBoolean:e=>!0===e||!1===e,isObject:Iv,isPlainObject:Mv,isReadableStream:Fv,isRequest:zv,isResponse:Vv,isHeaders:Uv,isUndefined:Pv,isDate:jv,isFile:Lv,isBlob:Av,isRegExp:Xv,isFunction:Dv,isStream:e=>Iv(e)&&Dv(e.pipe),isURLSearchParams:Bv,isTypedArray:Wv,isFileList:Nv,forEach:$v,merge:function e(){const{caseless:t}=Hv(this)&&this||{},r={},i=(i,n)=>{const s=t&&Gv(r,n)||n;Mv(r[s])&&Mv(i)?r[s]=e(r[s],i):Mv(i)?r[s]=e({},i):Tv(i)?r[s]=i.slice():r[s]=i};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&$v(arguments[e],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>($v(t,(t,i)=>{r&&Dv(t)?e[i]=bv(t,r):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let n,s,o;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),s=n.length;s-- >0;)o=n[s],i&&!i(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&wv(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Cv,kindOfTest:Rv,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(Tv(e))return e;let t=e.length;if(!xv(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[_v]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:Jv,hasOwnProperty:Qv,hasOwnProp:Qv,reduceDescriptors:Yv,freezeMethods:e=>{Yv(e,(t,r)=>{if(Dv(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Dv(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach(e=>{r[e]=!0})};return Tv(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Gv,global:qv,isContextDefined:Hv,isSpecCompliantForm:function(e){return!!(e&&Dv(e.append)&&"FormData"===e[Sv]&&e[_v])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Iv(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[i]=e;const n=Tv(e)?[]:{};return $v(e,(e,t)=>{const s=r(e,i+1);!Pv(s)&&(n[t]=s)}),t[i]=void 0,n}}return e};return r(e,0)},isAsyncFn:Zv,isThenable:e=>e&&(Iv(e)||Dv(e))&&Dv(e.then)&&Dv(e.catch),setImmediate:eb,asap:sb,isIterable:e=>null!=e&&Dv(e[_v])};function ab(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}ob.inherits(ab,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ob.toJSONObject(this.config),code:this.code,status:this.status}}});const cb=ab.prototype,db={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{db[e]={value:e}}),Object.defineProperties(ab,db),Object.defineProperty(cb,"isAxiosError",{value:!0}),ab.from=(e,t,r,i,n,s)=>{const o=Object.create(cb);return ob.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),ab.call(o,e.message,t,r,i,n),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function lb(e){return ob.isPlainObject(e)||ob.isArray(e)}function ub(e){return ob.endsWith(e,"[]")?e.slice(0,-2):e}function pb(e,t,r){return e?e.concat(t).map(function(e,t){return e=ub(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const hb=ob.toFlatObject(ob,{},null,function(e){return/^is[A-Z]/.test(e)});function fb(e,t,r){if(!ob.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=ob.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!ob.isUndefined(t[e])})).metaTokens,n=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ob.isSpecCompliantForm(t);if(!ob.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ob.isDate(e))return e.toISOString();if(ob.isBoolean(e))return e.toString();if(!a&&ob.isBlob(e))throw new ab("Blob is not supported. Use a Buffer instead.");return ob.isArrayBuffer(e)||ob.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(ob.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(ob.isArray(e)&&function(e){return ob.isArray(e)&&!e.some(lb)}(e)||(ob.isFileList(e)||ob.endsWith(r,"[]"))&&(a=ob.toArray(e)))return r=ub(r),a.forEach(function(e,i){!ob.isUndefined(e)&&null!==e&&t.append(!0===o?pb([r],i,s):null===o?r:r+"[]",c(e))}),!1;return!!lb(e)||(t.append(pb(n,r,s),c(e)),!1)}const l=[],u=Object.assign(hb,{defaultVisitor:d,convertValue:c,isVisitable:lb});if(!ob.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!ob.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+i.join("."));l.push(r),ob.forEach(r,function(r,s){!0===(!(ob.isUndefined(r)||null===r)&&n.call(t,r,ob.isString(s)?s.trim():s,i,u))&&e(r,i?i.concat(s):[s])}),l.pop()}}(e),t}function mb(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function gb(e,t){this._pairs=[],e&&fb(e,this,t)}const vb=gb.prototype;function bb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function yb(e,t,r){if(!t)return e;const i=r&&r.encode||bb;ob.isFunction(r)&&(r={serialize:r});const n=r&&r.serialize;let s;if(s=n?n(t,r):ob.isURLSearchParams(t)?t.toString():new gb(t,r).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}vb.append=function(e,t){this._pairs.push([e,t])},vb.toString=function(e){const t=e?function(t){return e.call(this,t,mb)}:mb;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class wb{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ob.forEach(this.handlers,function(t){null!==t&&e(t)})}}var _b={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Sb={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:gb,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const Cb="undefined"!=typeof window&&"undefined"!=typeof document,Rb="object"==typeof navigator&&navigator||void 0,kb=Cb&&(!Rb||["ReactNative","NativeScript","NS"].indexOf(Rb.product)<0),Tb="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Pb=Cb&&window.location.href||"http://localhost";var Ob={...Object.freeze({__proto__:null,hasBrowserEnv:Cb,hasStandardBrowserEnv:kb,hasStandardBrowserWebWorkerEnv:Tb,navigator:Rb,origin:Pb}),...Sb};function Eb(e){function t(e,r,i,n){let s=e[n++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=n>=e.length;if(s=!s&&ob.isArray(i)?i.length:s,a)return ob.hasOwnProp(i,s)?i[s]=[i[s],r]:i[s]=r,!o;i[s]&&ob.isObject(i[s])||(i[s]=[]);return t(e,r,i[s],n)&&ob.isArray(i[s])&&(i[s]=function(e){const t={},r=Object.keys(e);let i;const n=r.length;let s;for(i=0;i<n;i++)s=r[i],t[s]=e[s];return t}(i[s])),!o}if(ob.isFormData(e)&&ob.isFunction(e.entries)){const r={};return ob.forEachEntry(e,(e,i)=>{t(function(e){return ob.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Db={transitional:_b,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,n=ob.isObject(e);n&&ob.isHTMLForm(e)&&(e=new FormData(e));if(ob.isFormData(e))return i?JSON.stringify(Eb(e)):e;if(ob.isArrayBuffer(e)||ob.isBuffer(e)||ob.isStream(e)||ob.isFile(e)||ob.isBlob(e)||ob.isReadableStream(e))return e;if(ob.isArrayBufferView(e))return e.buffer;if(ob.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return fb(e,new Ob.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,i){return Ob.isNode&&ob.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=ob.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return fb(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||i?(t.setContentType("application/json",!1),function(e,t,r){if(ob.isString(e))try{return(t||JSON.parse)(e),ob.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Db.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(ob.isResponse(e)||ob.isReadableStream(e))return e;if(e&&ob.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw ab.from(e,ab.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ob.classes.FormData,Blob:Ob.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ob.forEach(["delete","get","head","post","put","patch"],e=>{Db.headers[e]={}});const xb=ob.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Ib=Symbol("internals");function Mb(e){return e&&String(e).trim().toLowerCase()}function jb(e){return!1===e||null==e?e:ob.isArray(e)?e.map(jb):String(e)}function Lb(e,t,r,i,n){return ob.isFunction(i)?i.call(this,t,r):(n&&(t=r),ob.isString(t)?ob.isString(i)?-1!==t.indexOf(i):ob.isRegExp(i)?i.test(t):void 0:void 0)}let Ab=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function n(e,t,r){const n=Mb(t);if(!n)throw new Error("header name must be a non-empty string");const s=ob.findKey(i,n);(!s||void 0===i[s]||!0===r||void 0===r&&!1!==i[s])&&(i[s||t]=jb(e))}const s=(e,t)=>ob.forEach(e,(e,r)=>n(e,r,t));if(ob.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(ob.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let r,i,n;return e&&e.split("\n").forEach(function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),i=e.substring(n+1).trim(),!r||t[r]&&xb[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t})(e),t);else if(ob.isObject(e)&&ob.isIterable(e)){let r,i,n={};for(const t of e){if(!ob.isArray(t))throw TypeError("Object iterator must return a key-value pair");n[i=t[0]]=(r=n[i])?ob.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}s(n,t)}else null!=e&&n(t,e,r);return this}get(e,t){if(e=Mb(e)){const r=ob.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(ob.isFunction(t))return t.call(this,e,r);if(ob.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Mb(e)){const r=ob.findKey(this,e);return!(!r||void 0===this[r]||t&&!Lb(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function n(e){if(e=Mb(e)){const n=ob.findKey(r,e);!n||t&&!Lb(0,r[n],n,t)||(delete r[n],i=!0)}}return ob.isArray(e)?e.forEach(n):n(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const n=t[r];e&&!Lb(0,this[n],n,e,!0)||(delete this[n],i=!0)}return i}normalize(e){const t=this,r={};return ob.forEach(this,(i,n)=>{const s=ob.findKey(r,n);if(s)return t[s]=jb(i),void delete t[n];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(n):String(n).trim();o!==n&&delete t[n],t[o]=jb(i),r[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ob.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&ob.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[Ib]=this[Ib]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Mb(e);t[i]||(!function(e,t){const r=ob.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,n){return this[i].call(this,t,e,r,n)},configurable:!0})})}(r,e),t[i]=!0)}return ob.isArray(e)?e.forEach(i):i(e),this}};function Nb(e,t){const r=this||Db,i=t||r,n=Ab.from(i.headers);let s=i.data;return ob.forEach(e,function(e){s=e.call(r,s,n.normalize(),t?t.status:void 0)}),n.normalize(),s}function Bb(e){return!(!e||!e.__CANCEL__)}function Fb(e,t,r){ab.call(this,null==e?"canceled":e,ab.ERR_CANCELED,t,r),this.name="CanceledError"}function zb(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new ab("Request failed with status code "+r.status,[ab.ERR_BAD_REQUEST,ab.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Ab.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ob.reduceDescriptors(Ab.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),ob.freezeMethods(Ab),ob.inherits(Fb,ab,{__CANCEL__:!0});const Vb=(e,t,r=3)=>{let i=0;const n=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let n,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];n||(n=c),r[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=r[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-n<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,i,n=0,s=1e3/t;const o=(t,s=Date.now())=>{n=s,r=null,i&&(clearTimeout(i),i=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-n;a>=s?o(e,t):(r=e,i||(i=setTimeout(()=>{i=null,o(r)},s-a)))},()=>r&&o(r)]}(r=>{const s=r.loaded,o=r.lengthComputable?r.total:void 0,a=s-i,c=n(a);i=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})},r)},Ub=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},$b=e=>(...t)=>ob.asap(()=>e(...t));var Gb=Ob.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Ob.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Ob.origin),Ob.navigator&&/(msie|trident)/i.test(Ob.navigator.userAgent)):()=>!0,qb=Ob.hasStandardBrowserEnv?{write(e,t,r,i,n,s){const o=[e+"="+encodeURIComponent(t)];ob.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ob.isString(i)&&o.push("path="+i),ob.isString(n)&&o.push("domain="+n),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Hb(e,t,r){let i=!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(i||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Wb=e=>e instanceof Ab?{...e}:e;function Kb(e,t){t=t||{};const r={};function i(e,t,r,i){return ob.isPlainObject(e)&&ob.isPlainObject(t)?ob.merge.call({caseless:i},e,t):ob.isPlainObject(t)?ob.merge({},t):ob.isArray(t)?t.slice():t}function n(e,t,r,n){return ob.isUndefined(t)?ob.isUndefined(e)?void 0:i(void 0,e,0,n):i(e,t,0,n)}function s(e,t){if(!ob.isUndefined(t))return i(void 0,t)}function o(e,t){return ob.isUndefined(t)?ob.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,n,s){return s in t?i(r,n):s in e?i(void 0,r):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>n(Wb(e),Wb(t),0,!0)};return ob.forEach(Object.keys(Object.assign({},e,t)),function(i){const s=c[i]||n,o=s(e[i],t[i],i);ob.isUndefined(o)&&s!==a||(r[i]=o)}),r}var Jb=e=>{const t=Kb({},e);let r,{data:i,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Ab.from(a),t.url=yb(Hb(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ob.isFormData(i))if(Ob.hasStandardBrowserEnv||Ob.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Ob.hasStandardBrowserEnv&&(n&&ob.isFunction(n)&&(n=n(t)),n||!1!==n&&Gb(t.url))){const e=s&&o&&qb.read(o);e&&a.set(s,e)}return t};var Qb="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=Jb(e);let n=i.data;const s=Ab.from(i.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function f(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let m=new XMLHttpRequest;function g(){if(!m)return;const i=Ab.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());zb(function(e){t(e),f()},function(e){r(e),f()},{data:u&&"text"!==u&&"json"!==u?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new ab("Request aborted",ab.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ab("Network Error",ab.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const n=i.transitional||_b;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new ab(t,n.clarifyTimeoutError?ab.ETIMEDOUT:ab.ECONNABORTED,e,m)),m=null},void 0===n&&s.setContentType(null),"setRequestHeader"in m&&ob.forEach(s.toJSON(),function(e,t){m.setRequestHeader(t,e)}),ob.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),u&&"json"!==u&&(m.responseType=i.responseType),h&&([c,l]=Vb(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,d]=Vb(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(o=t=>{m&&(r(!t||t.type?new Fb(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(o),i.signal&&(i.signal.aborted?o():i.signal.addEventListener("abort",o)));const v=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);v&&-1===Ob.protocols.indexOf(v)?r(new ab("Unsupported protocol "+v+":",ab.ERR_BAD_REQUEST,e)):m.send(n||null)})};const Xb=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const n=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;i.abort(t instanceof ab?t:new Fb(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,n(new ab(`timeout ${t} of ms exceeded`,ab.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(n):e.removeEventListener("abort",n)}),e=null)};e.forEach(e=>e.addEventListener("abort",n));const{signal:a}=i;return a.unsubscribe=()=>ob.asap(o),a}},Yb=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,n=0;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},Zb=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},ey=(e,t,r,i)=>{const n=async function*(e,t){for await(const r of Zb(e))yield*Yb(r,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await n.next();if(t)return a(),void e.close();let s=i.byteLength;if(r){let e=o+=s;r(e)}e.enqueue(new Uint8Array(i))}catch(e){throw a(e),e}},cancel:e=>(a(e),n.return())},{highWaterMark:2})},ty="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,ry=ty&&"function"==typeof ReadableStream,iy=ty&&("function"==typeof TextEncoder?(ny=new TextEncoder,e=>ny.encode(e)):async e=>new Uint8Array(await new Response(e).arrayBuffer()));var ny;const sy=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},oy=ry&&sy(()=>{let e=!1;const t=new Request(Ob.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),ay=ry&&sy(()=>ob.isReadableStream(new Response("").body)),cy={stream:ay&&(e=>e.body)};var dy;ty&&(dy=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!cy[e]&&(cy[e]=ob.isFunction(dy[e])?t=>t[e]():(t,r)=>{throw new ab(`Response type '${e}' is not supported`,ab.ERR_NOT_SUPPORT,r)})}));const ly=async(e,t)=>{const r=ob.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(ob.isBlob(e))return e.size;if(ob.isSpecCompliantForm(e)){const t=new Request(Ob.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ob.isArrayBufferView(e)||ob.isArrayBuffer(e)?e.byteLength:(ob.isURLSearchParams(e)&&(e+=""),ob.isString(e)?(await iy(e)).byteLength:void 0)})(t):r};var uy=ty&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=Jb(e);d=d?(d+"").toLowerCase():"text";let h,f=Xb([n,s&&s.toAbortSignal()],o);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&oy&&"get"!==r&&"head"!==r&&0!==(g=await ly(l,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(ob.isFormData(i)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=Ub(g,Vb($b(c)));i=ey(r.body,65536,e,t)}}ob.isString(u)||(u=u?"include":"omit");const n="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:n?u:void 0});let s=await fetch(h,p);const o=ay&&("stream"===d||"response"===d);if(ay&&(a||o&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=ob.toFiniteNumber(s.headers.get("content-length")),[r,i]=a&&Ub(t,Vb($b(a),!0))||[];s=new Response(ey(s.body,65536,r,()=>{i&&i(),m&&m()}),e)}d=d||"text";let v=await cy[ob.findKey(cy,d)||"text"](s,e);return!o&&m&&m(),await new Promise((t,r)=>{zb(t,r,{data:v,headers:Ab.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(t){if(m&&m(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new ab("Network Error",ab.ERR_NETWORK,e,h),{cause:t.cause||t});throw ab.from(t,t&&t.code,e,h)}});const py={http:null,xhr:Qb,fetch:uy};ob.forEach(py,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const hy=e=>`- ${e}`,fy=e=>ob.isFunction(e)||null===e||!1===e;var my=e=>{e=ob.isArray(e)?e:[e];const{length:t}=e;let r,i;const n={};for(let s=0;s<t;s++){let t;if(r=e[s],i=r,!fy(r)&&(i=py[(t=String(r)).toLowerCase()],void 0===i))throw new ab(`Unknown adapter '${t}'`);if(i)break;n[t||"#"+s]=i}if(!i){const e=Object.entries(n).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new ab("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(hy).join("\n"):" "+hy(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function gy(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Fb(null,e)}function vy(e){gy(e),e.headers=Ab.from(e.headers),e.data=Nb.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return my(e.adapter||Db.adapter)(e).then(function(t){return gy(e),t.data=Nb.call(e,e.transformResponse,t),t.headers=Ab.from(t.headers),t},function(t){return Bb(t)||(gy(e),t&&t.response&&(t.response.data=Nb.call(e,e.transformResponse,t.response),t.response.headers=Ab.from(t.response.headers))),Promise.reject(t)})}const by="1.10.0",yy={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{yy[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const wy={};yy.transitional=function(e,t,r){function i(e,t){return"[Axios v"+by+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,s)=>{if(!1===e)throw new ab(i(n," has been removed"+(t?" in "+t:"")),ab.ERR_DEPRECATED);return t&&!wy[n]&&(wy[n]=!0,console.warn(i(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,s)}},yy.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var _y={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ab("options must be an object",ab.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let n=i.length;for(;n-- >0;){const s=i[n],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new ab("option "+s+" must be "+r,ab.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new ab("Unknown option "+s,ab.ERR_BAD_OPTION)}},validators:yy};const Sy=_y.validators;let Cy=class{constructor(e){this.defaults=e||{},this.interceptors={request:new wb,response:new wb}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Kb(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:n}=t;void 0!==r&&_y.assertOptions(r,{silentJSONParsing:Sy.transitional(Sy.boolean),forcedJSONParsing:Sy.transitional(Sy.boolean),clarifyTimeoutError:Sy.transitional(Sy.boolean)},!1),null!=i&&(ob.isFunction(i)?t.paramsSerializer={serialize:i}:_y.assertOptions(i,{encode:Sy.function,serialize:Sy.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),_y.assertOptions(t,{baseUrl:Sy.spelling("baseURL"),withXsrfToken:Sy.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=n&&ob.merge(n.common,n[t.method]);n&&ob.forEach(["delete","get","head","post","put","patch","common"],e=>{delete n[e]}),t.headers=Ab.concat(s,n);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0;if(!a){const e=[vy.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(e){t.call(this,e);break}}try{d=vy.call(this,p)}catch(e){return Promise.reject(e)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return yb(Hb((e=Kb(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};ob.forEach(["delete","get","head","options"],function(e){Cy.prototype[e]=function(t,r){return this.request(Kb(r||{},{method:e,url:t,data:(r||{}).data}))}}),ob.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,n){return this.request(Kb(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Cy.prototype[e]=t(),Cy.prototype[e+"Form"]=t(!0)});const Ry={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Ry).forEach(([e,t])=>{Ry[t]=e});const ky=function e(t){const r=new Cy(t),i=bv(Cy.prototype.request,r);return ob.extend(i,Cy.prototype,r,{allOwnKeys:!0}),ob.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(Kb(t,r))},i}(Db);ky.Axios=Cy,ky.CanceledError=Fb,ky.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{r.subscribe(e),t=e}).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e(function(e,i,n){r.reason||(r.reason=new Fb(e,i,n),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},ky.isCancel=Bb,ky.VERSION=by,ky.toFormData=fb,ky.AxiosError=ab,ky.Cancel=ky.CanceledError,ky.all=function(e){return Promise.all(e)},ky.spread=function(e){return function(t){return e.apply(null,t)}},ky.isAxiosError=function(e){return ob.isObject(e)&&!0===e.isAxiosError},ky.mergeConfig=Kb,ky.AxiosHeaders=Ab,ky.formToJSON=e=>Eb(ob.isHTMLForm(e)?new FormData(e):e),ky.getAdapter=my,ky.HttpStatusCode=Ry,ky.default=ky;const{Axios:Ty,AxiosError:Py,CanceledError:Oy,isCancel:Ey,CancelToken:Dy,VERSION:xy,all:Iy,Cancel:My,isAxiosError:jy,spread:Ly,toFormData:Ay,AxiosHeaders:Ny,HttpStatusCode:By,formToJSON:Fy,getAdapter:zy,mergeConfig:Vy}=ky;function Uy(e,t){return vt(e,t)}function $y(e,t){return r=>(i,n,s)=>e(n())?t(r)(i,n,s):(console.warn("Not authorized to perform this action"),!1)}function Gy(e){return t=>(r,i,n)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,i,n)}function qy(e,t){return Uy(e,(e,r)=>{const{getState:i}=r;return"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),Promise.reject("Action cannot be performed outside of a connected room")):t(e,r)})}function Hy(e,t){return r=>(i,n,s)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):$y(e,t)(r)(i,n,s)}const Wy=((e={})=>{const t=new Map,{extra:r,onError:i=tr}=e;Mt(i,"onError");const n=e=>(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&Qt(e)}))(Jt(t,e)??Kt(e));Ut(n,{withTypes:()=>n});const s=e=>{const r=Jt(t,e);return r&&(r.unsubscribe(),e.cancelActive&&Qt(r)),!!r};Ut(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=Ht(n,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,Ut({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Vt(c.signal),pause:zt(c.signal),extra:r,signal:c.signal,fork:qt(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,r)=>{e!==c&&(Nt(e,Dt),r.delete(e))})},cancel:()=>{Nt(c,Dt),e.pending.delete(c)},throwIfCancelled:()=>{Bt(c.signal)}})))}catch(e){e instanceof It||Xt(i,e,{raisedBy:"effect"})}finally{await Promise.all(l),Nt(c,xt),e.pending.delete(c)}},a=(e=>()=>{e.forEach(Qt),e.clear()})(t);return{middleware:e=>r=>c=>{if(!N(c))return r(c);if(Yt.match(c))return n(c.payload);if(Zt.match(c))return void a();if(er.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===$t)throw new Error(`${Gt}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),n=Array.from(t.values());for(const t of n){let n=!1;try{n=t.predicate(c,r,d)}catch(e){n=!1,Xt(i,e,{raisedBy:"predicate"})}n&&o(t,c,e,l)}}}finally{d=$t}return u},startListening:n,stopListening:s,clearListeners:a}})(),Ky=Wy.startListening,Jy=(e,t)=>Ky({predicate:(t,r,i)=>{const n=e.map(e=>e(i)),s=e.map(e=>e(r));return n.some((e,t)=>e!==s[t])},effect:(r,{dispatch:i,getState:n,extra:s})=>{const o=e.map(e=>e(n()));t({dispatch:i,getState:n,extra:s},...o)}}),Qy=Ct({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,ignoreBreakoutGroups:!1,roomName:null,roomUrl:null,displayName:null,userAgent:"core:0.35.0",externalId:null},reducers:{doAppStart:(e,t)=>{const r=new URL(t.payload.roomUrl);return Object.assign(Object.assign(Object.assign({},e),t.payload),{roomName:r.pathname,initialConfig:Object.assign({},t.payload),isActive:!0})},doAppStop:e=>Object.assign(Object.assign({},e),{isActive:!1})}}),{doAppStop:Xy,doAppStart:Yy}=Qy.actions,Zy=e=>e.app.isActive,ew=e=>e.app.isDialIn,tw=e=>e.app.roomName,rw=e=>e.app.displayName,iw=e=>e.app.userAgent,nw=e=>e.app.externalId;function sw(e){return qe(`signalConnection/event/${e}`)}const ow={audioEnabled:sw("audioEnabled"),audioEnableRequested:sw("audioEnableRequested"),breakoutGroupJoined:sw("breakoutGroupJoined"),breakoutMoveToGroup:sw("breakoutMoveToGroup"),breakoutMoveToMain:sw("breakoutMoveToMain"),breakoutSessionUpdated:sw("breakoutSessionUpdated"),chatMessage:sw("chatMessage"),clientLeft:sw("clientLeft"),clientKicked:sw("clientKicked"),clientMetadataReceived:sw("clientMetadataReceived"),clientUnableToJoin:sw("clientUnableToJoin"),cloudRecordingStarted:sw("cloudRecordingStarted"),cloudRecordingStopped:sw("cloudRecordingStopped"),disconnect:sw("disconnect"),knockerLeft:sw("knockerLeft"),knockHandled:sw("knockHandled"),newClient:sw("newClient"),roomJoined:sw("roomJoined"),roomKnocked:sw("roomKnocked"),roomLeft:sw("roomLeft"),roomLocked:sw("roomLocked"),roomSessionEnded:sw("roomSessionEnded"),screenshareStarted:sw("screenshareStarted"),screenshareStopped:sw("screenshareStopped"),spotlightAdded:sw("spotlightAdded"),spotlightRemoved:sw("spotlightRemoved"),streamingStopped:sw("streamingStopped"),videoEnabled:sw("videoEnabled"),videoEnableRequested:sw("videoEnableRequested"),liveTranscriptionStarted:sw("liveTranscriptionStarted"),liveTranscriptionStopped:sw("liveTranscriptionStopped")},aw={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},cw=Ct({name:"authorization",initialState:{roomKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(Yy,(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey})),e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:i}=t.payload||{},n=null==r?void 0:r.clients.find(e=>e.id===i);return n?Object.assign(Object.assign({},e),{roleName:(null==n?void 0:n.role.roleName)||"none"}):e})}}),{setRoomKey:dw}=cw.actions,lw=e=>e.authorization.roomKey,uw=e=>e.authorization.roleName,pw=Be(uw,e=>aw.canLockRoom.includes(e)),hw=Be(uw,e=>aw.canRequestAudioEnable.includes(e)),fw=Be(uw,e=>aw.canRequestVideoEnable.includes(e)),mw=Be(uw,e=>aw.canKickClient.includes(e)),gw=Be(uw,e=>aw.canEndMeeting.includes(e)),vw=Be(uw,e=>aw.canAskToSpeak.includes(e)),bw=Be(uw,e=>aw.canSpotlight.includes(e));function yw(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}function ww(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){e.done?n(e.value):function(e){return e instanceof r?e:new r(function(t){t(e)})}(e.value).then(o,a)}c((i=i.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const _w=Ct({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(Sw.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(Sw.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload})),e.addCase(Sw.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!0}))}}),Sw=Uy("deviceCredentials/doGetDeviceCredentials",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{extra:t}){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})),Cw=e=>e.deviceCredentials,Rw=e=>{var t,r;return null===(r=null===(t=e.deviceCredentials.data)||void 0===t?void 0:t.credentials)||void 0===r?void 0:r.uuid};Jy([Be(Zy,Cw,(e,t)=>!(!e||t.isFetching||t.data))],({dispatch:e},t)=>{t&&e(Sw())});const kw=Ct({name:"signalConnection",initialState:{deviceIdentified:!1,isIdentifyingDevice:!1,status:"ready",socket:null},reducers:{socketConnecting:e=>Object.assign(Object.assign({},e),{status:"connecting"}),socketConnected:(e,t)=>Object.assign(Object.assign({},e),{socket:t.payload,status:"connected"}),socketDisconnected:e=>Object.assign(Object.assign({},e),{socket:null,deviceIdentified:!1,status:"disconnected"}),socketReconnecting:e=>Object.assign(Object.assign({},e),{status:"reconnecting"}),deviceIdentifying:e=>Object.assign(Object.assign({},e),{isIdentifyingDevice:!0}),deviceIdentified:e=>Object.assign(Object.assign({},e),{deviceIdentified:!0,isIdentifyingDevice:!1})},extraReducers:e=>{e.addCase(ow.disconnect,e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"}))}}),{deviceIdentifying:Tw,deviceIdentified:Pw,socketConnected:Ow,socketConnecting:Ew,socketDisconnected:Dw,socketReconnecting:xw}=kw.actions,Iw=()=>(e,t)=>{if(Bw(t()))return;e(Ew());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new dg(e,{autoConnect:!1})}();r.on("connect",()=>e(Ow(r))),r.on("device_identified",()=>e(Pw())),r.getManager().on("reconnect",()=>e(xw())),function(e,t){e.on("room_joined",e=>t(ow.roomJoined(e))),e.on("new_client",e=>t(ow.newClient(e))),e.on("client_left",e=>t(ow.clientLeft(e))),e.on("client_kicked",e=>t(ow.clientKicked(e))),e.on("client_unable_to_join",e=>t(ow.clientUnableToJoin(e))),e.on("audio_enabled",e=>t(ow.audioEnabled(e))),e.on("video_enabled",e=>t(ow.videoEnabled(e))),e.on("audio_enable_requested",e=>t(ow.audioEnableRequested(e))),e.on("client_metadata_received",e=>t(ow.clientMetadataReceived(e))),e.on("chat_message",e=>t(ow.chatMessage(e))),e.on("disconnect",()=>t(ow.disconnect())),e.on("room_knocked",e=>t(ow.roomKnocked(e))),e.on("room_left",()=>t(ow.roomLeft())),e.on("room_locked",e=>t(ow.roomLocked(e))),e.on("room_session_ended",e=>t(ow.roomSessionEnded(e))),e.on("knocker_left",e=>t(ow.knockerLeft(e))),e.on("knock_handled",e=>t(ow.knockHandled(e))),e.on("screenshare_started",e=>t(ow.screenshareStarted(e))),e.on("screenshare_stopped",e=>t(ow.screenshareStopped(e))),e.on("cloud_recording_started",e=>t(ow.cloudRecordingStarted(e))),e.on("cloud_recording_stopped",()=>t(ow.cloudRecordingStopped())),e.on("streaming_stopped",()=>t(ow.streamingStopped())),e.on("spotlight_added",e=>t(ow.spotlightAdded(e))),e.on("spotlight_removed",e=>t(ow.spotlightRemoved(e))),e.on("live_transcription_started",e=>t(ow.liveTranscriptionStarted(e))),e.on("live_transcription_stopped",e=>t(ow.liveTranscriptionStopped(e))),e.on("video_enable_requested",e=>t(ow.videoEnableRequested(e))),e.on("breakout_group_joined",e=>t(ow.breakoutGroupJoined(e))),e.on("breakout_session_updated",e=>t(ow.breakoutSessionUpdated(e))),e.on("breakout_move_to_group",()=>t(ow.breakoutMoveToGroup())),e.on("breakout_move_to_main",()=>t(ow.breakoutMoveToMain()))}(r,e),r.connect()},Mw=({deviceCredentials:e})=>(t,r)=>{const i=r(),n=Bw(i),s=Aw(i);n&&(s||(n.emit("identify_device",{deviceCredentials:e}),t(Tw())))},jw=()=>(e,t)=>{const r=t();if("connected"===Nw(r)){const t=Lw(r).socket;null==t||t.disconnect(),e(Dw())}},Lw=e=>e.signalConnection,Aw=e=>e.signalConnection.deviceIdentified,Nw=e=>e.signalConnection.status,Bw=e=>e.signalConnection.socket;Jy([Be(Zy,Nw,(e,t)=>!(!e||!["ready","reconnecting"].includes(t)))],({dispatch:e},t)=>{t&&e(Iw())});const Fw=Be(Cw,Nw,Aw,e=>e.signalConnection.isIdentifyingDevice,(e,t,r,i)=>!(!e.data||"connected"!==t||r||i));function zw(e,{delay:t=500,edges:r}={}){let i,n=0;return(...s)=>{n+=1,r&&1===n&&e(...s),clearTimeout(i),i=setTimeout(()=>{(!r||n>1)&&e(...s),i=void 0,n=0},t)}}Jy([Fw,Cw],({dispatch:e},t,r)=>{t&&r.data&&e(Mw({deviceCredentials:r.data}))}),Ky({actionCreator:ow.roomLeft,effect:(e,{dispatch:t})=>{t(jw())}}),Ky({actionCreator:ow.clientKicked,effect:(e,{dispatch:t})=>{t(jw())}});const Vw=Ct({name:"localMedia",initialState:{busyDeviceIds:[],cameraEnabled:!1,currentSpeakerDeviceId:"default",devices:[],isSettingCameraDevice:!1,isSettingMicrophoneDevice:!1,isSettingSpeakerDevice:!1,isTogglingCamera:!1,lowDataMode:!1,microphoneEnabled:!1,status:"inactive",stream:void 0,isSwitchingStream:!1},reducers:{deviceBusy:(e,t)=>e.busyDeviceIds.includes(t.payload.deviceId)?e:Object.assign(Object.assign({},e),{busyDeviceIds:[...e.busyDeviceIds,t.payload.deviceId]}),toggleCameraEnabled(e,t){var r;return Object.assign(Object.assign({},e),{cameraEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.cameraEnabled})},setCurrentCameraDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentCameraDeviceId:t.payload.deviceId}),toggleMicrophoneEnabled(e,t){var r;return Object.assign(Object.assign({},e),{microphoneEnabled:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.microphoneEnabled})},setCurrentMicrophoneDeviceId:(e,t)=>Object.assign(Object.assign({},e),{currentMicrophoneDeviceId:t.payload.deviceId}),setCurrentSpeakerDeviceId(e,t){var r;return Object.assign(Object.assign({},e),{currentSpeakerDeviceId:null!==(r=t.payload.deviceId)&&void 0!==r?r:"default"})},toggleLowDataModeEnabled(e,t){var r;return Object.assign(Object.assign({},e),{lowDataMode:null!==(r=t.payload.enabled)&&void 0!==r?r:!e.lowDataMode})},setDevices:(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}),setLocalMediaStream:(e,t)=>Object.assign(Object.assign({},e),{stream:t.payload.stream}),setLocalMediaOptions:(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.options}),localMediaStopped:e=>Object.assign(Object.assign({},e),{status:"stopped",stream:void 0}),localStreamMetadataUpdated(e,t){const{audio:r,video:i}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:i.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter(e=>e!==r.deviceId&&e!==i.deviceId)})}},extraReducers:e=>{e.addCase(Yy,(e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions})),e.addCase(r_.pending,(e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:i,isSettingMicrophoneDevice:r})}),e.addCase(r_.fulfilled,(e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})}),e.addCase(r_.rejected,(e,t)=>{const{audio:r,video:i}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!i&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:i?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})}),e.addCase(Zw.pending,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0})),e.addCase(Zw.fulfilled,e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1})),e.addCase(i_.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices})),e.addCase(s_.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(s_.fulfilled,(e,{payload:{stream:t,onDeviceChange:r}})=>{let i,n,s=!1,o=!1;const a=t.getAudioTracks()[0],c=t.getVideoTracks()[0];return a&&(n=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,i=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:i,currentMicrophoneDeviceId:n,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})}),e.addCase(s_.rejected,(e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error})),e.addCase(n_.pending,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0})),e.addCase(n_.fulfilled,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})),e.addCase(n_.rejected,e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))}}),{deviceBusy:Uw,setCurrentCameraDeviceId:$w,setCurrentMicrophoneDeviceId:Gw,setCurrentSpeakerDeviceId:qw,toggleCameraEnabled:Hw,toggleMicrophoneEnabled:Ww,toggleLowDataModeEnabled:Kw,setLocalMediaOptions:Jw,setLocalMediaStream:Qw,localMediaStopped:Xw,localStreamMetadataUpdated:Yw}=Vw.actions,Zw=Uy("localMedia/doToggleCamera",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){const i=t(),n=b_(i);if(!n)return;let s=n.getVideoTracks()[0];const o=u_(i);try{if(o)if(s)s.enabled=!0;else{const e=w_(i),t=c_(i);yield hv(Object.assign(Object.assign({},e),{audioId:!1,videoId:t,type:"exact"}),{replaceStream:n}),s=n.getVideoTracks()[0]}else{if(!s)return;s.enabled=!1,s.stop(),n.removeTrack(s)}n.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:s,enable:o}}))}catch(e){return r(e)}})),e_=Uy("localMedia/doToggleMicrophone",(e,{getState:t})=>{var r;const i=t(),n=b_(i);if(!n)return;const s=p_(i),o=null===(r=n.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)}),t_=()=>(e,t)=>{const r=t();if(!b_(r))return;const i=c_(r),n=d_(r);e(n_({audioId:n,videoId:i}))},r_=Uy("localMedia/reactSetDevice",(e,t)=>ww(void 0,[e,t],void 0,function*({audio:e,video:t},{getState:r,rejectWithValue:i}){try{const i=r(),n=b_(i);if(!n)throw new Error("No stream");const s=!!e&&d_(i),o=!!t&&c_(i),a=w_(i),{replacedTracks:c}=yield hv(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:n}),d=p_(i);n.getAudioTracks().forEach(e=>e.enabled=d);const l=u_(i);return n.getVideoTracks().forEach(e=>e.enabled=l),{replacedTracks:c}}catch(e){return i(e)}})),i_=Uy("localMedia/doUpdateDeviceList",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:i}){var n,s,o,a;const c=t();let d=[],l=[];const u=b_(c);try{d=yield navigator.mediaDevices.enumerateDevices(),l=f_(c);if(!(u&&!y_(c)&&d&&l&&l.find(e=>e.deviceId)))return{devices:d};const{changedDevices:e,addedDevices:t}=fv({oldDevices:l,newDevices:d});let i=null===(n=e.audioinput)||void 0===n?void 0:n.deviceId,p=null===(s=e.videoinput)||void 0===s?void 0:s.deviceId;return void 0===i&&(i=null===(o=t.audioinput)||void 0===o?void 0:o.deviceId),void 0===p&&(p=null===(a=t.videoinput)||void 0===a?void 0:a.deviceId),void 0===i&&void 0===p||r(n_({audioId:i,videoId:p})),{devices:d}}catch(e){return i(e)}})),n_=Uy("localMedia/doSwitchLocalStream",(e,t)=>ww(void 0,[e,t],void 0,function*({audioId:e,videoId:t},{dispatch:r,getState:i,rejectWithValue:n}){const s=i(),o=b_(s),a=w_(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:i}=yield hv(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),n=e||t;return c&&n&&r(Uw({deviceId:n})),{replacedTracks:i}}catch(i){console.error(i);const s=e||t;return c&&s&&r(Uw({deviceId:s})),n(i)}})),s_=Uy("localMedia/doStartLocalMedia",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,dispatch:r,rejectWithValue:i}){const n=zw(()=>{r(i_())},{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",n),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:n});if(!e.audio&&!e.video)return{stream:new MediaStream,onDeviceChange:n};r(Jw({options:e}));try{yield r(i_());const i=t(),s=w_(i),{stream:o}=yield hv(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:n}}catch(e){return i(e)}})),o_=()=>(e,t)=>{const r=b_(t()),i=g_(t()).onDeviceChange;null==r||r.getTracks().forEach(e=>{e.stop()}),navigator.mediaDevices&&i&&navigator.mediaDevices.removeEventListener("devicechange",i),e(Xw())},a_=e=>e.localMedia.busyDeviceIds,c_=e=>e.localMedia.currentCameraDeviceId,d_=e=>e.localMedia.currentMicrophoneDeviceId,l_=e=>e.localMedia.currentSpeakerDeviceId,u_=e=>e.localMedia.cameraEnabled,p_=e=>e.localMedia.microphoneEnabled,h_=e=>e.localMedia.lowDataMode,f_=e=>e.localMedia.devices,m_=e=>e.localMedia.options;Be(m_,e=>!!e);const g_=e=>e.localMedia,v_=e=>e.localMedia.status,b_=e=>e.localMedia.stream,y_=e=>e.localMedia.isSwitchingStream,w_=Be(f_,c_,d_,h_,(e,t,r,i)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:i,simulcast:!0,widescreen:!0}})),__=Be(v_,e=>"starting"===e),S_=Be(f_,a_,(e,t)=>e.filter(e=>"videoinput"===e.kind).filter(e=>!t.includes(e.deviceId))),C_=Be(f_,a_,(e,t)=>e.filter(e=>"audioinput"===e.kind).filter(e=>!t.includes(e.deviceId))),R_=Be(f_,e=>e.filter(e=>"audiooutput"===e.kind));Jy([Be(Zy,v_,m_,(e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r})],({dispatch:e},t)=>{t&&e(s_(t))});Jy([Be(Zy,v_,m_,(e,t,r)=>!e&&"inactive"!==t&&!!r)],({dispatch:e},t)=>{t&&e(o_())}),Ky({predicate:(e,t,r)=>{const i=p_(r),n=p_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(e_())}}),Ky({predicate:(e,t,r)=>{const i=h_(r),n=h_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(t_())}}),Ky({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const i=u_(r),n=u_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(Zw())}}),Ky({predicate:(e,t,r)=>{const i=c_(r),n=c_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(r_({audio:!1,video:!0}))}}),Ky({predicate:(e,t,r)=>{const i=d_(r),n=d_(t);return"started"===v_(r)&&i!==n},effect:(e,{dispatch:t})=>{t(r_({audio:!0,video:!1}))}}),Ky({matcher:lt(s_.fulfilled,i_.fulfilled,n_.fulfilled,n_.rejected),effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=b_(i),s=f_(i);if(!n)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:i,lastAudioId:n,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||i,e=o(e),{video:uv("videoinput",t,r,s),audio:uv("audioinput",e,r,n)}}({audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0],devices:s});t(Yw(o))}}),Ky({actionCreator:ow.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Ww({enabled:!1}))}}),Ky({actionCreator:ow.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(Hw({enabled:!1}))}}),Ky({actionCreator:ow.breakoutSessionUpdated,effect:({payload:e},{dispatch:t})=>{var r;!1===(null===(r=e.initiatedBy)||void 0===r?void 0:r.active)&&t(Ww({enabled:!1}))}});const k_=["recorder","streamer"],T_=e=>e.localParticipant,P_=e=>e.localParticipant.id,O_=e=>e.localParticipant.displayName,E_=e=>e.localParticipant.stickyReaction,D_=Be(T_,b_,(e,t)=>{const r={id:e.id,clientId:e.id,breakoutGroup:e.breakoutGroup,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return k_.includes(e.roleName)?null:r});function x_({assignments:e,groups:t,startedAt:r,initiatedBy:i,breakoutStartedAt:n,breakoutEndedAt:s,breakoutNotification:o,breakoutTimerDuration:a,autoMoveToGroup:c,moveToGroupGracePeriod:d,autoMoveToMain:l,moveToMainGracePeriod:u,enforceAssignment:p,breakoutTimerSetting:h}={}){return{assignments:e||null,groups:t||null,startedAt:r?new Date(r):null,initiatedBy:i,breakoutStartedAt:n||null,breakoutEndedAt:s||null,breakoutNotification:o||null,breakoutTimerDuration:a||1800,autoMoveToGroup:c||!1,moveToGroupGracePeriod:d||10,autoMoveToMain:l||!1,moveToMainGracePeriod:u||30,enforceAssignment:p||!1,breakoutTimerSetting:h||!1}}const I_=Ct({name:"breakout",initialState:Object.assign(Object.assign({},x_()),{groupId:null}),reducers:{},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{breakout:r}=t.payload||{};return r?Object.assign(Object.assign({},e),x_(r)):e}),e.addCase(ow.breakoutSessionUpdated,(e,t)=>Object.assign(Object.assign({},e),x_(t.payload))),e.addCase(ow.breakoutGroupJoined,(e,t)=>{var r;return(null===(r=t.meta)||void 0===r?void 0:r.localParticipantId)!==t.payload.clientId?e:Object.assign(Object.assign({},e),{groupId:t.payload.group})})}}),M_=e=>(t,r)=>{const i=r(),{socket:n}=Lw(i);null==n||n.emit("join_breakout_group",{group:e.group})},j_=e=>e.breakout,L_=e=>!!e.breakout.startedAt,A_=e=>e.breakout.assignments,N_=Be(j_,e=>e.localParticipant.breakoutGroup,(e,t)=>e.groupId||t||""),B_=Be(j_,N_,(e,t)=>{var r;const i=null===(r=e.groups)||void 0===r?void 0:r[t];return i?{id:t,name:i}:null});Ky({actionCreator:ow.breakoutMoveToGroup,effect:(e,{dispatch:t,getState:r})=>{const i=r(),n=T_(i).breakoutGroupAssigned;n&&t(M_({group:n}))}}),Ky({actionCreator:ow.breakoutMoveToMain,effect:(e,{dispatch:t})=>{t(M_({group:""}))}}),Ky({actionCreator:ow.breakoutSessionUpdated,effect:({payload:e},{dispatch:t,getState:r})=>{var i;const n=r(),s=j_(n).autoMoveToMain;!1===(null===(i=e.initiatedBy)||void 0===i?void 0:i.active)&&(s||t(M_({group:""})))}});const F_=Ct({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(ow.chatMessage,(e,t)=>{const r={senderId:t.payload.senderId,timestamp:t.payload.timestamp,text:t.payload.text};return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,r]})})}}),z_=Gy(e=>(t,r)=>{const i=r(),n=Lw(i).socket,s=N_(i);null==n||n.emit("chat_message",Object.assign(Object.assign({text:e.text},s&&{breakoutGroup:s}),e.isBroadcast&&{broadcast:!0}))}),V_=Ct({name:"cloudRecording",initialState:{isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{status:"requested"})},extraReducers:e=>{e.addCase(ow.cloudRecordingStopped,e=>Object.assign(Object.assign({},e),{isRecording:!1,status:void 0})),e.addCase(ow.cloudRecordingStarted,(e,t)=>{const{payload:r}=t;return r.error?Object.assign(Object.assign({},e),{isRecording:!1,status:"error",error:r.error}):e}),e.addCase(ow.newClient,(e,{payload:t})=>{var r;const{client:i}=t;return"recorder"===(null===(r=i.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:i.startedCloudRecordingAt?new Date(i.startedCloudRecordingAt).getTime():(new Date).getTime()}):e})}}),{recordingRequestStarted:U_}=V_.actions,$_=Gy(()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=q_(r);n&&["recording","requested"].includes(n)||(null==i||i.emit("start_recording",{recording:"cloud"}),e(U_()))}),G_=Gy(()=>(e,t)=>{const r=t(),i=Lw(r).socket;null==i||i.emit("stop_recording")}),q_=e=>e.cloudRecording.status,H_=e=>e.roomConnection.status;function W_(e){return qe(`rtcConnection/event/${e}`)}const K_={rtcManagerCreated:W_("rtcManagerCreated"),rtcManagerDestroyed:W_("rtcManagerDestroyed"),streamAdded:W_("streamAdded"),clientConnectionStatusChanged:W_("clientConnectionStatusChanged")};function J_(e,t=!1){const{streams:r,role:i,breakoutGroup:n}=e,s=yw(e,["streams","role","breakoutGroup"]);return Object.assign(Object.assign({},s),{stream:null,streams:r.map(e=>({id:e,state:t?"new_accept":"to_accept"})),isLocalParticipant:!1,roleName:(null==i?void 0:i.roleName)||"none",presentationStream:null,breakoutGroup:n||null,newJoiner:t})}function Q_(e,t){const r=e.remoteParticipants.findIndex(e=>e.id===t);return{index:r,participant:e.remoteParticipants[r]}}function X_(e,t,r){const{participant:i,index:n}=Q_(e,t);return i?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,n),Object.assign(Object.assign({},i),r),...e.remoteParticipants.slice(n+1)]}):(console.error(`Did not find client for update ${t}`),e)}function Y_(e,t,r,i){const{participant:n}=Q_(e,t);if(!n)return console.error(`No client ${t} found to update stream ${r} ${i}`),e;const s=n.streams.findIndex(e=>e.id===r),o=[...n.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:i}),X_(e,t,{streams:o})}function Z_(e,t,r){const{participant:i}=Q_(e,t);return!i||i.streams.find(e=>e.id===r)?(console.warn(`No participant ${t} or stream ${r} already exists`),e):X_(e,t,{streams:[...i.streams,{id:r,state:"to_accept"}]})}const eS=Ct({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:i,state:n}of t.payload)r=Y_(r,e,i,n);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:i}=t.payload;return X_(e,r,{stream:i})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Z_(e,r,i)}},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r,selfId:i}=t.payload||{};return(null==r?void 0:r.clients)?Object.assign(Object.assign({},e),{remoteParticipants:r.clients.filter(e=>e.id!==i).map(e=>J_(e))}):e}),e.addCase(K_.streamAdded,(e,t)=>function(e,t){const{clientId:r,stream:i,streamType:n}=t;let{streamId:s}=t;const{participant:o}=Q_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=i.id);const c=a.find(e=>e.id===r);if(!c)return e;const d=c.streams.find(e=>e.id===s);return c.stream&&(c.stream.id===s||c.stream.inboundId===s)||!c.stream&&"webcam"===n||!c.stream&&!n&&!d?X_(e,r,{stream:i}):X_(e,r,{presentationStream:i})}(e,t.payload)),e.addCase(ow.newClient,(e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=Q_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,J_(r,!0))}),e.addCase(ow.clientLeft,(e,t)=>{const{clientId:r}=t.payload;return function(e,t){return Object.assign(Object.assign({},e),{remoteParticipants:e.remoteParticipants.filter(e=>e.id!==t)})}(e,r)}),e.addCase(ow.audioEnabled,(e,t)=>{const{clientId:r,isAudioEnabled:i}=t.payload;return X_(e,r,{isAudioEnabled:i})}),e.addCase(ow.videoEnabled,(e,t)=>{const{clientId:r,isVideoEnabled:i}=t.payload;return X_(e,r,{isVideoEnabled:i})}),e.addCase(ow.clientMetadataReceived,(e,t)=>{const{error:r,payload:i}=t.payload;if(r||!i)return console.warn(r||"Client metadata error received"),e;const{clientId:n,displayName:s,stickyReaction:o}=i;return X_(e,n,{displayName:s,stickyReaction:o})}),e.addCase(ow.breakoutGroupJoined,(e,t)=>{const{clientId:r,group:i}=t.payload;return X_(e,r,{breakoutGroup:i||null})}),e.addCase(ow.screenshareStarted,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Z_(e,r,i)}),e.addCase(ow.screenshareStopped,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return function(e,t,r){var i,n;const{participant:s}=Q_(e,t);if(!s)return console.error(`No participant ${t} found to remove stream ${r}`),e;const o=s.stream&&s.stream.id,a=(null===(i=s.presentationStream)||void 0===i?void 0:i.inboundId)||(null===(n=s.presentationStream)||void 0===n?void 0:n.id),c=s.streams.findIndex(e=>e.id===r);return X_(e,t,Object.assign(Object.assign({streams:s.streams.filter((e,t)=>t!==c)},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,i)})}}),{participantStreamAdded:tS,participantStreamIdAdded:rS,streamStatusUpdated:iS}=eS.actions,nS=Hy(e=>hw(e),e=>(t,r)=>{const i=r(),n=vw(i);if(e.enable&&!n)return void console.warn("Not authorized to perform this action");const s=Lw(i).socket;null==s||s.emit("request_audio_enable",e)}),sS=Hy(e=>fw(e),e=>(t,r)=>{const i=r(),n=Lw(i).socket;null==n||n.emit("request_video_enable",e)}),oS=e=>e.remoteParticipants.remoteParticipants,aS=Be(oS,e=>e.filter(e=>!k_.includes(e.roleName)));Be(oS,e=>e.length+1);const cS=Be(aS,T_,(e,t)=>k_.includes(t.roleName)?e.length:e.length+1),dS=Ct({name:"localScreenshare",initialState:{status:"inactive",stream:null,error:null},reducers:{stopScreenshare:(e,t)=>Object.assign(Object.assign({},e),{status:"inactive",stream:null})},extraReducers:e=>{e.addCase(uS.pending,e=>Object.assign(Object.assign({},e),{status:"starting"})),e.addCase(uS.fulfilled,(e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t})),e.addCase(uS.rejected,(e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null}))}}),{stopScreenshare:lS}=dS.actions,uS=qy("localScreenshare/doStartScreenshare",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r,rejectWithValue:i}){var n;try{const e=r(),i=hS(e);if(i)return{stream:i};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t(pS())};return"oninactive"in s?s.addEventListener("inactive",o):null===(n=s.getVideoTracks()[0])||void 0===n||n.addEventListener("ended",o),{stream:s}}catch(e){return i(e)}})),pS=Gy(()=>(e,t)=>{const r=t(),i=hS(r);i&&(i.getTracks().forEach(e=>e.stop()),e(lS({stream:i})))}),hS=e=>e.localScreenshare.stream;function fS(e){return"streamer"===e.roleName}function mS(e){return"recorder"===e.roleName}Ky({actionCreator:Xw,effect:(e,{getState:t})=>{const r=t(),i=hS(r);i&&(null==i||i.getTracks().forEach(e=>{e.stop()}))}});const gS=Ct({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{isLocked:Boolean(t.payload.isLocked)}):e;const{room:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r.isLocked)})}),e.addCase(ow.roomLocked,(e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})})}}),vS=$y(e=>pw(e),e=>(t,r)=>{const i=r(),{socket:n}=Lw(i);null==n||n.emit("set_lock",{locked:e.locked})}),bS=$y(e=>mw(e),e=>(t,r)=>{const i=r(),{socket:n}=Lw(i);null==n||n.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})}),yS=$y(e=>gw(e),e=>(t,r)=>{const i=r(),n=oS(i).map(e=>e.id);if(n.length){const{socket:e}=Lw(i);null==e||e.emit("kick_client",{clientIds:n,reasonId:"end-meeting"})}e.stayBehind||t(Xy())}),wS=Be(hS,T_,aS,(e,t,r)=>{const i=[];e&&i.push({id:e.id||"local-screenshare",participantId:"local",hasAudioTrack:e.getTracks().some(e=>"audio"===e.kind),breakoutGroup:t.breakoutGroup,stream:e,isLocal:!0});for(const e of r)e.presentationStream&&i.push({id:e.presentationStream.id||`pres-${e.id}`,participantId:e.id,hasAudioTrack:e.presentationStream.getTracks().some(e=>"audio"===e.kind),breakoutGroup:e.breakoutGroup,stream:e.presentationStream,isLocal:!1});return i}),_S=Be(hS,T_,aS,N_,A_,(e,t,r,i,n)=>{const s=[];if(e){const r=!!e.getAudioTracks().length;s.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e,breakoutGroup:i||""})}for(const e of r){if(fS(e)||mS(e))continue;const{presentationStream:t}=e,r=yw(e,["presentationStream"]),i=e.displayName||"Guest",o=t&&t.active,a="pres-"+e.id,c=e.stream&&e.stream.active,d=e.isVideoEnabled;s.push(Object.assign(Object.assign(Object.assign({},r),{breakoutGroupAssigned:(null==n?void 0:n[e.deviceId])||"",clientId:e.id,displayName:i,hasActivePresentation:!!o}),e.isVideoEnabled?{isVideoEnabled:d}:{})),o&&s.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${i})`,id:a,isPresentation:!0,isVideoEnabled:!0}),c&&{isRecording:null}))}return s}),SS=Be(D_,_S,(e,t)=>[...e?[e]:[],...t]),CS=Be(SS,L_,N_,(e,t,r)=>t&&r?e.filter(e=>e.isLocalClient||e.breakoutGroup===(r||"")||e.breakoutGroupAssigned&&e.breakoutGroupAssigned===r):e),RS=Be(SS,L_,e=>e.breakout.groups,(e,t,r)=>{if(!t||!r)return[];return[{clients:e.filter(e=>!e.breakoutGroup||""===e.breakoutGroup),group:{id:"",name:""}},...Object.entries(r).map(([t,r])=>({clients:e.filter(e=>!e.isPresentation&&e.breakoutGroup===t),group:{id:t,name:r}}))]});function kS({isPresentation:e,stream:t}){var r,i;return e?null!==(i=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==i?i:null==t?void 0:t.id:"0"}function TS(e,t){return e.find(e=>e.clientId===t.clientId&&e.streamId===t.streamId)?e:e.concat(t)}const PS=Ct({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:TS(e.sorted,{clientId:r,streamId:i})})},removeSpotlight(e,t){const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===i))})}},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{var r;if("error"in t.payload)return e;const{room:i}=t.payload||{};return i?Object.assign(Object.assign({},e),{sorted:null!==(r=i.spotlights)&&void 0!==r?r:e.sorted}):e}),e.addCase(ow.spotlightAdded,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:TS(e.sorted,{clientId:r,streamId:i})})}),e.addCase(ow.spotlightRemoved,(e,t)=>{const{clientId:r,streamId:i}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>!(e.clientId===r&&e.streamId===i))})}),e.addMatcher(lt(ow.clientKicked,ow.clientLeft),(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter(e=>e.clientId!==r)})})}}),{addSpotlight:OS,removeSpotlight:ES}=PS.actions,DS=$y(e=>bw(e),({id:e})=>(t,r)=>{const i=r(),n=SS(i).find(t=>t.clientId===e);if(!n)return;const{socket:s}=Lw(i),o=kS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)}),xS=$y(e=>bw(e),({id:e})=>(t,r)=>{const i=r(),n=SS(i).find(t=>t.clientId===e);if(!n)return;const{socket:s}=Lw(i),o=kS(n),a={clientId:n.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)}),IS=e=>e.spotlights.sorted;Be(T_,IS,(e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:i}){return!!e.find(e=>{const n=kS({isPresentation:t,stream:i});return e.clientId===r&&e.streamId===n})}({clientId:e.id,stream:e.stream,spotlights:t}));const MS=Be(SS,IS,(e,t)=>function(e,t){return e.reduce((e,r)=>{const i=t.find(e=>r.clientId===e.clientId&&r.streamId===kS(e));return i&&!e.includes(i)&&e.push(i),e},[])}(t,e));Ky({actionCreator:uS.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=T_(n);s&&r(OS({clientId:s.id,streamId:i.id}))}}),Ky({actionCreator:lS,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:i}=e,n=t(),s=T_(n);s&&r(ES({clientId:s.id,streamId:i.id}))}});const jS=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(JS(r)):"stream_added"===t?e(K_.streamAdded(r)):"rtc_manager_destroyed"===t?e(VS()):"client_connection_status_changed"===t&&e(K_.clientConnectionStatusChanged(r))}}),LS={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},AS=Ct({name:"rtcConnection",initialState:LS,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:i,height:n}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:i,height:n}})})},rtcDisconnected:()=>Object.assign({},LS),rtcDispatcherCreated:(e,t)=>Object.assign(Object.assign({},e),{dispatcherCreated:!0,rtcManagerDispatcher:t.payload}),rtcManagerCreated:(e,t)=>Object.assign(Object.assign({},e),{rtcManager:t.payload,status:"ready"}),rtcManagerDestroyed:e=>Object.assign(Object.assign({},e),{rtcManager:null}),rtcManagerInitialized:e=>Object.assign(Object.assign({},e),{rtcManagerInitialized:!0}),rtcClientConnectionStatusChanged:{reducer:e=>e,prepare:e=>({payload:{},meta:{localParticipantId:e.localParticipantId}})}},extraReducers:e=>{e.addCase(xw,e=>Object.assign(Object.assign({},e),{status:"reconnecting"})),e.addCase(ow.roomJoined,(e,t)=>"error"in t.payload?e:Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status}))}}),{resolutionReported:NS,rtcDispatcherCreated:BS,rtcDisconnected:FS,rtcManagerCreated:zS,rtcManagerDestroyed:VS,rtcManagerInitialized:US,isAcceptingStreams:$S,rtcClientConnectionStatusChanged:GS}=AS.actions,qS=()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=XS(r).rtcManagerDispatcher,s=u_(r),o=p_(r),a=(e=>e.app.isNodeSdk)(r);if(n||!i)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable:e=>function({client:e,breakoutCurrentId:t}){return!(!e||(t||!e.breakoutGroup)&&(e.isAudioEnabled||e.isVideoEnabled))}({client:aS(t()).find(t=>t.id===e),breakoutCurrentId:N_(t())||""})},d=new Vg({emitter:jS(e),serverSocket:i,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,p2pVp9On:!0,sfuVp9On:!1,h264On:!1,simulcastScreenshareOn:!1}});e(BS(d))},HS=()=>(e,t)=>{const{rtcManager:r}=XS(t());r&&r.disconnectAll(),e(FS())},WS=e=>(t,r)=>{var i;t($S(!0));const n=r(),s=XS(n).rtcManager,o=oS(n);if(!s)throw new Error("No rtc manager");const a=L_(n),c=null===(i=s.shouldAcceptStreamsFromBothSides)||void 0===i?void 0:i.call(s),d=[];for(const{clientId:t,streamId:r,state:i}of e){if(o.find(e=>e.id===t)){if("to_accept"===i||"new_accept"===i&&c||"old_accept"===i&&!c)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:a});else if("new_accept"===i||"old_accept"===i);else if("to_unaccept"===i)null==s||s.disconnect("0"===r?t:r,a);else if("done_accept"!==i)continue;d.push({clientId:t,streamId:r,state:i.replace(/to_|new_|old_/,"done_")})}}t(iS(d)),t($S(!1))},KS=({streamId:e,width:t,height:r})=>(i,n)=>{const{reportedStreamResolutions:s,rtcManager:o}=XS(n()),a=b_(n());if(!o||(null==a?void 0:a.id)===e)return;const c=s[e];c&&c.width===t&&c.height===r||o.updateStreamResolution(e,null,{width:t||1,height:r||1}),i(NS({streamId:e,width:t,height:r}))},JS=e=>t=>{const{rtcManager:r}=e;t(zS(r))},QS=()=>(e,t)=>{const r=b_(t()),i=XS(t()).rtcManager,n=u_(t()),s=p_(t());r&&i&&i.addNewStream("0",r,!s,!n),e(US())},XS=e=>e.rtcConnection,YS=e=>e.rtcConnection.rtcManagerInitialized,ZS=e=>e.rtcConnection.rtcManager,eC=e=>e.rtcConnection.status;Ky({actionCreator:r_.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:i}=XS(t()),n=b_(t());null==r||r.forEach(e=>{((e,t)=>{const r=null==n?void 0:n.getTracks().find(t=>t.kind===e);r&&(null==i||i.replaceTrack(t,r))})(e.kind,e)})}}),Ky({actionCreator:uS.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=XS(t());null==i||i.addNewStream(r.id,r,!1,!0)}}),Ky({actionCreator:Xy,effect:(e,{getState:t})=>{const r=ZS(t());null==r||r.rtcStatsDisconnect()}}),Ky({actionCreator:lS,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:i}=XS(t());null==i||i.removeStream(r.id,r,null)}}),Ky({actionCreator:n_.fulfilled,effect:({payload:e},{getState:t})=>{var r;const i=b_(t()),{rtcManager:n}=XS(t());if(i&&n){const t=(e,t)=>{const r=i.getTracks().find(t=>t.kind===e);return r&&n.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach(e=>{t(e.kind,e)})}}}),Ky({actionCreator:K_.clientConnectionStatusChanged,effect:(e,{dispatch:t,getState:r})=>{const i=T_(r());t(GS({localParticipantId:i.id}))}});Jy([Be(eC,Zy,e=>e.rtcConnection.dispatcherCreated,e=>e.rtcConnection.isCreatingDispatcher,Bw,(e,t,r,i,n)=>!(!t||"inactive"!==e||r||i||!n))],({dispatch:e},t)=>{t&&e(qS())});const tC=Be(ZS,YS,v_,(e,t,r)=>!("started"!==r||!e||t));Jy([tC],({dispatch:e},t)=>{t&&e(QS())});Jy([Be(eC,Zy,(e,t)=>!t&&!["inactive","disconnected"].includes(e))],({dispatch:e},t)=>{t&&e(HS())});const rC=Be(eC,oS,N_,IS,e=>e.app.ignoreBreakoutGroups,(e,t,r,i,n)=>{if("ready"!==e)return[];const s=[];for(const e of t){const{streams:t,id:o,newJoiner:a}=e,c=i.find(t=>t.clientId===e.id&&"0"===t.streamId);for(let i=0;i<t.length;i++){let d=t[i].id,l=t[i].state;if((null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===i?(d=t[1].id,l=t[1].state):1===i&&(d=t[0].id,l=t[0].state)),!e.breakoutGroup&&!r||e.breakoutGroup===r||""===e.breakoutGroup&&c||n){if("done_accept"===l)continue;s.push({clientId:o,streamId:d,state:(a&&"0"===d?"new":"to")+"_accept"})}else{if("done_unaccept"===l)continue;s.push({clientId:o,streamId:d,state:"to_unaccept"})}}}return s});Jy([rC,e=>e.rtcConnection.isAcceptingStreams],({dispatch:e},t,r)=>{0<t.length&&!r&&e(WS(t))});const iC={running:!1},nC=Ct({name:"connectionMonitor",initialState:iC,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},iC)}}),{connectionMonitorStarted:sC,connectionMonitorStopped:oC}=nC.actions,aC=()=>(e,t)=>{var r;r=()=>{const e=t(),r=SS(e).map(e=>{var t,r;return{id:e.id,clientId:e.clientId,isLocalClient:e.isLocalClient,audio:{enabled:e.isAudioEnabled,track:null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks()[0]},video:{enabled:e.isVideoEnabled,track:null===(r=e.stream)||void 0===r?void 0:r.getVideoTracks()[0]},isPresentation:e.isPresentation}});return r},uf.getClients=r;const i=rv({onUpdatedIssues:e=>{var r;const i=t(),n=ZS(i);if(!n)return;let s=0,o=0,a=0,c=0;Object.entries(e.aggregated.metrics).forEach(([e,t])=>{/loc.*packetloss/.test(e)&&(s=Math.max(s,t.curMax)),/rem.*packetloss/.test(e)&&(o=Math.max(o,t.curMax)),/loc.*bitrate/.test(e)&&(a+=t.curSum),/rem.*bitrate/.test(e)&&(c+=t.curSum)}),n.sendStatsCustomEvent("insightsStats",{ls:Math.round(1e3*s)/1e3,lr:Math.round(1e3*o)/1e3,bs:Math.round(a),br:Math.round(c),cpu:null===(r=e.aggregated.metrics["global-cpu-pressure"])||void 0===r?void 0:r.curSum,_time:Date.now()})}});e(sC({stopIssueSubscription:i.stop}))},cC=()=>(e,t)=>{const r=t(),i=lC(r);i&&i(),e(oC())},dC=e=>e.connectionMonitor.running,lC=e=>e.connectionMonitor.stopCallbackFunction,uC=Be(H_,dC,(e,t)=>!t&&"connected"===e),pC=Be(H_,dC,(e,t)=>!(!t||!["kicked","left"].includes(e)));Jy([uC],({dispatch:e},t)=>{t&&e(aC())}),Jy([pC],({dispatch:e},t)=>{t&&e(cC())});const hC=Ct({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,breakoutGroupAssigned:"",isAudioEnabled:!0,isVideoEnabled:!0,isLocalParticipant:!0,stream:void 0,isScreenSharing:!1,roleName:"none",clientClaim:void 0,stickyReaction:void 0,isDialIn:!1},reducers:{setDisplayName:(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}),setBreakoutGroupAssigned:(e,t)=>Object.assign(Object.assign({},e),{breakoutGroupAssigned:t.payload.breakoutGroupAssigned})},extraReducers:e=>{e.addCase(Yy,(e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName})),e.addCase(vC.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload})),e.addCase(bC.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload})),e.addCase(yC.fulfilled,(e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload})),e.addCase(ow.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error?Object.assign(Object.assign({},e),{id:t.payload.selfId}):e;const{room:i,selfId:n,clientClaim:s}=t.payload||{},o=i.clients.find(e=>e.id===n);return Object.assign(Object.assign({},e),{id:n,roleName:(null===(r=null==o?void 0:o.role)||void 0===r?void 0:r.roleName)||"none",clientClaim:s,breakoutGroup:(null==o?void 0:o.breakoutGroup)||null})}),e.addCase(ow.breakoutGroupJoined,(e,t)=>{var r,i;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(i=t.payload)||void 0===i?void 0:i.group})})}}),{setDisplayName:fC,setBreakoutGroupAssigned:mC}=hC.actions,gC=Gy(e=>(t,r)=>{const i=r(),n=Lw(i).socket;null==n||n.emit("send_client_metadata",{type:"UserData",payload:{displayName:e.displayName}}),t(fC({displayName:e.displayName}))}),vC=qy("localParticipant/doEnableAudio",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{dispatch:t,getState:r}){const i=r(),n=Lw(i).socket;return null==n||n.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(yC({enabled:!1})),e.enabled})),bC=qy("localParticipant/doEnableVideo",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t}){const r=t(),i=Lw(r).socket;return null==i||i.emit("enable_video",{enabled:e.enabled}),e.enabled})),yC=qy("localParticipant/doSetLocalStickyReaction",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{getState:t,rejectWithValue:r}){var i;const n=t(),s=E_(n),o=Boolean(s),a=null!==(i=e.enabled)&&void 0!==i?i:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})),wC=Gy(()=>(e,t)=>{const r=t(),i=Lw(r).socket,n={displayName:O_(r),stickyReaction:E_(r)};null==i||i.emit("send_client_metadata",{type:"UserData",payload:n})});Ky({actionCreator:Hw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isVideoEnabled:n}=T_(r());"connected"===H_(r())&&t(bC({enabled:i||!n}))}}),Ky({actionCreator:Ww,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:i}=e,{isAudioEnabled:n}=T_(r());"connected"===H_(r())&&t(vC({enabled:i||!n}))}}),Jy([O_,E_,H_],({dispatch:e},t,r,i)=>{"connected"===i&&e(wC())}),Jy([A_,Rw,T_],({dispatch:e},t,r,i)=>{const n=(null==t?void 0:t[r||""])||"";i.breakoutGroupAssigned!==n&&e(mC({breakoutGroupAssigned:n}))});function _C(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const SC=Ct({name:"notifications",initialState:{emitter:new bp,events:[]},reducers:{addNotification:(e,t)=>Object.assign(Object.assign({},e),{events:[...e.events,Object.assign({},t.payload)]}),doClearNotifications:e=>Object.assign(Object.assign({},e),{events:[]})}}),{doClearNotifications:CC}=SC.actions,RC=e=>(t,r)=>{t(SC.actions.addNotification(e));const i=r(),n=kC(i);n.emit(e.type,e),n.emit("*",e)},kC=e=>e.notifications.emitter;Ky({actionCreator:ow.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const i=r(),n=aS(i).find(({id:t})=>t===e.senderId);n?t(RC(_C({type:"chatMessageReceived",message:`${n.displayName} says: ${e.text}`,props:{client:n,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),Ky({actionCreator:ow.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=aS(s).find(({id:e})=>e===n);o?t(RC(_C({type:i?"requestAudioEnable":"requestAudioDisable",message:i?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local audio change")}}),Ky({actionCreator:ow.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:i,requestedByClientId:n}=e,s=r(),o=aS(s).find(({id:e})=>e===n);o?t(RC(_C({type:i?"requestVideoEnable":"requestVideoDisable",message:i?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:i}}))):console.warn("Could not find remote client that requested a local video change")}}),Ky({actionCreator:ow.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:i})=>{var n;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=i();if(!vw(d))return;const l=aS(d).find(({id:e})=>e===a);if(!l)return void console.warn("Could not find remote client that provided updated metadata");const u=r(),p=aS(u).find(({id:e})=>e===a);(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(n=null==p?void 0:p.stickyReaction)||void 0===n?void 0:n.timestamp)&&t(RC(_C({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),Jy([Nw],({dispatch:e,getState:t},r)=>{const i=t(),n=H_(i);["left","kicked"].includes(n)||("disconnected"===r?e(RC(_C({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(RC(_C({type:"signalOk",message:"Network connection available",props:{}}))))}),Ky({actionCreator:ow.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(RC(_C({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const TC=Ct({name:"organization",initialState:{data:null,isFetching:!1,error:null},reducers:{},extraReducers:e=>{e.addCase(PC.pending,e=>Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(PC.fulfilled,(e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0})),e.addCase(PC.rejected,e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0}))}}),PC=Uy("organization/doOrganizationFetch",(e,t)=>ww(void 0,[e,t],void 0,function*(e,{extra:t,getState:r}){try{const e=r().app.roomUrl,i=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!i)throw new Error("Invalid room url");return i}catch(e){console.error(e)}})),OC=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};Jy([Be(Zy,e=>e.organization,Cw,(e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching))],({dispatch:e},t)=>{t&&e(PC())});const EC=Ct({name:"roomConnection",initialState:{session:null,status:"ready",error:null},reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{var r;if("error"in t.payload)return"room_locked"===t.payload.error&&t.payload.isLocked?Object.assign(Object.assign({},e),{status:"room_locked"}):Object.assign(Object.assign({},e),{status:"disconnected",error:t.payload.error});const{room:i}=t.payload;return Object.assign(Object.assign({},e),{status:"connected",session:null!==(r=i.session)&&void 0!==r?r:null})}),e.addCase(ow.disconnect,e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"})),e.addCase(ow.newClient,(e,t)=>{var r,i;return Object.assign(Object.assign({},e),{session:null!==(i=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==i?i:null})}),e.addCase(ow.roomSessionEnded,(e,t)=>{var r;return(null===(r=e.session)||void 0===r?void 0:r.id)!==t.payload.roomSessionId?e:Object.assign(Object.assign({},e),{session:null})}),e.addCase(ow.clientKicked,e=>Object.assign(Object.assign({},e),{status:"kicked"})),e.addCase(ow.roomLeft,e=>Object.assign(Object.assign({},e),{status:"left"})),e.addCase(xw,e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))}}),{connectionStatusChanged:DC}=EC.actions,xC=()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=tw(r),s=lw(r),o=rw(r),a=ew(r),c=iw(r),d=nw(r),l=OC(r);"room_locked"===H_(r)?(null==i||i.emit("knock_room",{avatarUrl:null,config:{isAudioEnabled:!0,isVideoEnabled:!0},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:a,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:c,externalId:d}),e(DC("knocking"))):console.warn("Room is not locked, knock aborted")},IC=()=>(e,t)=>{const r=t(),i=Lw(r).socket,n=tw(r),s=lw(r),o=rw(r),a=iw(r),c=nw(r),d=ew(r),l=OC(r),u=u_(t()),p=p_(t()),h=(e=>e.localParticipant.clientClaim)(t());null==i||i.emit("join_room",Object.assign({avatarUrl:null,config:{isAudioEnabled:p,isVideoEnabled:u},deviceCapabilities:{canScreenshare:!0},displayName:o,isCoLocated:!1,isDialIn:d,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:l,roomKey:s,roomName:n,userAgent:a,externalId:c},h&&{clientClaim:h})),e(DC("connecting"))};Jy([Be([Zy,OC,H_,Aw,v_,e=>e.roomConnection.error],(e,t,r,i,n,s)=>!(!(e&&"started"===n&&i&&t&&["ready","reconnecting","disconnected"].includes(r))||s))],({dispatch:e},t)=>{t&&e(IC())}),Ky({actionCreator:ow.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:i,resolution:n}=e,s=r();i===P_(s)&&("accepted"===n?(t(dw(e.metadata.roomKey)),t(IC())):"rejected"===n&&t(DC("knock_rejected")))}}),Ky({actionCreator:Xy,effect:(e,{dispatch:t,getState:r})=>{const i=r();if("connected"===H_(i)){const e=Lw(i).socket;null==e||e.emit("leave_room"),t(DC("leaving"))}else jw()}});const MC={audioEnabled:{actions:[vC.fulfilled],rtcEventName:"audioEnabled",getValue:e=>p_(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[bC.fulfilled],rtcEventName:"videoEnabled",getValue:e=>u_(e),getOutput:e=>({enabled:e})},localStream:{actions:[r_.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=b_(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({stream:e})},localScreenshareStream:{actions:[uS.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=hS(e))||void 0===t?void 0:t.getTracks().map(e=>({id:e.id,kind:e.kind,label:e.label}))},getOutput:e=>({tracks:e})},localScreenshareStreamStopped:{actions:[lS],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[fC],rtcEventName:"displayName",getValue:e=>{const t=O_(e),r=(e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.preferences})(e);return(null==r?void 0:r.hideInsightsDisplayNames)?"[[redacted]]":t},getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>P_(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>Rw(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>nw(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>OC(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>Nw(e),getOutput:e=>({status:e})},roomSessionId:{actions:[ow.newClient,ow.roomJoined,ow.roomSessionEnded,ow.clientLeft],rtcEventName:"roomSessionId",getValue:e=>(e=>{var t;return null===(t=e.roomConnection.session)||void 0===t?void 0:t.id})(e),getOutput:e=>({roomSessionId:e})},rtcConnectionStatus:{actions:null,rtcEventName:"rtcConnectionStatus",getValue:e=>eC(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>uw(e),getOutput:e=>({userRole:e})}},jC=Object.values(MC).flatMap(({actions:e})=>{var t;return null!==(t=null==e?void 0:e.map(e=>e))&&void 0!==t?t:null}).filter(e=>null!==e),LC=e=>"object"==typeof e?JSON.stringify(e):e,AC=Ct({name:"rtcAnalytics",initialState:{reportedValues:{}},reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),NC=()=>(e,t)=>{const r=t(),i=XS(r).rtcManager;i&&(i.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(MC).forEach(({rtcEventName:t,getValue:n,getOutput:s})=>{var o;const a=n(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=LC(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(i.sendStatsCustomEvent(t,c),e(BC({rtcEventName:t,value:a})))}))},{updateReportedValues:BC}=AC.actions;Ky({matcher:lt(...jC),effect:({type:e},{getState:t,dispatch:r})=>{var i;const n=t(),s=XS(n).rtcManager;if(!s)return;const o=Object.values(MC).find(({actions:t})=>null==t?void 0:t.map(e=>e.type).includes(e));if(!o)return;const{getValue:a,getOutput:c,rtcEventName:d}=o,l=a(n),u=LC(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(i=n.rtcAnalytics.reportedValues)||void 0===i?void 0:i[d])!==u&&(s.sendStatsCustomEvent(d,p),r(BC({rtcEventName:d,value:l})))}}),Jy([YS],({dispatch:e},t)=>{t&&e(NC())});const FC=Ct({name:"streaming",initialState:{isStreaming:!1,error:null,startedAt:void 0},reducers:{doHandleStreamingStarted:e=>Object.assign(Object.assign({},e),{isStreaming:!0,error:null,startedAt:(new Date).getTime()}),doHandleStreamingStopped:e=>Object.assign(Object.assign({},e),{isStreaming:!1})}}),{doHandleStreamingStarted:zC,doHandleStreamingStopped:VC}=FC.actions,UC=Ct({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(ow.roomJoined,(e,t)=>{if("error"in t.payload)return e;const{room:r}=t.payload;return r.knockers.length?Object.assign(Object.assign({},e),{waitingParticipants:r.knockers.map(e=>({id:e.clientId,displayName:e.displayName}))}):e}),e.addCase(ow.roomKnocked,(e,t)=>{const{clientId:r,displayName:i}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:i}]})}),e.addCase(ow.knockerLeft,(e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter(e=>e.id!==r)})})}}),$C=Gy(e=>(t,r)=>{const{participantId:i}=e,n=r(),s=Bw(n);null==s||s.emit("handle_knock",{action:"accept",clientId:i,response:{}})}),GC=Gy(e=>(t,r)=>{const{participantId:i}=e,n=r(),s=Bw(n);null==s||s.emit("handle_knock",{action:"reject",clientId:i,response:{}})}),qC=L({app:Qy.reducer,authorization:cw.reducer,breakout:I_.reducer,chat:F_.reducer,cloudRecording:V_.reducer,connectionMonitor:nC.reducer,deviceCredentials:_w.reducer,localMedia:Vw.reducer,localParticipant:hC.reducer,localScreenshare:dS.reducer,notifications:SC.reducer,organization:TC.reducer,remoteParticipants:eS.reducer,room:gS.reducer,roomConnection:EC.reducer,rtcAnalytics:AC.reducer,rtcConnection:AS.reducer,signalConnection:kw.reducer,spotlights:PS.reducer,streaming:FC.reducer,waitingParticipants:UC.reducer}),HC=(e,t)=>{var r;if(Yy.match(t)){const i={app:Object.assign(Object.assign({},Qy.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},Vw.getInitialState()),null==e?void 0:e.localMedia)};return qC(i,t)}return qC(e,t)};let WC,KC=class{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}};function JC(e,t){return Am.ok(e,`${t} is required`),e}function QC(e,t){return Am.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function XC(e,t){return Am.ok("number"==typeof e,`${t}<number> is required`),e}function YC(e,t){return Am.ok("string"==typeof e,`${t}<string> is required`),e}function ZC(e,t,r){const i=r||t.name[0].toLowerCase()+t.name.substring(1);return Am.ok(e instanceof t,`${i}<${t.name}> is required`),e}function eR(e,t){return Am.ok(Array.isArray(e),`${t}<array> is required`),e}function tR(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function rR(e,t,r){YC(t,"name"),function(e,t,r){YC(r,"name");const i=`${r} must be null or of type ${t}`;Am.ok(null===e||typeof e===t,i)}(e,"string",t)}function iR({baseUrl:e,url:t}){return e?e+t:t}class nR{constructor({baseUrl:e}){YC(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return ky.request(r)}request(e,t){return YC(e,"url"),Am.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Am.ok(t,"options are required"),this._requestAxios(e,t).then(e=>{const{data:t,headers:r,status:i,statusText:n,config:s}=e,o=s&&s.url?iR({baseUrl:s.baseURL,url:s.url}):null;return new KC({data:t,headers:r,status:i,statusText:n,url:o})}).catch(e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:i,status:n,statusText:s,config:o}=t,a=o&&o.url?iR({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new KC({data:r,headers:i,status:n,statusText:s,url:a}))})}}class sR{constructor({httpClient:e}){Am.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){Am.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach(r=>{const i=e[r];t.append(r,i)}),t}request(e,t={}){const r=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:r,transformRequest:sR.dataToFormData}))}}WC="object"==typeof window?window.btoa||vv:"object"==typeof global&&global.btoa||vv;const oR=()=>Promise.resolve(null);class aR{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then(r=>{const i=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${WC(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),n=Object.assign({},t,{headers:i});return this._httpClient.request(e,n)})}}class cR{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=oR}={}){this.authenticatedHttpClient=new aR({httpClient:new nR({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new sR({httpClient:this.authenticatedHttpClient})}request(e,t){return YC(e,"url"),Am.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Am.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return YC(e,"url"),Am.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Am.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function dR(e,t){return YC(tR(e,"data")[t],t)}const lR=(uR=dR,(e,t)=>{const r=tR(e,"data")[t];return null==r?null:uR(e,t)});var uR;function pR(e,t,r){return function(e,t){return eR(tR(e,"data")[t],t)}(e,t).map(e=>r(e))}class hR{constructor(e,t,r=void 0){this.credentials={uuid:e},this.hmac=t,this.userId=r}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new hR(dR(function(e,t){const r=tR(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),dR(e,"hmac"),lR(e,"userId")||void 0)}}class fR{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then(({data:e})=>hR.fromJson(e)).catch(e=>{if(e.response&&404===e.response.status)return null;throw e})}}class mR{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise(t=>{this._chromeStorage.get(this._key,r=>{t(r[this._key]||e)})})}save(e){return new Promise(t=>{this._chromeStorage.set({[this._key]:e},()=>{t()})})}}class gR{constructor(e,t){JC(t,"localStorage"),this._key=YC(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let vR;try{vR=self.localStorage}catch(iv){vR={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var bR=vR;const yR="credentials_saved";class wR extends bp{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const i=new fR({apiClient:new cR({baseUrl:e})});let n=null;if("localStorage"===r)n=new gR(t,bR);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);n=new mR(t,window.chrome.storage.local)}return new wR({deviceService:i,credentialsStore:n})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise(t=>{const r=()=>{this._deviceService.getCredentials().then(r=>e.save(r?r.toJson():null).then(()=>t(r))).catch(()=>{setTimeout(r,2e3)})};r()})}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then(e=>e?hR.fromJson(e):null)}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then(e=>e||this._fetchNewCredentialsFromApi())),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then(()=>(this.emit(yR,e),e))}setUserId(e){return this.getCurrentCredentials().then(t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))}).then(()=>{})}}class _R{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:i}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=i}static fromJson(e){return new _R({isExhausted:QC(e.isExhausted,"isExhausted"),renewsAt:new Date(YC(e.renewsAt,"renewsAt")),totalMinutesLimit:XC(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:XC(e.totalMinutesUsed,"totalMinutesUsed")})}}class SR{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:i,onTrialUntil:n,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=i,this.onTrialUntil=n||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new SR({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:QC(e.isDeactivated,"isDeactivated"),isOnTrial:QC(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?_R.fromJson(e.embeddedFreeTierStatus):null})}}function CR(e){return null!=e}function RR(e={}){return{maxNumberOfInvitationsAndUsers:CR(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:CR(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:CR(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:CR(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:CR(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class kR{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,ZC(e,Object,"properties"),YC(e.organizationId,"organizationId"),YC(e.organizationName,"organizationName"),YC(e.subdomain,"subdomain"),ZC(e.permissions,Object,"permissions"),ZC(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new SR(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=ZC(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},i=(null==t?void 0:t.onboardingSurvey)||null,n=ZC(t.permissions,Object,"permissions");return new kR({organizationId:YC(t.organizationId,"organizationId"),organizationName:YC(t.organizationName,"organizationName"),subdomain:YC(t.subdomain,"subdomain"),permissions:n,limits:RR(ZC(t.limits,Object,"limits")),account:t.account?SR.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:r,onboardingSurvey:i,type:"string"==typeof t.type?t.type:null})}}kR.GLOBAL_ORGANIZATION_ID="1";class TR{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:i,consents:n}=r||{},s="email"in r?{value:r.email,verificationCode:YC(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(YC(t,"subdomain"),YC(e,"organizationName"),YC(i,"owner.displayName"),Am.ok(s||o,"owner.email or owner.idToken is required"),n){eR(n,"consents");for(const{consentRevisionId:e,action:t}of n)YC(e,"consentRevisionId"),rR(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},s&&{email:s}),o&&{idToken:o}),n&&{consents:n}),{displayName:i})}}).then(({data:e})=>dR(e,"organizationId"))}getOrganizationBySubdomain(e){return YC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then(({data:e})=>kR.fromJson(e)).catch(e=>{if(e instanceof KC){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationByOrganizationId(e){return YC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then(({data:e})=>kR.fromJson(e)).catch(e=>{if(e instanceof KC){if(404===e.status)return null;throw new Error(e.statusText)}throw e})}getOrganizationsByContactPoint(e){const{code:t}=e,r="email"in e?e.email:null,i="phoneNumber"in e?e.phoneNumber:null;Am.ok((r||i)&&!(r&&i),"either email or phoneNumber is required"),YC(t,"code");const n=r?{type:"email",value:r}:{type:"phoneNumber",value:i};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:n,code:t}}).then(({data:e})=>pR(e,"organizations",e=>kR.fromJson(e)))}getOrganizationsByIdToken({idToken:e}){return YC(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then(({data:e})=>pR(e,"organizations",e=>kR.fromJson(Object.assign({permissions:{},limits:{}},tR(e,"organization")))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then(({data:e})=>pR(e,"organizations",e=>kR.fromJson(Object.assign({permissions:{},limits:{}},tR(e,"organization")))))}getSubdomainAvailability(e){return YC(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then(({data:e})=>(ZC(e,Object,"data"),{status:dR(e,"status")}))}updatePreferences({organizationId:e,preferences:t}){return JC(e,"organizationId"),JC(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then(()=>{})}deleteOrganization({organizationId:e}){return JC(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then(()=>{})}}class PR{constructor({organizationService:e,subdomain:t}){this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then(()=>{})}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}const OR="https://api.whereby.dev";const ER=s.createContext(null);R(ER);const DR=function(e=w){const t=e===w?k:R(e),r=()=>t().dispatch;return Object.assign(r,{withTypes:()=>r}),r}(ER),xR=function(e=w){const t=e===w?C:S(e),r=(e,r={})=>{const{equalityFn:i=T}="function"==typeof r?{equalityFn:r}:r;if(!e)throw new Error("You must pass a selector to useSelector");if("function"!=typeof e)throw new Error("You must pass a function as a selector to useSelector");if("function"!=typeof i)throw new Error("You must pass a function as an equality function to useSelector");const n=t(),{store:o,subscription:a,getServerState:c}=n,d=s.useRef(!0),l=s.useCallback({[e.name](t){const s=e(t);{const{devModeChecks:o={}}="function"==typeof r?{}:r,{identityFunctionCheck:a,stabilityCheck:c}=n,{identityFunctionCheck:l,stabilityCheck:u}={stabilityCheck:c,identityFunctionCheck:a,...o};if("always"===u||"once"===u&&d.current){const r=e(t);if(!i(s,r)){let i;try{throw new Error}catch(e){({stack:i}=e)}console.warn("Selector "+(e.name||"unknown")+" returned a different result when called with the same parameters. This can lead to unnecessary rerenders.\nSelectors that return a new reference (such as an object or an array) should be memoized: https://redux.js.org/usage/deriving-data-selectors#optimizing-selectors-with-memoization",{state:t,selected:s,selected2:r,stack:i})}}if(("always"===l||"once"===l&&d.current)&&s===t){let t;try{throw new Error}catch(e){({stack:t}=e)}console.warn("Selector "+(e.name||"unknown")+" returned the root state when called. This can lead to unnecessary rerenders.\nSelectors that return the entire state are almost certainly a mistake, as they will cause a rerender whenever *anything* in state changes.",{stack:t})}d.current&&(d.current=!1)}return s}}[e.name],[e]),u=p.useSyncExternalStoreWithSelector(a.addNestedSub,o.getState,c||o.getState,l,i);return s.useDebugValue(u),u};return Object.assign(r,{withTypes:()=>r}),r}(ER);var IR=function(){return IR=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},IR.apply(this,arguments)};function MR(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}"function"==typeof SuppressedError&&SuppressedError;const jR=DR.withTypes(),LR=xR.withTypes(),AR=({stream:e,muted:r})=>{const i=t.useRef(null),n=LR(l_);return t.useEffect(()=>{i.current&&!r&&e&&n&&(i.current.srcObject!==e&&(i.current.srcObject=e),i.current.setSinkId&&i.current.setSinkId(n))},[e,i,n,r]),i},NR=s.forwardRef((e,t)=>{var{muted:r,mirror:i=!1,stream:n,onVideoResize:o}=e,a=MR(e,["muted","mirror","stream","onVideoResize"]);const c=jR(),d=s.useRef(null),l=AR({muted:r,stream:n});return s.useImperativeHandle(t,()=>Object.assign(d.current,{captureAspectRatio:()=>{if(!d.current)return null;const e=d.current.videoHeight,t=d.current.videoWidth;return t&&e&&t+e>20?t/e:null}})),s.useEffect(()=>{if(!d.current)return;const e=new ResizeObserver(zw(()=>{if(d.current&&(null==n?void 0:n.id)){const e=d.current.clientWidth,t=d.current.clientHeight;c(KS({streamId:n.id,width:e,height:t})),o&&o({width:e,height:t,stream:n})}},{delay:1e3,edges:!0}));return e.observe(d.current),()=>{e.disconnect()}},[n]),s.useEffect(()=>{d.current&&(d.current.srcObject!==n&&(d.current.srcObject=n),d.current.muted!==r&&(d.current.muted=Boolean(r)))},[r,n,d]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:d,autoPlay:!0,playsInline:!0},a,{style:Object.assign({transform:i?"scaleX(-1)":"none",width:"100%",height:"100%"},a.style)})),s.createElement("audio",{ref:l,autoPlay:!0,playsInline:!0}))});NR.displayName="VideoView";const BR=Be(e=>e.chat.chatMessages,e=>e.cloudRecording,B_,L_,RS,CS,T_,b_,aS,wS,H_,e=>e.streaming,e=>e.waitingParticipants.waitingParticipants,kC,MS,(e,t,r,i,n,s,o,a,c,d,l,u,p,h,f)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,breakout:{isActive:i,currentGroup:r,groupedParticipants:n,participantsInCurrentGroup:s},connectionStatus:l,events:h,liveStream:u.isStreaming?{status:"streaming",startedAt:u.startedAt}:void 0,localScreenshareStatus:o.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},o),{stream:a}),remoteParticipants:c,screenshares:d,waitingParticipants:p,spotlightedParticipants:f})),FR={localMediaOptions:{audio:!0,video:!0}};const zR=Be(e=>e.localMedia.cameraDeviceError,S_,c_,d_,l_,e=>e.localMedia.isSettingCameraDevice,e=>e.localMedia.isSettingMicrophoneDevice,__,b_,e=>e.localMedia.microphoneDeviceError,C_,R_,e=>e.localMedia.startError,(e,t,r,i,n,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:i,currentSpeakerDeviceId:n,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p}));var VR={TABLET_BREAKPOINT:750,BOTTOM_TOOLBAR_HEIGHT:82,VIDEO_CONTROLS_MIN_WIDTH:420,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800};function UR({top:e=0,left:t=0}={}){return{top:e,left:t}}function $R({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function GR({top:e=0,left:t=0,width:r=0,height:i=0}={}){return{bounds:$R({width:r,height:i}),origin:UR({top:e,left:t})}}function qR({top:e=0,left:t=0,bottom:r=0,right:i=0}={}){return{top:e,left:t,bottom:r,right:i}}function HR(e){return!!e&&!(e.width<=0||e.height<=0)}function WR(e,t){const{width:r,height:i}=t,n=i,s=n*e,o=Math.min(r/s,i/n);return{width:s*o,height:n*o}}const KR=({vertical:e,width:t,height:r,count:i,aspectRatio:n})=>{const s=[1,2,3].map(s=>(({width:e,height:t,rows:r,cols:i,aspectRatio:n})=>{const s=WR(n,{width:e/i,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(i/s):s,cols:e?s:Math.ceil(i/s),aspectRatio:n})),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}};function JR({count:e,width:t,height:r,aspectRatio:i}){if(e<=1)return{rows:1,cols:1};const{splits:n,vertical:s}=(({width:e,height:t,count:r,aspectRatio:i})=>{const n=KR({vertical:!0,width:e,height:t,count:r,aspectRatio:i}),s=KR({vertical:!1,width:e,height:t,count:r,aspectRatio:i});return n.weight>s.weight?{splits:n.splits,vertical:!0}:{splits:s.splits,vertical:!1}})({width:t,height:r,count:e,aspectRatio:i});return s?{rows:Math.ceil(e/n),cols:n}:{rows:n,cols:Math.ceil(e/n)}}function QR(e){var{aspectRatio:t,children:r,className:i,height:n,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=MR(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=n,h=0,f=0;t&&(({width:u,height:p}=WR(t,{width:a,height:n})),h=(a-u)/2,f=(n-p)/2);const m=Object.assign({width:`${Math.round(u)}px`,height:`${Math.round(p)}px`},h||f?{transform:`translate3d(${Math.round(h)}px, ${Math.round(f)}px, 0)`}:{});return s.createElement("div",{className:i,style:Object.assign({position:"absolute",top:0,left:0},o)},s.createElement("div",Object.assign({style:m},l),s.cloneElement(r,{contentWidth:u,contentHeight:p,withRoundedCorners:c,withShadow:d})))}function XR({origin:e,bounds:t}){return{top:Math.round(e.top),left:Math.round(e.left),height:Math.round(t.height),width:Math.round(t.width)}}function YR({cell:e,child:t,clientId:r,style:i={},withRoundedCorners:n=!1,withShadow:o=!1}){const a=!HR(e.bounds);return s.createElement(QR,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:i,withRoundedCorners:n,withShadow:o,key:r},t)}function ZR({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:i,gridContent:n=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=GR(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return n.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.videoGrid)||void 0===o?void 0:o.cells)||[],c=e.map((e,o)=>{var c,d;if(!r.videoGrid)return null;const l=a[o],u={top:r.videoGrid.origin.top+r.videoGrid.paddings.top+l.origin.top,left:r.videoGrid.origin.left+r.videoGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return YR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`video-${o}`}),clientId:h||`video-${o}`,withRoundedCorners:i,style:p,withShadow:n})});return c}({content:n,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:i,withShadow:n}){var o;const a=(null===(o=r.presentationGrid)||void 0===o?void 0:o.cells)||[];return e.map((e,o)=>{var c,d;if(!r.presentationGrid)return null;const l=a[o],u={top:r.presentationGrid.origin.top+r.presentationGrid.paddings.top+l.origin.top,left:r.presentationGrid.origin.left+r.presentationGrid.paddings.left+l.origin.left},p={width:Math.round(l.bounds.width),height:Math.round(l.bounds.height),transform:`translate3d(${Math.round(u.left)}px, ${Math.round(u.top)}px, 0)`},h=null===(d=null===(c=null==e?void 0:e.props)||void 0===c?void 0:c.participant)||void 0===d?void 0:d.id;return YR({cell:l,child:s.cloneElement(e,{isSmallCell:l.isSmallCell,isZoomedByDefault:!!t&&!(null==e?void 0:e.props.participant.isPresentation),canZoom:!!t,key:h||`presentation-${o}`}),clientId:h||`presentation-${o}`,style:p,withRoundedCorners:i,withShadow:n})})}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),i&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:i}){var n;if(!r.floatingContent)return null;const o=r.floatingContent,a=o.origin.top,c=o.origin.left,d={width:Math.round(o.bounds.width),height:Math.round(o.bounds.height),transform:`translate3d(${Math.round(t.origin.left+c)}px, ${Math.round(t.origin.top+a)}px, 0)`,position:"fixed",top:o.bounds.height/2,left:0,zIndex:40},l=(null===(n=e.props.client)||void 0===n?void 0:n.id)||"floating";return YR({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:i,withShadow:!1})}({content:i,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:i}){const n=t.subgrid.cells;return e.map((e,o)=>{var a,c,d,l;const u=n[o],p={height:Math.round(u.bounds.height),width:Math.round(u.bounds.width),transform:""},h={top:t.subgrid.origin.top+u.origin.top,left:t.subgrid.origin.left+u.origin.left};p.transform=`translate3d(${Math.round(h.left)}px, ${Math.round(h.top)}px, 0)`;const f=null===(c=null===(a=null==e?void 0:e.props)||void 0===a?void 0:a.participant)||void 0===c?void 0:c.id,m=(null===(d=u.paddings)||void 0===d?void 0:d.left)||0,g=(null===(l=u.paddings)||void 0===l?void 0:l.right)||0;return YR({cell:u,child:s.cloneElement(e,{avatarSize:u.bounds.width-m-g,canZoom:!1,cellPaddings:u.paddings,isSmallCell:u.isSmallCell,isZoomedByDefault:!1,key:f||`subgrid-${o}`,style:p}),clientId:f||`subgrid-${o}`,style:p,withRoundedCorners:r,withShadow:i})})}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},HR(a.bounds)&&s.createElement("div",{style:XR(a)}),p,t&&s.createElement(s.Fragment,null))}const ek=16/9,tk=4/3,rk=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function ik({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let i=null;if(t===r)i=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(n=e).sort((e,t)=>n.filter(t=>t===e).length-n.filter(e=>e===t).length).pop():r;i=rk({value:t||r,min:tk,max:ek})}var n;return{minAr:t,maxAr:r,chosenAr:i}}const nk="rows",sk="columns";function ok({layoutGrid:e,dim:t,secDim:r,index:i,count:n,gridGap:s}){const o=(t-s*(n-1))*(e.fractions?e.fractions[i]:1/n),a=e.lines[i];return[o,(r-s*(a-1))/a]}function ak({isHorizontal:e,layoutGrid:t,width:r,height:i,gridGap:n}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?i:r,u=e?r:i;for(let r=0;r<d;r++){const i=ok({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:n}),p={width:e?i[1]:i[0],height:e?i[0]:i[1]},h=t.lines[r];for(let t=0;t<h;t++)s.push({origin:Object.assign({},c),bounds:p}),e?c.x+=p.width+n:c.y+=p.height+n;e?(c.y+=p.height+n,c.x=o):(c.x+=p.width+n,c.y=a)}return s}function ck({layoutGrid:e,width:t,height:r,gridGap:i}){switch(e.type){case nk:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return ak({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i});case sk:return function({layoutGrid:e,width:t,height:r,gridGap:i}){return ak({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:i})}({layoutGrid:e,width:t,height:r,gridGap:i})}}function dk({width:e,height:t,cellCount:r,gridGap:i=0,paddings:n=qR()}){const s=e-(n.left+n.right),o=t-(n.top+n.bottom),a=Math.round(s/o*10)/10<=1?function(e){return{1:{type:nk,lines:[1]},2:{type:nk,lines:[1,1]},3:{type:nk,lines:[2,1]},4:{type:nk,lines:[2,2]},5:{type:nk,lines:[2,2,1]},6:{type:nk,lines:[2,2,2]},7:{type:nk,lines:[3,2,2]},8:{type:nk,lines:[2,2,2,2]},9:{type:nk,lines:[3,2,2,2]},10:{type:nk,lines:[3,3,2,2]},11:{type:nk,lines:[3,3,3,2]},12:{type:nk,lines:[3,3,3,3]},13:{type:nk,lines:[2,2,3,3,3]},14:{type:nk,lines:[2,3,3,3,3]},15:{type:nk,lines:[3,3,3,3,3]},16:{type:nk,lines:[2,2,3,3,3,3]},17:{type:nk,lines:[2,3,3,3,3,3]},18:{type:nk,lines:[3,3,3,3,3,3]},19:{type:nk,lines:[2,2,3,3,3,3,3]},20:{type:nk,lines:[2,3,3,3,3,3,3]},21:{type:nk,lines:[3,3,3,3,3,3,3]},22:{type:nk,lines:[2,2,3,3,3,3,3,3]},23:{type:nk,lines:[2,3,3,3,3,3,3,3]},24:{type:nk,lines:[3,3,3,3,3,3,3,3]}}[e]||{type:nk,lines:[3,3,3,3,3,3,3,3]}}(r):function(e){return{1:{type:sk,lines:[1]},2:{type:sk,lines:[1,1]},3:{type:sk,lines:[2,1]},4:{type:sk,lines:[2,2]},5:{type:nk,lines:[3,2],fractions:[.45,.55]},6:{type:sk,lines:[2,2,2]},7:{type:nk,lines:[4,3],fractions:[.45,.55]},8:{type:sk,lines:[2,2,2,2]},9:{type:sk,lines:[3,2,2,2]},10:{type:sk,lines:[3,3,2,2]},11:{type:sk,lines:[3,3,3,2]},12:{type:sk,lines:[3,3,3,3]},13:{type:sk,lines:[4,3,3,3]},14:{type:sk,lines:[4,4,3,3]},15:{type:sk,lines:[3,3,3,3,3]},16:{type:sk,lines:[4,3,3,3,3]},17:{type:sk,lines:[4,4,3,3,3]},18:{type:sk,lines:[4,4,4,3,3]},19:{type:sk,lines:[4,4,4,4,3]},20:{type:sk,lines:[4,4,4,4,4]},21:{type:sk,lines:[5,4,4,4,4]},22:{type:sk,lines:[5,5,4,4,4]},23:{type:sk,lines:[5,5,5,4,4]},24:{type:sk,lines:[5,5,5,5,4]}}[e]||{type:sk,lines:[5,5,5,5,5]}}(r);return{cellRects:ck({layoutGrid:a,width:s,height:o,gridGap:i})||[],cellCount:r,gridGap:i,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:n}}function lk({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:i,paddings:n=qR()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-n.left-n.right,p=e.height-n.top-n.bottom;return r&&(t?(c=Math.floor(u/i.width),a=Math.ceil(r/c),s=u,o=a*i.height,d=(u-c*i.width)/2):(a=Math.floor(p/i.height),c=Math.ceil(r/a),s=c*i.width,o=p,l=(p-a*i.height)/2)),{isPortrait:t,width:s+n.left+n.right,height:o+n.top+n.bottom,cellBounds:i,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:n}}const{BOTTOM_TOOLBAR_HEIGHT:uk,VIDEO_CONTROLS_MIN_WIDTH:pk,TABLET_BREAKPOINT:hk,SUBGRID_EMPTY_STAGE_MAX_WIDTH:fk}=VR,mk=qR({top:4,bottom:28,left:8,right:8});function gk({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function vk({cellCount:e}){const t=e<=6;return $R({width:t?250:300,height:t?150:200})}function bk({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}){let o;for(let a=0;a<i.length;a++){const c=i[a];if(o=lk({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:$R({width:c+n.left+n.right,height:c+n.top+n.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:i,cellPaddings:n,paddings:s}),a=o.cellBounds.width-n.left-n.right===i[i.length-1],c=$R({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=$R({width:o.width,height:o.height});return 0===r?{bounds:c,contentBounds:d,videoCells:[]}:{bounds:c,contentBounds:d,videoCells:[...Array(r)].map((e,t)=>{const{top:r,left:i,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:i,cols:n,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/n):Math.floor(e%i),u=r?Math.floor(e%n):Math.floor(e/i),p=function({index:e,isPortrait:t,rows:r,cols:i,cellBounds:n,cellCount:s}){const o=r*i,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?i:r)-a)+1||e>c?0:a*(t?n.width:n.height)/2}({index:e,isPortrait:r,rows:i,cols:n,cellBounds:o,cellCount:s});return{top:d.top+c+l*o.height+(r?0:p),left:d.left+a+u*o.width+(r?p:0),width:o.width,height:o.height}}({index:t,layout:o});return{origin:UR({top:r,left:i}),bounds:$R({width:s,height:c}),paddings:n,isSmallCell:a}})}}function yk({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:i,gridGap:n,hasConstrainedOverflow:s,hasPresentationContent:o,hasVideoContent:a,isConstrained:c,isMaximizeMode:d,isPortrait:l,isSmallScreen:u,maxGridWidth:p,shouldOverflowSubgrid:h,subgridVideos:f}){const{width:m,height:g}=r,v=o||a,b=f.length>0;if(!b&&!v)return{isPortrait:l,videosContainer:GR(),subgrid:Object.assign(Object.assign({},GR()),{contentBounds:$R(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:GR(Object.assign(Object.assign({},r),i)),subgrid:Object.assign(Object.assign({},GR()),{contentBounds:$R(),cells:[]}),hasOverflow:s};const y=h?20:0;let w=null;if(v)if(h){const i=t[0];let n=d?uk:uk+e.top+(c||u?i/2:i)+e.bottom;r.height-n<200&&(n=0),w=$R({width:r.width,height:n})}else w=$R(d?{width:r.width,height:t[0]+e.top+e.bottom}:l?{width:r.width,height:r.height/2}:{width:r.width/2,height:r.height});else w=$R({width:Math.min(fk,r.width),height:r.height});let _=0;w.width>p&&(_=(w.width-p)/2);const S=bk({containerBounds:w,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:qR({top:y,left:_,right:_})}),C=$R({width:S.contentBounds.width-w.width,height:S.contentBounds.height-w.height}),R=C.width>0||C.height>0;let k,T=null;T=!v||h||R?S.contentBounds:S.bounds;let P=T;v?(P=$R(h?{width:0,height:w.height+y+n}:l?{width:0,height:S.bounds.height+n}:{width:S.bounds.width+n,height:0}),k=function({bounds:e,fromBounds:t}){return{width:Math.max(t.width-e.width,0),height:Math.max(t.height-e.height,0)}}({bounds:P,fromBounds:r})):k=$R();const O=Object.assign({},i);let E;return E=UR(v?{top:l?Math.max(i.top+g-P.height+n,0):i.top,left:l?i.left:Math.max(i.left+m-T.width,0)}:{top:i.top+Math.max(0,(g-T.height)/2),left:i.left+Math.max(0,(m-T.width)/2)}),{isPortrait:l,videosContainer:GR(Object.assign(Object.assign({},k),O)),subgrid:Object.assign(Object.assign({},GR(Object.assign(Object.assign({},T),E))),{cells:S.videoCells.map((e,t)=>{var r,i;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(i=f[t])||void 0===i?void 0:i.clientId},e)}),contentBounds:S.contentBounds}),hasOverflow:R||h||s,overflowNeedBounds:h?$R():C}}function wk({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:i,hasPresentationContent:n,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=$R(),p=UR(),h=o?Object.assign({},e):$R(),f=o?Object.assign({},t):UR();if(n){const n=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:i}){const{width:n,height:s}=e;if(!(r.width>0))return{isPortrait:n<=s,supersizedContentBounds:e};const o=Math.round(n/2),a=Math.round(s/2),c=Math.max(n-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;{const e=WR(t,{width:c,height:s}),r=WR(t,{width:n,height:d});if(l=t<=1?r.height>e.height:r.width>e.width,l){const e=d-Math.max(r.height,a);p=Math.max(e,0)}else{const t=c-Math.max(e.width,o);u=Math.max(t,0)}}return{isPortrait:l,supersizedContentBounds:{width:l?n:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:i,minGridContainerBounds:$R({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=n.isPortrait,u=n.supersizedContentBounds,p=Object.assign({},t),o&&(h=$R({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=UR({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},GR(Object.assign(Object.assign({},u),p))),videoGrid:GR(Object.assign(Object.assign({},h),f))}}function _k({containerBounds:e,paddings:t=qR(),videos:r,isConstrained:i,maxGridWidth:n,gridGap:s}){const{width:o,height:a}=e,c=n?Math.min(o,n):o,d=r.length;let l=null,u=null;if(i){const e=dk({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),i=d>4;u=r.map((t,r)=>{const n=function({index:e,layout:t}){const{cellRects:r}=t,i=r[e]||GR();return{top:i.origin.y,left:i.origin.x,width:i.bounds.width,height:i.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:UR({top:n.top,left:n.left}),bounds:$R({width:n.width,height:n.height}),aspectRatio:n.width/n.height,isSmallCell:i,type:"video"}}),l=e}else{const e=r.map(e=>e.aspectRatio||1),n=vk({cellCount:d}),o=function({width:e,height:t,cellCount:r,gridGap:i,cellAspectRatios:n=[tk],paddings:s=qR()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:i,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=ik({choices:n});let d=c.chosenAr;const{rows:l,cols:u}=JR({count:r,width:o,height:a,aspectRatio:d});1===l?d=rk({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=rk({value:o/(a/l),min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}));const{cellWidth:p,cellHeight:h,extraHorizontalPadding:f,extraVerticalPadding:m}=function({width:e,height:t,rows:r,cols:i,gridGap:n,aspectRatio:s}){const o=(e-(i-1)*n)/i,a=(t-(r-1)*n)/r,c=o/a;let d=0,l=0;return s<c?d=o-a*s:s>c&&(l=a-o/s),{cellWidth:o-d,cellHeight:a-l,extraHorizontalPadding:d*i/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:i,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:i,paddings:s}}({width:c,height:a,cellCount:d,gridGap:s,cellAspectRatios:e,paddings:t});u=r.map((e,t)=>{const r=function({index:e,layout:t}){const{cellWidth:r,cellHeight:i,rows:n,cols:s,cellCount:o,gridGap:a}=t,c=Math.floor(e/s),d=Math.floor(e%s),l=function({rows:e,cols:t,cellWidth:r,index:i,cellCount:n,gridGap:s}){const o=e*t,a=o-n;if(!a)return 0;const c=o-a-1;return i>=c-(t-a)+1&&i<=c?a*r/2+s:0}({rows:n,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*i+c*a,left:d*r+d*a+l,width:r,height:i}}({index:t,layout:o}),s=o.cellWidth<n.width,a=i||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:UR({top:r.top,left:r.left}),bounds:$R({width:r.width,height:r.height}),aspectRatio:a,isSmallCell:s,type:"video"}}),l=o}return{videoCells:u,extraHorizontalPadding:o!==c?l.extraHorizontalPadding+(o-c)/2:l.extraHorizontalPadding,extraVerticalPadding:l.extraVerticalPadding,paddings:l.paddings,gridGap:s}}function Sk({a:e,b:t,gridGap:r,isPortrait:i}){const n=i?e.vertical:e.horizontal,s=i?t.vertical:t.horizontal;if(n===s)return{a:0,b:0};const o=n<s?e:t,a=i?o.vertical:o.horizontal,c=(r+(n+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function Ck({gridGap:e,isConstrained:t,presentationVideos:r,videos:i,videosContainerLayout:n,gridLayoutPaddings:s=qR(),presentationGridLayoutPaddings:o=qR(),maxGridWidth:a}){return{gridLayout:_k({containerBounds:n.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:i}),presentationGridLayout:_k({containerBounds:n.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function Rk({floatingVideo:e,frame:t,gridGap:r,isConstrained:i,isMaximizeMode:n=!1,isXLMeetingSize:s=!1,paddings:o=qR(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=mk,subgridVideos:p=[],videoControlsHeight:h=0,videos:f=[],videoGridGap:m}){let g=s&&(!screen||screen.width<=2048);const v=!!a.length,b=a.length>1,y=v&&!b?a[0].aspectRatio:null,w=!!f.length,_=t.bounds.width-o.left-o.right;let S=t.bounds.height-o.top-o.bottom;const C=Math.max(2200,.8*_),R=i&&f.length>12,k=S/4,T=Math.ceil((f.length-12)/3);S=R?S+k*T:S;const P=$R({width:_,height:S}),O=UR({top:o.top,left:o.left}),E=vk({cellCount:f.length}),D=d.width<hk||d.height<hk,x=n||g||!(v||w)||P.width<=P.height,I={cellPaddings:u,containerBounds:P,containerOrigin:O,gridGap:r,hasPresentationContent:v,hasVideoContent:w,isConstrained:i,isMaximizeMode:n,isSmallScreen:D,subgridVideos:p,maxGridWidth:C};let M=yk(Object.assign(Object.assign({},I),{cellSizeOptions:gk({hasOverflow:g,hasStage:v||w}),isPortrait:x,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})),j=!1;if(!g&&l&&!M.hasOverflow){yk(Object.assign(Object.assign({},I),{containerBounds:$R({width:P.width,height:P.height-uk}),cellSizeOptions:gk({hasOverflow:g,hasStage:v||w}),isPortrait:x,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})).hasOverflow&&(j=!0)}(j||M.hasOverflow&&!g)&&(g=!0,M=yk(Object.assign(Object.assign({},I),{cellSizeOptions:gk({hasOverflow:!0,hasStage:v||w}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})));const L=wk({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:w,minGridBounds:E});let{gridLayout:A,presentationGridLayout:N}=Ck({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C});if(M.hasOverflow&&!g){const{vPaddings:e,hPaddings:t}=function({need:e,stageLayout:t,gridLayout:r,presentationGridLayout:i,videosContainerLayout:n}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,i.extraVerticalPadding);s={presentationGrid:Math.min(n.isPortrait?i.extraVerticalPadding:t,e.height),grid:Math.min(n.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,i.extraHorizontalPadding);o={presentationGrid:Math.min(n.isPortrait?t:i.extraHorizontalPadding,e.width),grid:Math.min(n.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||$R(),stageLayout:M,gridLayout:A,presentationGridLayout:N,videosContainerLayout:L});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:i}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=i.isPortrait?2*e.presentationGrid+2*e.grid:e.presentationGrid+e.grid;r.videosContainer.bounds.height-=t,r.subgrid.origin.top-=t,r.subgrid.bounds.height+=t,i.presentationGrid.bounds.height-=2*e.presentationGrid,i.videoGrid.bounds.height-=2*e.grid,i.isPortrait&&(i.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=i.isPortrait?t.presentationGrid+t.grid:2*t.presentationGrid+2*t.grid;r.videosContainer.bounds.width-=e,r.subgrid.origin.left-=e,r.subgrid.bounds.width+=e,i.presentationGrid.bounds.width-=2*t.presentationGrid,i.videoGrid.bounds.width-=2*t.grid,i.isPortrait||(i.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:L}),({gridLayout:A,presentationGridLayout:N}=Ck({gridGap:m||r,isConstrained:i,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C})))}const B=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:i,margin:n=8}){if(!r)return null;const s=WR(r.aspectRatio||0,{width:200,height:200}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+n)<pk;let c=0;o&&a?c=-1*i:o||a||(c=i);const d=UR({top:t.origin.top+(t.bounds.height-s.height-n)+c,left:t.origin.left+(t.bounds.width-s.width-n)});return{clientId:r.clientId,isDraggable:r.isDraggable,origin:d,bounds:s,aspectRatio:r.aspectRatio,isSmallCell:!0}}({roomBounds:d,containerFrame:t,floatingVideo:e||null,videoControlsHeight:h});c&&function({videosContainerLayout:e,gridLayout:t,presentationGridLayout:r,stageLayout:i,gridGap:n,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=i.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const i=Sk({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:n,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=i.a,e.videoGrid.origin.top-=i.b,d.vertical=i.b):(e.presentationGrid.origin.left+=i.a,e.videoGrid.origin.left-=i.b,d.horizontal=i.b)}if(c&&(o||a)&&!s){const s={horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},c={horizontal:t.extraHorizontalPadding+d.horizontal,vertical:t.extraVerticalPadding+d.vertical};let l;const u=o&&a;l=u&&e.isPortrait&&!i.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&i.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=Sk({a:l,b:{horizontal:0,vertical:0},gridGap:n,isPortrait:i.isPortrait});i.isPortrait?i.subgrid.origin.top-=p.b:i.subgrid.origin.left-=p.b}}({videosContainerLayout:L,gridLayout:A,presentationGridLayout:N,stageLayout:M,gridGap:r,shouldOverflowSubgrid:g});let F=o.top+M.videosContainer.bounds.height+M.subgrid.bounds.height+o.bottom;return(v||w)&&(F+=r),{isPortrait:M.isPortrait,hasOverflow:M.hasOverflow,videosContainer:Object.assign(Object.assign({},L),{bounds:$R({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:UR({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:$R({height:g?F:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},L.presentationGrid),{cells:N.videoCells,paddings:qR({top:N.paddings.top+N.extraVerticalPadding,bottom:N.paddings.bottom+N.extraVerticalPadding,left:N.paddings.left+N.extraHorizontalPadding,right:N.paddings.right+N.extraHorizontalPadding})}),videoGrid:Object.assign(Object.assign({},L.videoGrid),{cells:A.videoCells,paddings:qR({top:A.paddings.top+A.extraVerticalPadding,bottom:A.paddings.bottom+A.extraVerticalPadding,left:A.paddings.left+A.extraHorizontalPadding,right:A.paddings.right+A.extraHorizontalPadding})}),subgrid:M.subgrid,floatingContent:Object.assign(Object.assign(Object.assign({},B),e),{origin:(null==B?void 0:B.origin)||UR(),bounds:(null==B?void 0:B.bounds)||$R(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function kk({aspectRatio:e,avatarSize:t,cellPaddings:r,client:i,isDraggable:n=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:i,clientId:(null==i?void 0:i.id)||"",isDraggable:n,isPlaceholder:s,isSubgrid:o,type:"video"}}function Tk({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=12,gridGap:i=8,videoGridGap:n=8,enableSubgrid:o=!0,enableConstrainedGrid:a=!0}={}){const[c,d]=s.useState({width:0,height:0}),[l,u]=s.useState(!1),[p,h]=s.useState({}),[f,m]=s.useState(null),[g,v]=s.useState(null),{clientViewsInGrid:b,clientViewsInPresentationGrid:y,clientViewsInSubgrid:w,floatingClientView:_}=function({activeVideosSubgridTrigger:e=12,stageParticipantLimit:t=12,forceSubgrid:r=!0,enableSubgrid:i=!0,maximizedParticipant:n,floatingParticipant:o,isConstrained:a=!1}={}){const c=LR(SS),d=LR(MS),l=LR(cS),u=s.useMemo(()=>o,[o]),p=s.useMemo(()=>u?c.filter(e=>e.id!==u.id):c,[c,u]),h=s.useMemo(()=>!!i&&(!!r||l>t),[r,l,t,i]),f=s.useMemo(()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:i,maximizedParticipant:n,isPhoneResolution:s}){if(!r)return[];const o=i.length>0,a=(n?e.filter(e=>e.id!==n.id):e).filter(e=>!e.isPresentation&&!i.includes(e)),c=a.filter(e=>!e.isVideoEnabled),d=a.filter(e=>e.isVideoEnabled).length>t,l=a.filter(e=>!c.includes(e)&&e.isAudioEnabled),u=a.filter(e=>!c.includes(e)&&!e.isAudioEnabled);if(c.length&&o)return[...u,...c];if(s&&a.length>24){const e=[...l,...u],t=e.slice(0,24);return t.length<=24?[...e.filter(e=>!t.includes(e)),...c]:[...u,...c]}if(d&&u.length){const e=[...l,...u].slice(0,t);return e.length<=t?[...u.filter(t=>!e.includes(t)),...c]:[...u,...c]}return c}({clientViews:p,activeVideosSubgridTrigger:e,shouldShowSubgrid:h,spotlightedParticipants:d,maximizedParticipant:n,isPhoneResolution:a}),[p,h,e,d,a]),m=s.useMemo(()=>p.filter(e=>!f.includes(e)),[p,f]),g=s.useMemo(()=>n?[n]:d,[d,n]),v=s.useMemo(()=>m.filter(e=>!g.includes(e)),[m,g]);return{floatingClientView:u,clientViewsInGrid:v,clientViewsInPresentationGrid:g,clientViewsInSubgrid:f}}({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo(()=>_?[kk({client:_,aspectRatio:p[_.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[],[_,p]),C=s.useMemo(()=>b.map(e=>kk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[b,p]),R=s.useMemo(()=>y.map(e=>kk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})),[y,p]),k=s.useMemo(()=>w.map(e=>kk({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})),[w,p]),T=s.useMemo(()=>GR(c),[c]);s.useEffect(()=>{a&&u(c.width<500||c.height<500)},[c,a]);const P=s.useMemo(()=>Rk({floatingVideo:S[0],frame:T,gridGap:i,isConstrained:l,roomBounds:T.bounds,videos:C,videoGridGap:n,presentationVideos:R,subgridVideos:k}),[T,S,C,R,k,i,n]);return{containerFrame:T,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:R,cellViewsInSubgrid:k,clientAspectRatios:p,videoStage:P,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}var Pk={exports:{}};const Ok=55296,Ek=127995,Dk=127999,xk=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function Ik(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,i=0;for(;r<e.length;)i+=Mk(r+i,e),Nk(e[r+i])&&i++,Lk(e[r+i])&&i++,Ak(e[r+i])&&i++,Bk(e[r+i])?i++:(t.push(e.substring(r,r+i)),r+=i,i=0);return t}function Mk(e,t){const r=t[e];if(!function(e){return e&&zk(e[0].charCodeAt(0),Ok,56319)}(r)||e===t.length-1)return 1;const i=r+t[e+1];let n=t.substring(e+2,e+5);return jk(i)&&jk(n)||function(e){return zk(Fk(e),Ek,Dk)}(n)?4:2}function jk(e){return zk(Fk(e),127462,127487)}function Lk(e){return"string"==typeof e&&zk(e.charCodeAt(0),65024,65039)}function Ak(e){return"string"==typeof e&&zk(e.charCodeAt(0),8400,8447)}function Nk(e){return"string"==typeof e&&-1!==xk.indexOf(e.charCodeAt(0))}function Bk(e){return"string"==typeof e&&8205===e.charCodeAt(0)}function Fk(e){return(e.charCodeAt(0)-Ok<<10)+(e.charCodeAt(1)-56320)+65536}function zk(e,t,r){return e>=t&&e<=r}Pk.exports=Ik,Pk.exports.substr=function(e,t,r){const i=Ik(e);if(void 0===t)return e;if(t>=i.length)return"";const n=i.length-t;let s=t+(void 0===r?n:r);return s>t+n&&(s=void 0),i.slice(t,s).join("")};var Vk=c(Pk.exports);const Uk=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map(e=>Vk(e)[0]).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,i=t.join("").toUpperCase();return s.createElement("svg",{viewBox:"-60 -60 120 120","aria-hidden":"true",style:{height:"100%",pointerEvents:"none",width:"100%"}},s.createElement("text",{x:0,y:0,textAnchor:"middle",dominantBaseline:"central",fontSize:r},i))};function $k(e){var{avatarUrl:t,className:r,size:i=40,name:n,variant:o="round"}=e,a=MR(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${i}px`,width:`${i}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:n},a),!t&&n?s.createElement(Uk,{name:n}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function Gk({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:i,stream:n,muted:o}){const a=AR({stream:n,muted:o});return s.createElement(s.Fragment,null,s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:i?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement($k,{variant:"square",avatarUrl:e,name:t,size:r?60:80}))),s.createElement("audio",{ref:a,autoPlay:!0,playsInline:!0}))}function qk(e,t,{checkForDefaultPrevented:r=!0}={}){return function(i){if(e?.(i),!1===r||!i.defaultPrevented)return t?.(i)}}function Hk(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function Wk(...e){return t=>{let r=!1;const i=e.map(e=>{const i=Hk(e,t);return r||"function"!=typeof i||(r=!0),i});if(r)return()=>{for(let t=0;t<i.length;t++){const r=i[t];"function"==typeof r?r():Hk(e[t],null)}}}}function Kk(...e){return s.useCallback(Wk(...e),e)}var Jk,Qk={exports:{}},Xk={};Qk.exports=(Jk||(Jk=1,function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===A?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case R:return"Fragment";case C:return"Portal";case T:return"Profiler";case k:return"StrictMode";case D:return"Suspense";case x:return"SuspenseList"}if("object"==typeof t)switch("number"==typeof t.tag&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),t.$$typeof){case O:return(t.displayName||"Context")+".Provider";case P:return(t._context.displayName||"Context")+".Consumer";case E:var r=t.render;return(t=t.displayName)||(t=""!==(t=r.displayName||r.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case I:return null!==(r=t.displayName||null)?r:e(t.type)||"Memo";case M:r=t._payload,t=t._init;try{return e(t(r))}catch(e){}}return null}function r(e){return""+e}function i(e){try{r(e);var t=!1}catch(e){t=!0}if(t){var i=(t=console).error,n="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",n),r(e)}}function n(){}function s(e){if(void 0===$)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);$=t&&t[1]||"",G=-1<e.stack.indexOf("\n at")?" (<anonymous>)":-1<e.stack.indexOf("@")?"@unknown:0:0":""}return"\n"+$+e+G}function o(e,t){if(!e||H)return"";var r,i=W.get(e);if(void 0!==i)return i;H=!0,i=Error.prepareStackTrace,Error.prepareStackTrace=void 0,r=N.H,N.H=null,function(){if(0===U){f=console.log,m=console.info,g=console.warn,v=console.error,b=console.group,y=console.groupCollapsed,w=console.groupEnd;var e={configurable:!0,enumerable:!0,value:n,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}U++}();try{var o={DetermineComponentFrameRoot:function(){try{if(t){var r=function(){throw Error()};if(Object.defineProperty(r.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(r,[])}catch(e){var i=e}Reflect.construct(e,[],r)}else{try{r.call()}catch(e){i=e}e.call(r.prototype)}}else{try{throw Error()}catch(e){i=e}(r=e())&&"function"==typeof r.catch&&r.catch(function(){})}}catch(e){if(e&&i&&"string"==typeof e.stack)return[e.stack,i.stack]}return[null,null]}};o.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var a=Object.getOwnPropertyDescriptor(o.DetermineComponentFrameRoot,"name");a&&a.configurable&&Object.defineProperty(o.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var c=o.DetermineComponentFrameRoot(),d=c[0],l=c[1];if(d&&l){var u=d.split("\n"),p=l.split("\n");for(c=a=0;a<u.length&&!u[a].includes("DetermineComponentFrameRoot");)a++;for(;c<p.length&&!p[c].includes("DetermineComponentFrameRoot");)c++;if(a===u.length||c===p.length)for(a=u.length-1,c=p.length-1;1<=a&&0<=c&&u[a]!==p[c];)c--;for(;1<=a&&0<=c;a--,c--)if(u[a]!==p[c]){if(1!==a||1!==c)do{if(a--,0>--c||u[a]!==p[c]){var h="\n"+u[a].replace(" at new "," at ");return e.displayName&&h.includes("<anonymous>")&&(h=h.replace("<anonymous>",e.displayName)),"function"==typeof e&&W.set(e,h),h}}while(1<=a&&0<=c);break}}}finally{H=!1,N.H=r,function(){if(0===--U){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:F({},e,{value:f}),info:F({},e,{value:m}),warn:F({},e,{value:g}),error:F({},e,{value:v}),group:F({},e,{value:b}),groupCollapsed:F({},e,{value:y}),groupEnd:F({},e,{value:w})})}0>U&&console.error("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=i}return u=(u=e?e.displayName||e.name:"")?s(u):"","function"==typeof e&&W.set(e,u),u}function a(e){if(null==e)return"";if("function"==typeof e){var t=e.prototype;return o(e,!(!t||!t.isReactComponent))}if("string"==typeof e)return s(e);switch(e){case D:return s("Suspense");case x:return s("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case E:return o(e.render,!1);case I:return a(e.type);case M:t=e._payload,e=e._init;try{return a(e(t))}catch(e){}}return""}function c(){var e=N.A;return null===e?null:e.getOwner()}function d(){var t=e(this.type);return J[t]||(J[t]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),void 0!==(t=this.props.ref)?t:null}function l(t,r,n,s,o,a){if("string"==typeof t||"function"==typeof t||t===R||t===T||t===k||t===D||t===x||t===j||"object"==typeof t&&null!==t&&(t.$$typeof===M||t.$$typeof===I||t.$$typeof===O||t.$$typeof===P||t.$$typeof===E||t.$$typeof===z||void 0!==t.getModuleId)){var l=r.children;if(void 0!==l)if(s)if(V(l)){for(s=0;s<l.length;s++)u(l[s],t);Object.freeze&&Object.freeze(l)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else u(l,t)}else l="",(void 0===t||"object"==typeof t&&null!==t&&0===Object.keys(t).length)&&(l+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."),null===t?s="null":V(t)?s="array":void 0!==t&&t.$$typeof===S?(s="<"+(e(t.type)||"Unknown")+" />",l=" Did you accidentally export a JSX literal instead of a component?"):s=typeof t,console.error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",s,l);if(B.call(r,"key")){l=e(t);var p=Object.keys(r).filter(function(e){return"key"!==e});s=0<p.length?"{key: someKey, "+p.join(": ..., ")+": ...}":"{key: someKey}",Q[l+s]||(p=0<p.length?"{"+p.join(": ..., ")+": ...}":"{}",console.error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',s,l,p,l),Q[l+s]=!0)}if(l=null,void 0!==n&&(i(n),l=""+n),function(e){if(B.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(r)&&(i(r.key),l=""+r.key),"key"in r)for(var h in n={},r)"key"!==h&&(n[h]=r[h]);else n=r;return l&&function(e,t){function r(){q||(q=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}r.isReactWarning=!0,Object.defineProperty(e,"key",{get:r,configurable:!0})}(n,"function"==typeof t?t.displayName||t.name||"Unknown":t),function(e,t,r,i,n,s){return r=s.ref,e={$$typeof:S,type:e,key:t,props:s,_owner:n},null!==(void 0!==r?r:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:d}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(t,l,a,0,c(),n)}function u(e,t){if("object"==typeof e&&e&&e.$$typeof!==K)if(V(e))for(var r=0;r<e.length;r++){var i=e[r];p(i)&&h(i,t)}else if(p(e))e._store&&(e._store.validated=1);else if("function"==typeof(r=null===e||"object"!=typeof e?null:"function"==typeof(r=L&&e[L]||e["@@iterator"])?r:null)&&r!==e.entries&&(r=r.call(e))!==e)for(;!(e=r.next()).done;)p(e.value)&&h(e.value,t)}function p(e){return"object"==typeof e&&null!==e&&e.$$typeof===S}function h(t,r){if(t._store&&!t._store.validated&&null==t.key&&(t._store.validated=1,r=function(t){var r="",i=c();return i&&(i=e(i.type))&&(r="\n\nCheck the render method of `"+i+"`."),r||(t=e(t))&&(r="\n\nCheck the top-level render call using <"+t+">."),r}(r),!X[r])){X[r]=!0;var i="";t&&null!=t._owner&&t._owner!==c()&&(i=null,"number"==typeof t._owner.tag?i=e(t._owner.type):"string"==typeof t._owner.name&&(i=t._owner.name),i=" It was passed a child from "+i+".");var n=N.getCurrentStack;N.getCurrentStack=function(){var e=a(t.type);return n&&(e+=n()||""),e},console.error('Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',r,i),N.getCurrentStack=n}}var f,m,g,v,b,y,w,_=t,S=Symbol.for("react.transitional.element"),C=Symbol.for("react.portal"),R=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),T=Symbol.for("react.profiler"),P=Symbol.for("react.consumer"),O=Symbol.for("react.context"),E=Symbol.for("react.forward_ref"),D=Symbol.for("react.suspense"),x=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),M=Symbol.for("react.lazy"),j=Symbol.for("react.offscreen"),L=Symbol.iterator,A=Symbol.for("react.client.reference"),N=_.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=Object.prototype.hasOwnProperty,F=Object.assign,z=Symbol.for("react.client.reference"),V=Array.isArray,U=0;n.__reactDisabledLog=!0;var $,G,q,H=!1,W=new("function"==typeof WeakMap?WeakMap:Map),K=Symbol.for("react.client.reference"),J={},Q={},X={};Xk.Fragment=R,Xk.jsx=function(e,t,r,i,n){return l(e,t,r,!1,0,n)},Xk.jsxs=function(e,t,r,i,n){return l(e,t,r,!0,0,n)}}()),Xk);var Yk=Qk.exports;function Zk(e,t=[]){let r=[];const i=()=>{const t=r.map(e=>s.createContext(e));return function(r){const i=r?.[e]||t;return s.useMemo(()=>({[`__scope${e}`]:{...r,[e]:i}}),[r,i])}};return i.scopeName=e,[function(t,i){const n=s.createContext(i),o=r.length;r=[...r,i];const a=t=>{const{scope:r,children:i,...a}=t,c=r?.[e]?.[o]||n,d=s.useMemo(()=>a,Object.values(a));return Yk.jsx(c.Provider,{value:d,children:i})};return a.displayName=t+"Provider",[a,function(r,a){const c=a?.[e]?.[o]||n,d=s.useContext(c);if(d)return d;if(void 0!==i)return i;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},eT(i,...t)]}function eT(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const i=r.reduce((t,{useScope:r,scopeName:i})=>({...t,...r(e)[`__scope${i}`]}),{});return s.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return r.scopeName=t.scopeName,r}function tT(e){const t=rT(e),r=s.forwardRef((e,r)=>{const{children:i,...n}=e,o=s.Children.toArray(i),a=o.find(nT);if(a){const e=a.props.children,i=o.map(t=>t===a?s.Children.count(e)>1?s.Children.only(null):s.isValidElement(e)?e.props.children:null:t);return Yk.jsx(t,{...n,ref:r,children:s.isValidElement(e)?s.cloneElement(e,void 0,i):null})}return Yk.jsx(t,{...n,ref:r,children:i})});return r.displayName=`${e}.Slot`,r}function rT(e){const t=s.forwardRef((e,t)=>{const{children:r,...i}=e;if(s.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),n=function(e,t){const r={...t};for(const i in t){const n=e[i],s=t[i];/^on[A-Z]/.test(i)?n&&s?r[i]=(...e)=>{const t=s(...e);return n(...e),t}:n&&(r[i]=n):"style"===i?r[i]={...n,...s}:"className"===i&&(r[i]=[n,s].filter(Boolean).join(" "))}return{...e,...r}}(i,r.props);return r.type!==s.Fragment&&(n.ref=t?Wk(t,e):e),s.cloneElement(r,n)}return s.Children.count(r)>1?s.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var iT=Symbol("radix.slottable");function nT(e){return s.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===iT}var sT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=tT(`Primitive.${t}`),i=s.forwardRef((e,i)=>{const{asChild:n,...s}=e,o=n?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Yk.jsx(o,{...s,ref:i})});return i.displayName=`Primitive.${t}`,{...e,[t]:i}},{});function oT(e){const t=s.useRef(e);return s.useEffect(()=>{t.current=e}),s.useMemo(()=>(...e)=>t.current?.(...e),[])}var aT,cT="dismissableLayer.update",dT="dismissableLayer.pointerDownOutside",lT="dismissableLayer.focusOutside",uT=s.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),pT=s.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:i,onPointerDownOutside:n,onFocusOutside:o,onInteractOutside:a,onDismiss:c,...d}=e,l=s.useContext(uT),[u,p]=s.useState(null),h=u?.ownerDocument??globalThis?.document,[,f]=s.useState({}),m=Kk(t,e=>p(e)),g=Array.from(l.layers),[v]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),b=g.indexOf(v),y=u?g.indexOf(u):-1,w=l.layersWithOutsidePointerEventsDisabled.size>0,_=y>=b,S=function(e,t=globalThis?.document){const r=oT(e),i=s.useRef(!1),n=s.useRef(()=>{});return s.useEffect(()=>{const e=e=>{if(e.target&&!i.current){let i=function(){fT(dT,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",n.current),n.current=i,t.addEventListener("click",n.current,{once:!0})):i()}else t.removeEventListener("click",n.current);i.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",n.current)}},[t,r]),{onPointerDownCapture:()=>i.current=!0}}(e=>{const t=e.target,r=[...l.branches].some(e=>e.contains(t));_&&!r&&(n?.(e),a?.(e),e.defaultPrevented||c?.())},h),C=function(e,t=globalThis?.document){const r=oT(e),i=s.useRef(!1);return s.useEffect(()=>{const e=e=>{if(e.target&&!i.current){fT(lT,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}(e=>{const t=e.target;[...l.branches].some(e=>e.contains(t))||(o?.(e),a?.(e),e.defaultPrevented||c?.())},h);return function(e,t=globalThis?.document){const r=oT(e);s.useEffect(()=>{const e=e=>{"Escape"===e.key&&r(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[r,t])}(e=>{y===l.layers.size-1&&(i?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))},h),s.useEffect(()=>{if(u)return r&&(0===l.layersWithOutsidePointerEventsDisabled.size&&(aT=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(u)),l.layers.add(u),hT(),()=>{r&&1===l.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=aT)}},[u,h,r,l]),s.useEffect(()=>()=>{u&&(l.layers.delete(u),l.layersWithOutsidePointerEventsDisabled.delete(u),hT())},[u,l]),s.useEffect(()=>{const e=()=>f({});return document.addEventListener(cT,e),()=>document.removeEventListener(cT,e)},[]),Yk.jsx(sT.div,{...d,ref:m,style:{pointerEvents:w?_?"auto":"none":void 0,...e.style},onFocusCapture:qk(e.onFocusCapture,C.onFocusCapture),onBlurCapture:qk(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:qk(e.onPointerDownCapture,S.onPointerDownCapture)})});pT.displayName="DismissableLayer";function hT(){const e=new CustomEvent(cT);document.dispatchEvent(e)}function fT(e,t,r,{discrete:i}){const n=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&n.addEventListener(e,t,{once:!0}),i?function(e,t){e&&o.flushSync(()=>e.dispatchEvent(t))}(n,s):n.dispatchEvent(s)}s.forwardRef((e,t)=>{const r=s.useContext(uT),i=s.useRef(null),n=Kk(t,i);return s.useEffect(()=>{const e=i.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),Yk.jsx(sT.div,{...e,ref:n})}).displayName="DismissableLayerBranch";var mT=0;function gT(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var vT="focusScope.autoFocusOnMount",bT="focusScope.autoFocusOnUnmount",yT={bubbles:!1,cancelable:!0},wT=s.forwardRef((e,t)=>{const{loop:r=!1,trapped:i=!1,onMountAutoFocus:n,onUnmountAutoFocus:o,...a}=e,[c,d]=s.useState(null),l=oT(n),u=oT(o),p=s.useRef(null),h=Kk(t,e=>d(e)),f=s.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;s.useEffect(()=>{if(i){let e=function(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:RT(p.current,{select:!0})},t=function(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||RT(p.current,{select:!0}))},r=function(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&RT(c)};document.addEventListener("focusin",e),document.addEventListener("focusout",t);const i=new MutationObserver(r);return c&&i.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),i.disconnect()}}},[i,c,f.paused]),s.useEffect(()=>{if(c){kT.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(vT,yT);c.addEventListener(vT,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const i of e)if(RT(i,{select:t}),document.activeElement!==r)return}((e=_T(c),e.filter(e=>"A"!==e.tagName)),{select:!0}),document.activeElement===t&&RT(c))}return()=>{c.removeEventListener(vT,l),setTimeout(()=>{const e=new CustomEvent(bT,yT);c.addEventListener(bT,u),c.dispatchEvent(e),e.defaultPrevented||RT(t??document.body,{select:!0}),c.removeEventListener(bT,u),kT.remove(f)},0)}}var e},[c,l,u,f]);const m=s.useCallback(e=>{if(!r&&!i)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,n=document.activeElement;if(t&&n){const t=e.currentTarget,[i,s]=function(e){const t=_T(e),r=ST(t,e),i=ST(t.reverse(),e);return[r,i]}(t);i&&s?e.shiftKey||n!==s?e.shiftKey&&n===i&&(e.preventDefault(),r&&RT(s,{select:!0})):(e.preventDefault(),r&&RT(i,{select:!0})):n===t&&e.preventDefault()}},[r,i,f.paused]);return Yk.jsx(sT.div,{tabIndex:-1,...a,ref:h,onKeyDown:m})});function _T(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function ST(e,t){for(const r of e)if(!CT(r,{upTo:t}))return r}function CT(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function RT(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}wT.displayName="FocusScope";var kT=function(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=TT(e,t),e.unshift(t)},remove(t){e=TT(e,t),e[0]?.resume()}}}();function TT(e,t){const r=[...e],i=r.indexOf(t);return-1!==i&&r.splice(i,1),r}var PT=globalThis?.document?s.useLayoutEffect:()=>{},OT=s[" useId ".trim().toString()]||(()=>{}),ET=0;function DT(e){const[t,r]=s.useState(OT());return PT(()=>{r(e=>e??String(ET++))},[e]),e||(t?`radix-${t}`:"")}const xT=["top","right","bottom","left"],IT=Math.min,MT=Math.max,jT=Math.round,LT=Math.floor,AT=e=>({x:e,y:e}),NT={left:"right",right:"left",bottom:"top",top:"bottom"},BT={start:"end",end:"start"};function FT(e,t,r){return MT(e,IT(t,r))}function zT(e,t){return"function"==typeof e?e(t):e}function VT(e){return e.split("-")[0]}function UT(e){return e.split("-")[1]}function $T(e){return"x"===e?"y":"x"}function GT(e){return"y"===e?"height":"width"}const qT=new Set(["top","bottom"]);function HT(e){return qT.has(VT(e))?"y":"x"}function WT(e){return $T(HT(e))}function KT(e){return e.replace(/start|end/g,e=>BT[e])}const JT=["left","right"],QT=["right","left"],XT=["top","bottom"],YT=["bottom","top"];function ZT(e,t,r,i){const n=UT(e);let s=function(e,t,r){switch(e){case"top":case"bottom":return r?t?QT:JT:t?JT:QT;case"left":case"right":return t?XT:YT;default:return[]}}(VT(e),"start"===r,i);return n&&(s=s.map(e=>e+"-"+n),t&&(s=s.concat(s.map(KT)))),s}function eP(e){return e.replace(/left|right|bottom|top/g,e=>NT[e])}function tP(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function rP(e){const{x:t,y:r,width:i,height:n}=e;return{width:i,height:n,top:r,left:t,right:t+i,bottom:r+n,x:t,y:r}}function iP(e,t,r){let{reference:i,floating:n}=e;const s=HT(t),o=WT(t),a=GT(o),c=VT(t),d="y"===s,l=i.x+i.width/2-n.width/2,u=i.y+i.height/2-n.height/2,p=i[a]/2-n[a]/2;let h;switch(c){case"top":h={x:l,y:i.y-n.height};break;case"bottom":h={x:l,y:i.y+i.height};break;case"right":h={x:i.x+i.width,y:u};break;case"left":h={x:i.x-n.width,y:u};break;default:h={x:i.x,y:i.y}}switch(UT(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function nP(e,t){var r;void 0===t&&(t={});const{x:i,y:n,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=zT(t,e),f=tP(h),m=a[p?"floating"===u?"reference":"floating":u],g=rP(await s.getClippingRect({element:null==(r=await(null==s.isElement?void 0:s.isElement(m)))||r?m:m.contextElement||await(null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:d,rootBoundary:l,strategy:c})),v="floating"===u?{x:i,y:n,width:o.floating.width,height:o.floating.height}:o.reference,b=await(null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),y=await(null==s.isElement?void 0:s.isElement(b))&&await(null==s.getScale?void 0:s.getScale(b))||{x:1,y:1},w=rP(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:b,strategy:c}):v);return{top:(g.top-w.top+f.top)/y.y,bottom:(w.bottom-g.bottom+f.bottom)/y.y,left:(g.left-w.left+f.left)/y.x,right:(w.right-g.right+f.right)/y.x}}function sP(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function oP(e){return xT.some(t=>e[t]>=0)}const aP=new Set(["left","top"]);function cP(){return"undefined"!=typeof window}function dP(e){return pP(e)?(e.nodeName||"").toLowerCase():"#document"}function lP(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function uP(e){var t;return null==(t=(pP(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function pP(e){return!!cP()&&(e instanceof Node||e instanceof lP(e).Node)}function hP(e){return!!cP()&&(e instanceof Element||e instanceof lP(e).Element)}function fP(e){return!!cP()&&(e instanceof HTMLElement||e instanceof lP(e).HTMLElement)}function mP(e){return!(!cP()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof lP(e).ShadowRoot)}const gP=new Set(["inline","contents"]);function vP(e){const{overflow:t,overflowX:r,overflowY:i,display:n}=EP(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+r)&&!gP.has(n)}const bP=new Set(["table","td","th"]);function yP(e){return bP.has(dP(e))}const wP=[":popover-open",":modal"];function _P(e){return wP.some(t=>{try{return e.matches(t)}catch(e){return!1}})}const SP=["transform","translate","scale","rotate","perspective"],CP=["transform","translate","scale","rotate","perspective","filter"],RP=["paint","layout","strict","content"];function kP(e){const t=TP(),r=hP(e)?EP(e):e;return SP.some(e=>!!r[e]&&"none"!==r[e])||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||CP.some(e=>(r.willChange||"").includes(e))||RP.some(e=>(r.contain||"").includes(e))}function TP(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const PP=new Set(["html","body","#document"]);function OP(e){return PP.has(dP(e))}function EP(e){return lP(e).getComputedStyle(e)}function DP(e){return hP(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function xP(e){if("html"===dP(e))return e;const t=e.assignedSlot||e.parentNode||mP(e)&&e.host||uP(e);return mP(t)?t.host:t}function IP(e){const t=xP(e);return OP(t)?e.ownerDocument?e.ownerDocument.body:e.body:fP(t)&&vP(t)?t:IP(t)}function MP(e,t,r){var i;void 0===t&&(t=[]),void 0===r&&(r=!0);const n=IP(e),s=n===(null==(i=e.ownerDocument)?void 0:i.body),o=lP(n);if(s){const e=jP(o);return t.concat(o,o.visualViewport||[],vP(n)?n:[],e&&r?MP(e):[])}return t.concat(n,MP(n,[],r))}function jP(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function LP(e){const t=EP(e);let r=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const n=fP(e),s=n?e.offsetWidth:r,o=n?e.offsetHeight:i,a=jT(r)!==s||jT(i)!==o;return a&&(r=s,i=o),{width:r,height:i,$:a}}function AP(e){return hP(e)?e:e.contextElement}function NP(e){const t=AP(e);if(!fP(t))return AT(1);const r=t.getBoundingClientRect(),{width:i,height:n,$:s}=LP(t);let o=(s?jT(r.width):r.width)/i,a=(s?jT(r.height):r.height)/n;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const BP=AT(0);function FP(e){const t=lP(e);return TP()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:BP}function zP(e,t,r,i){void 0===t&&(t=!1),void 0===r&&(r=!1);const n=e.getBoundingClientRect(),s=AP(e);let o=AT(1);t&&(i?hP(i)&&(o=NP(i)):o=NP(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==lP(e))&&t}(s,r,i)?FP(s):AT(0);let c=(n.left+a.x)/o.x,d=(n.top+a.y)/o.y,l=n.width/o.x,u=n.height/o.y;if(s){const e=lP(s),t=i&&hP(i)?lP(i):i;let r=e,n=jP(r);for(;n&&i&&t!==r;){const e=NP(n),t=n.getBoundingClientRect(),i=EP(n),s=t.left+(n.clientLeft+parseFloat(i.paddingLeft))*e.x,o=t.top+(n.clientTop+parseFloat(i.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=lP(n),n=jP(r)}}return rP({width:l,height:u,x:c,y:d})}function VP(e,t){const r=DP(e).scrollLeft;return t?t.left+r:zP(uP(e)).left+r}function UP(e,t,r){void 0===r&&(r=!1);const i=e.getBoundingClientRect();return{x:i.left+t.scrollLeft-(r?0:VP(e,i)),y:i.top+t.scrollTop}}const $P=new Set(["absolute","fixed"]);function GP(e,t,r){let i;if("viewport"===t)i=function(e,t){const r=lP(e),i=uP(e),n=r.visualViewport;let s=i.clientWidth,o=i.clientHeight,a=0,c=0;if(n){s=n.width,o=n.height;const e=TP();(!e||e&&"fixed"===t)&&(a=n.offsetLeft,c=n.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)i=function(e){const t=uP(e),r=DP(e),i=e.ownerDocument.body,n=MT(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),s=MT(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let o=-r.scrollLeft+VP(e);const a=-r.scrollTop;return"rtl"===EP(i).direction&&(o+=MT(t.clientWidth,i.clientWidth)-n),{width:n,height:s,x:o,y:a}}(uP(e));else if(hP(t))i=function(e,t){const r=zP(e,!0,"fixed"===t),i=r.top+e.clientTop,n=r.left+e.clientLeft,s=fP(e)?NP(e):AT(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:n*s.x,y:i*s.y}}(t,r);else{const r=FP(e);i={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return rP(i)}function qP(e,t){const r=xP(e);return!(r===t||!hP(r)||OP(r))&&("fixed"===EP(r).position||qP(r,t))}function HP(e,t,r){const i=fP(t),n=uP(t),s="fixed"===r,o=zP(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=AT(0);function d(){c.x=VP(n)}if(i||!i&&!s)if(("body"!==dP(t)||vP(n))&&(a=DP(t)),i){const e=zP(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else n&&d();s&&!i&&n&&d();const l=!n||i||s?AT(0):UP(n,a);return{x:o.left+a.scrollLeft-c.x-l.x,y:o.top+a.scrollTop-c.y-l.y,width:o.width,height:o.height}}function WP(e){return"static"===EP(e).position}function KP(e,t){if(!fP(e)||"fixed"===EP(e).position)return null;if(t)return t(e);let r=e.offsetParent;return uP(e)===r&&(r=r.ownerDocument.body),r}function JP(e,t){const r=lP(e);if(_P(e))return r;if(!fP(e)){let t=xP(e);for(;t&&!OP(t);){if(hP(t)&&!WP(t))return t;t=xP(t)}return r}let i=KP(e,t);for(;i&&yP(i)&&WP(i);)i=KP(i,t);return i&&OP(i)&&WP(i)&&!kP(i)?r:i||function(e){let t=xP(e);for(;fP(t)&&!OP(t);){if(kP(t))return t;if(_P(t))return null;t=xP(t)}return null}(e)||r}const QP={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:i,strategy:n}=e;const s="fixed"===n,o=uP(i),a=!!t&&_P(t.floating);if(i===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=AT(1);const l=AT(0),u=fP(i);if((u||!u&&!s)&&(("body"!==dP(i)||vP(o))&&(c=DP(i)),fP(i))){const e=zP(i);d=NP(i),l.x=e.x+i.clientLeft,l.y=e.y+i.clientTop}const p=!o||u||s?AT(0):UP(o,c,!0);return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x+p.x,y:r.y*d.y-c.scrollTop*d.y+l.y+p.y}},getDocumentElement:uP,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:i,strategy:n}=e;const s="clippingAncestors"===r?_P(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let i=MP(e,[],!1).filter(e=>hP(e)&&"body"!==dP(e)),n=null;const s="fixed"===EP(e).position;let o=s?xP(e):e;for(;hP(o)&&!OP(o);){const t=EP(o),r=kP(o);r||"fixed"!==t.position||(n=null),(s?!r&&!n:!r&&"static"===t.position&&n&&$P.has(n.position)||vP(o)&&!r&&qP(e,o))?i=i.filter(e=>e!==o):n=t,o=xP(o)}return t.set(e,i),i}(t,this._c):[].concat(r),o=[...s,i],a=o[0],c=o.reduce((e,r)=>{const i=GP(t,r,n);return e.top=MT(i.top,e.top),e.right=IT(i.right,e.right),e.bottom=IT(i.bottom,e.bottom),e.left=MT(i.left,e.left),e},GP(t,a,n));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:JP,getElementRects:async function(e){const t=this.getOffsetParent||JP,r=this.getDimensions,i=await r(e.floating);return{reference:HP(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=LP(e);return{width:t,height:r}},getScale:NP,isElement:hP,isRTL:function(e){return"rtl"===EP(e).direction}};function XP(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function YP(e,t,r,i){void 0===i&&(i={});const{ancestorScroll:n=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=i,d=AP(e),l=n||s?[...d?MP(d):[],...MP(t)]:[];l.forEach(e=>{n&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)});const u=d&&a?function(e,t){let r,i=null;const n=uP(e);function s(){var e;clearTimeout(r),null==(e=i)||e.disconnect(),i=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const d=e.getBoundingClientRect(),{left:l,top:u,width:p,height:h}=d;if(a||t(),!p||!h)return;const f={rootMargin:-LT(u)+"px "+-LT(n.clientWidth-(l+p))+"px "+-LT(n.clientHeight-(u+h))+"px "+-LT(l)+"px",threshold:MT(0,IT(1,c))||1};let m=!0;function g(t){const i=t[0].intersectionRatio;if(i!==c){if(!m)return o();i?o(!1,i):r=setTimeout(()=>{o(!1,1e-7)},1e3)}1!==i||XP(d,e.getBoundingClientRect())||o(),m=!1}try{i=new IntersectionObserver(g,{...f,root:n.ownerDocument})}catch(e){i=new IntersectionObserver(g,f)}i.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver(e=>{let[i]=e;i&&i.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),r()}),d&&!c&&f.observe(d),f.observe(t));let m=c?zP(e):null;return c&&function t(){const i=zP(e);m&&!XP(m,i)&&r();m=i,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach(e=>{n&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)}),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const ZP=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,i;const{x:n,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:i,elements:n}=e,s=await(null==i.isRTL?void 0:i.isRTL(n.floating)),o=VT(r),a=UT(r),c="y"===HT(r),d=aP.has(o)?-1:1,l=s&&c?-1:1,u=zT(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*l,y:p*d}:{x:p*d,y:h*l}}(t,e);return o===(null==(r=a.offset)?void 0:r.placement)&&null!=(i=a.arrow)&&i.alignmentOffset?{}:{x:n+c.x,y:s+c.y,data:{...c,placement:o}}}}},eO=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:i,placement:n}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=zT(e,t),d={x:r,y:i},l=await nP(t,c),u=HT(VT(n)),p=$T(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=FT(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=FT(f+l["y"===u?"top":"left"],f,f-l[e])}const m=a.fn({...t,[p]:h,[u]:f});return{...m,data:{x:m.x-r,y:m.y-i,enabled:{[p]:s,[u]:o}}}}}},tO=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,i;const{placement:n,middlewareData:s,rects:o,initialPlacement:a,platform:c,elements:d}=t,{mainAxis:l=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:m=!0,...g}=zT(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=VT(n),b=HT(a),y=VT(a)===a,w=await(null==c.isRTL?void 0:c.isRTL(d.floating)),_=p||(y||!m?[eP(a)]:function(e){const t=eP(e);return[KT(e),t,KT(t)]}(a)),S="none"!==f;!p&&S&&_.push(...ZT(a,m,f,w));const C=[a,..._],R=await nP(t,g),k=[];let T=(null==(i=s.flip)?void 0:i.overflows)||[];if(l&&k.push(R[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const i=UT(e),n=WT(e),s=GT(n);let o="x"===n?i===(r?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=eP(o)),[o,eP(o)]}(n,o,w);k.push(R[e[0]],R[e[1]])}if(T=[...T,{placement:n,overflows:k}],!k.every(e=>e<=0)){var P,O;const e=((null==(P=s.flip)?void 0:P.index)||0)+1,t=C[e];if(t){if(!("alignment"===u&&b!==HT(t))||T.every(e=>e.overflows[0]>0&&HT(e.placement)===b))return{data:{index:e,overflows:T},reset:{placement:t}}}let r=null==(O=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:O.placement;if(!r)switch(h){case"bestFit":{var E;const e=null==(E=T.filter(e=>{if(S){const t=HT(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:E[0];e&&(r=e);break}case"initialPlacement":r=a}if(n!==r)return{reset:{placement:r}}}return{}}}},rO=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){var r,i;const{placement:n,rects:s,platform:o,elements:a}=t,{apply:c=()=>{},...d}=zT(e,t),l=await nP(t,d),u=VT(n),p=UT(n),h="y"===HT(n),{width:f,height:m}=s.floating;let g,v;"top"===u||"bottom"===u?(g=u,v=p===(await(null==o.isRTL?void 0:o.isRTL(a.floating))?"start":"end")?"left":"right"):(v=u,g="end"===p?"top":"bottom");const b=m-l.top-l.bottom,y=f-l.left-l.right,w=IT(m-l[g],b),_=IT(f-l[v],y),S=!t.middlewareData.shift;let C=w,R=_;if(null!=(r=t.middlewareData.shift)&&r.enabled.x&&(R=y),null!=(i=t.middlewareData.shift)&&i.enabled.y&&(C=b),S&&!p){const e=MT(l.left,0),t=MT(l.right,0),r=MT(l.top,0),i=MT(l.bottom,0);h?R=f-2*(0!==e||0!==t?e+t:MT(l.left,l.right)):C=m-2*(0!==r||0!==i?r+i:MT(l.top,l.bottom))}await c({...t,availableWidth:R,availableHeight:C});const k=await o.getDimensions(a.floating);return f!==k.width||m!==k.height?{reset:{rects:!0}}:{}}}},iO=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:i="referenceHidden",...n}=zT(e,t);switch(i){case"referenceHidden":{const e=sP(await nP(t,{...n,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:oP(e)}}}case"escaped":{const e=sP(await nP(t,{...n,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:oP(e)}}}default:return{}}}}},nO=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:i,placement:n,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=zT(e,t)||{};if(null==d)return{};const u=tP(l),p={x:r,y:i},h=WT(n),f=GT(h),m=await o.getDimensions(d),g="y"===h,v=g?"top":"left",b=g?"bottom":"right",y=g?"clientHeight":"clientWidth",w=s.reference[f]+s.reference[h]-p[h]-s.floating[f],_=p[h]-s.reference[h],S=await(null==o.getOffsetParent?void 0:o.getOffsetParent(d));let C=S?S[y]:0;C&&await(null==o.isElement?void 0:o.isElement(S))||(C=a.floating[y]||s.floating[f]);const R=w/2-_/2,k=C/2-m[f]/2-1,T=IT(u[v],k),P=IT(u[b],k),O=T,E=C-m[f]-P,D=C/2-m[f]/2+R,x=FT(O,D,E),I=!c.arrow&&null!=UT(n)&&D!==x&&s.reference[f]/2-(D<O?T:P)-m[f]/2<0,M=I?D<O?D-O:D-E:0;return{[h]:p[h]+M,data:{[h]:x,centerOffset:D-x-M,...I&&{alignmentOffset:M}},reset:I}}}),sO=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:i,placement:n,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=zT(e,t),l={x:r,y:i},u=HT(n),p=$T(u);let h=l[p],f=l[u];const m=zT(a,t),g="number"==typeof m?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(c){const e="y"===p?"height":"width",t=s.reference[p]-s.floating[e]+g.mainAxis,r=s.reference[p]+s.reference[e]-g.mainAxis;h<t?h=t:h>r&&(h=r)}if(d){var v,b;const e="y"===p?"width":"height",t=aP.has(VT(n)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),i=s.reference[u]+s.reference[e]+(t?0:(null==(b=o.offset)?void 0:b[u])||0)-(t?g.crossAxis:0);f<r?f=r:f>i&&(f=i)}return{[p]:h,[u]:f}}}},oO=(e,t,r)=>{const i=new Map,n={platform:QP,...r},s={...n.platform,_c:i};return(async(e,t,r)=>{const{placement:i="bottom",strategy:n="absolute",middleware:s=[],platform:o}=r,a=s.filter(Boolean),c=await(null==o.isRTL?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:n}),{x:l,y:u}=iP(d,i,c),p=i,h={},f=0;for(let r=0;r<a.length;r++){const{name:s,fn:m}=a[r],{x:g,y:v,data:b,reset:y}=await m({x:l,y:u,initialPlacement:i,placement:p,strategy:n,middlewareData:h,rects:d,platform:o,elements:{reference:e,floating:t}});l=null!=g?g:l,u=null!=v?v:u,h={...h,[s]:{...h[s],...b}},y&&f<=50&&(f++,"object"==typeof y&&(y.placement&&(p=y.placement),y.rects&&(d=!0===y.rects?await o.getElementRects({reference:e,floating:t,strategy:n}):y.rects),({x:l,y:u}=iP(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:n,middlewareData:h}})(e,t,{...n,platform:s})};var aO="undefined"!=typeof document?t.useLayoutEffect:function(){};function cO(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;let r,i,n;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(i=r;0!==i--;)if(!cO(e[i],t[i]))return!1;return!0}if(n=Object.keys(e),r=n.length,r!==Object.keys(t).length)return!1;for(i=r;0!==i--;)if(!{}.hasOwnProperty.call(t,n[i]))return!1;for(i=r;0!==i--;){const r=n[i];if(("_owner"!==r||!e.$$typeof)&&!cO(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function dO(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function lO(e,t){const r=dO(e);return Math.round(t*r)/r}function uO(e){const t=s.useRef(e);return aO(()=>{t.current=e}),t}const pO=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:i}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?nO({element:r.current,padding:i}).fn(t):{}:r?nO({element:r,padding:i}).fn(t):{}}}),hO=(e,t)=>({...ZP(e),options:[e,t]}),fO=(e,t)=>({...eO(e),options:[e,t]}),mO=(e,t)=>({...sO(e),options:[e,t]}),gO=(e,t)=>({...tO(e),options:[e,t]}),vO=(e,t)=>({...rO(e),options:[e,t]}),bO=(e,t)=>({...iO(e),options:[e,t]}),yO=(e,t)=>({...pO(e),options:[e,t]});var wO=s.forwardRef((e,t)=>{const{children:r,width:i=10,height:n=5,...s}=e;return Yk.jsx(sT.svg,{...s,ref:t,width:i,height:n,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?r:Yk.jsx("polygon",{points:"0,0 30,0 15,10"})})});wO.displayName="Arrow";var _O=wO;var SO="Popper",[CO,RO]=Zk(SO),[kO,TO]=CO(SO),PO=e=>{const{__scopePopper:t,children:r}=e,[i,n]=s.useState(null);return Yk.jsx(kO,{scope:t,anchor:i,onAnchorChange:n,children:r})};PO.displayName=SO;var OO="PopperAnchor",EO=s.forwardRef((e,t)=>{const{__scopePopper:r,virtualRef:i,...n}=e,o=TO(OO,r),a=s.useRef(null),c=Kk(t,a);return s.useEffect(()=>{o.onAnchorChange(i?.current||a.current)}),i?null:Yk.jsx(sT.div,{...n,ref:c})});EO.displayName=OO;var DO="PopperContent",[xO,IO]=CO(DO),MO=s.forwardRef((e,t)=>{const{__scopePopper:r,side:i="bottom",sideOffset:n=0,align:a="center",alignOffset:c=0,arrowPadding:d=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:h="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:g,...v}=e,b=TO(DO,r),[y,w]=s.useState(null),_=Kk(t,e=>w(e)),[S,C]=s.useState(null),R=function(e){const[t,r]=s.useState(void 0);return PT(()=>{if(e){r({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver(t=>{if(!Array.isArray(t))return;if(!t.length)return;const i=t[0];let n,s;if("borderBoxSize"in i){const e=i.borderBoxSize,t=Array.isArray(e)?e[0]:e;n=t.inlineSize,s=t.blockSize}else n=e.offsetWidth,s=e.offsetHeight;r({width:n,height:s})});return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}r(void 0)},[e]),t}(S),k=R?.width??0,T=R?.height??0,P=i+("center"!==a?"-"+a:""),O="number"==typeof p?p:{top:0,right:0,bottom:0,left:0,...p},E=Array.isArray(u)?u:[u],D=E.length>0,x={padding:O,boundary:E.filter(NO),altBoundary:D},{refs:I,floatingStyles:M,placement:j,isPositioned:L,middlewareData:A}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:i=[],platform:n,elements:{reference:a,floating:c}={},transform:d=!0,whileElementsMounted:l,open:u}=e,[p,h]=s.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=s.useState(i);cO(f,i)||m(i);const[g,v]=s.useState(null),[b,y]=s.useState(null),w=s.useCallback(e=>{e!==R.current&&(R.current=e,v(e))},[]),_=s.useCallback(e=>{e!==k.current&&(k.current=e,y(e))},[]),S=a||g,C=c||b,R=s.useRef(null),k=s.useRef(null),T=s.useRef(p),P=null!=l,O=uO(l),E=uO(n),D=uO(u),x=s.useCallback(()=>{if(!R.current||!k.current)return;const e={placement:t,strategy:r,middleware:f};E.current&&(e.platform=E.current),oO(R.current,k.current,e).then(e=>{const t={...e,isPositioned:!1!==D.current};I.current&&!cO(T.current,t)&&(T.current=t,o.flushSync(()=>{h(t)}))})},[f,t,r,E,D]);aO(()=>{!1===u&&T.current.isPositioned&&(T.current.isPositioned=!1,h(e=>({...e,isPositioned:!1})))},[u]);const I=s.useRef(!1);aO(()=>(I.current=!0,()=>{I.current=!1}),[]),aO(()=>{if(S&&(R.current=S),C&&(k.current=C),S&&C){if(O.current)return O.current(S,C,x);x()}},[S,C,x,O,P]);const M=s.useMemo(()=>({reference:R,floating:k,setReference:w,setFloating:_}),[w,_]),j=s.useMemo(()=>({reference:S,floating:C}),[S,C]),L=s.useMemo(()=>{const e={position:r,left:0,top:0};if(!j.floating)return e;const t=lO(j.floating,p.x),i=lO(j.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+i+"px)",...dO(j.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:i}},[r,d,j.floating,p.x,p.y]);return s.useMemo(()=>({...p,update:x,refs:M,elements:j,floatingStyles:L}),[p,x,M,j,L])}({strategy:"fixed",placement:P,whileElementsMounted:(...e)=>YP(...e,{animationFrame:"always"===m}),elements:{reference:b.anchor},middleware:[hO({mainAxis:n+T,alignmentAxis:c}),l&&fO({mainAxis:!0,crossAxis:!1,limiter:"partial"===h?mO():void 0,...x}),l&&gO({...x}),vO({...x,apply:({elements:e,rects:t,availableWidth:r,availableHeight:i})=>{const{width:n,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${i}px`),o.setProperty("--radix-popper-anchor-width",`${n}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),S&&yO({element:S,padding:d}),BO({arrowWidth:k,arrowHeight:T}),f&&bO({strategy:"referenceHidden",...x})]}),[N,B]=FO(j),F=oT(g);PT(()=>{L&&F?.()},[L,F]);const z=A.arrow?.x,V=A.arrow?.y,U=0!==A.arrow?.centerOffset,[$,G]=s.useState();return PT(()=>{y&&G(window.getComputedStyle(y).zIndex)},[y]),Yk.jsx("div",{ref:I.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:L?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:$,"--radix-popper-transform-origin":[A.transformOrigin?.x,A.transformOrigin?.y].join(" "),...A.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:Yk.jsx(xO,{scope:r,placedSide:N,onArrowChange:C,arrowX:z,arrowY:V,shouldHideArrow:U,children:Yk.jsx(sT.div,{"data-side":N,"data-align":B,...v,ref:_,style:{...v.style,animation:L?void 0:"none"}})})})});MO.displayName=DO;var jO="PopperArrow",LO={top:"bottom",right:"left",bottom:"top",left:"right"},AO=s.forwardRef(function(e,t){const{__scopePopper:r,...i}=e,n=IO(jO,r),s=LO[n.placedSide];return Yk.jsx("span",{ref:n.onArrowChange,style:{position:"absolute",left:n.arrowX,top:n.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[n.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[n.placedSide],visibility:n.shouldHideArrow?"hidden":void 0},children:Yk.jsx(_O,{...i,ref:t,style:{...i.style,display:"block"}})})});function NO(e){return null!==e}AO.displayName=jO;var BO=e=>({name:"transformOrigin",options:e,fn(t){const{placement:r,rects:i,middlewareData:n}=t,s=0!==n.arrow?.centerOffset,o=s?0:e.arrowWidth,a=s?0:e.arrowHeight,[c,d]=FO(r),l={start:"0%",center:"50%",end:"100%"}[d],u=(n.arrow?.x??0)+o/2,p=(n.arrow?.y??0)+a/2;let h="",f="";return"bottom"===c?(h=s?l:`${u}px`,f=-a+"px"):"top"===c?(h=s?l:`${u}px`,f=`${i.floating.height+a}px`):"right"===c?(h=-a+"px",f=s?l:`${p}px`):"left"===c&&(h=`${i.floating.width+a}px`,f=s?l:`${p}px`),{data:{x:h,y:f}}}});function FO(e){const[t,r="center"]=e.split("-");return[t,r]}var zO=PO,VO=EO,UO=MO,$O=AO,GO=s.forwardRef((e,t)=>{const{container:i,...n}=e,[o,a]=s.useState(!1);PT(()=>a(!0),[]);const c=i||o&&globalThis?.document?.body;return c?r.createPortal(Yk.jsx(sT.div,{...n,ref:t}),c):null});GO.displayName="Portal";var qO=e=>{const{present:t,children:r}=e,i=function(e){const[t,r]=s.useState(),i=s.useRef(null),n=s.useRef(e),o=s.useRef("none"),a=e?"mounted":"unmounted",[c,d]=function(e,t){return s.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return s.useEffect(()=>{const e=HO(i.current);o.current="mounted"===c?e:"none"},[c]),PT(()=>{const t=i.current,r=n.current;if(r!==e){const i=o.current,s=HO(t);if(e)d("MOUNT");else if("none"===s||"none"===t?.display)d("UNMOUNT");else{d(r&&i!==s?"ANIMATION_OUT":"UNMOUNT")}n.current=e}},[e,d]),PT(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,s=s=>{const o=HO(i.current).includes(s.animationName);if(s.target===t&&o&&(d("ANIMATION_END"),!n.current)){const i=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=i)})}},a=e=>{e.target===t&&(o.current=HO(i.current))};return t.addEventListener("animationstart",a),t.addEventListener("animationcancel",s),t.addEventListener("animationend",s),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",a),t.removeEventListener("animationcancel",s),t.removeEventListener("animationend",s)}}d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:s.useCallback(e=>{i.current=e?getComputedStyle(e):null,r(e)},[])}}(t),n="function"==typeof r?r({present:i.isPresent}):s.Children.only(r),o=Kk(i.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(n));return"function"==typeof r||i.isPresent?s.cloneElement(n,{ref:o}):null};function HO(e){return e?.animationName||"none"}qO.displayName="Presence";var WO=s[" useInsertionEffect ".trim().toString()]||PT;function KO({prop:e,defaultProp:t,onChange:r=()=>{},caller:i}){const[n,o,a]=function({defaultProp:e,onChange:t}){const[r,i]=s.useState(e),n=s.useRef(r),o=s.useRef(t);return WO(()=>{o.current=t},[t]),s.useEffect(()=>{n.current!==r&&(o.current?.(r),n.current=r)},[r,n]),[r,i,o]}({defaultProp:t,onChange:r}),c=void 0!==e,d=c?e:n;{const t=s.useRef(void 0!==e);s.useEffect(()=>{const e=t.current;if(e!==c){const t=e?"controlled":"uncontrolled",r=c?"controlled":"uncontrolled";console.warn(`${i} is changing from ${t} to ${r}. 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.`)}t.current=c},[c,i])}const l=s.useCallback(t=>{if(c){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else o(t)},[c,e,o,a]);return[d,l]}var JO=new WeakMap,QO=new WeakMap,XO={},YO=0,ZO=function(e){return e&&(e.host||ZO(e.parentNode))},eE=function(e,t,r,i){var n=function(e,t){return t.map(function(t){if(e.contains(t))return t;var r=ZO(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(e){return Boolean(e)})}(t,Array.isArray(e)?e:[e]);XO[r]||(XO[r]=new WeakMap);var s=XO[r],o=[],a=new Set,c=new Set(n),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};n.forEach(d);var l=function(e){e&&!c.has(e)&&Array.prototype.forEach.call(e.children,function(e){if(a.has(e))l(e);else try{var t=e.getAttribute(i),n=null!==t&&"false"!==t,c=(JO.get(e)||0)+1,d=(s.get(e)||0)+1;JO.set(e,c),s.set(e,d),o.push(e),1===c&&n&&QO.set(e,!0),1===d&&e.setAttribute(r,"true"),n||e.setAttribute(i,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}})};return l(t),a.clear(),YO++,function(){o.forEach(function(e){var t=JO.get(e)-1,n=s.get(e)-1;JO.set(e,t),s.set(e,n),t||(QO.has(e)||e.removeAttribute(i),QO.delete(e)),n||e.removeAttribute(r)}),--YO||(JO=new WeakMap,JO=new WeakMap,QO=new WeakMap,XO={})}},tE=function(e,t,r){void 0===r&&(r="data-aria-hidden");var i=Array.from(Array.isArray(e)?e:[e]),n=function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return n?(i.push.apply(i,Array.from(n.querySelectorAll("[aria-live], script"))),eE(i,n,r,"aria-hidden")):function(){return null}},rE="right-scroll-bar-position",iE="width-before-scroll-bar";function nE(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var sE="undefined"!=typeof window?s.useLayoutEffect:s.useEffect,oE=new WeakMap;function aE(e,r){var i,n,s,o=(i=null,n=function(t){return e.forEach(function(e){return nE(e,t)})},s=t.useState(function(){return{value:i,callback:n,facade:{get current(){return s.value},set current(e){var t=s.value;t!==e&&(s.value=e,s.callback(e,t))}}}})[0],s.callback=n,s.facade);return sE(function(){var t=oE.get(o);if(t){var r=new Set(t),i=new Set(e),n=o.current;r.forEach(function(e){i.has(e)||nE(e,null)}),i.forEach(function(e){r.has(e)||nE(e,n)})}oE.set(o,e)},[e]),o}function cE(e){return e}var dE=function(e){var t=e.sideCar,r=MR(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var i=t.read();if(!i)throw new Error("Sidecar medium not found");return s.createElement(i,IR({},r))};dE.isSideCarExport=!0;var lE=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=cE);var r=[],i=!1;return{read:function(){if(i)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var n=t(e,i);return r.push(n),function(){r=r.filter(function(e){return e!==n})}},assignSyncMedium:function(e){for(i=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){i=!0;var t=[];if(r.length){var n=r;r=[],n.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},o=function(){return Promise.resolve().then(s)};o(),r={push:function(e){t.push(e),o()},filter:function(e){return t=t.filter(e),r}}}}}(null);return t.options=IR({async:!0,ssr:!1},e),t}(),uE=function(){},pE=s.forwardRef(function(e,t){var r=s.useRef(null),i=s.useState({onScrollCapture:uE,onWheelCapture:uE,onTouchMoveCapture:uE}),n=i[0],o=i[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noRelative,m=e.noIsolation,g=e.inert,v=e.allowPinchZoom,b=e.as,y=void 0===b?"div":b,w=e.gapMode,_=MR(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,C=aE([r,t]),R=IR(IR({},_),n);return s.createElement(s.Fragment,null,u&&s.createElement(S,{sideCar:lE,removeScrollBar:l,shards:p,noRelative:f,noIsolation:m,inert:g,setCallbacks:o,allowPinchZoom:!!v,lockRef:r,gapMode:w}),a?s.cloneElement(s.Children.only(c),IR(IR({},R),{ref:C})):s.createElement(y,IR({},R,{className:d,ref:C}),c))});pE.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},pE.classNames={fullWidth:iE,zeroRight:rE};function hE(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var fE=function(){var e=0,t=null;return{add:function(r){var i,n;0==e&&(t=hE())&&(n=r,(i=t).styleSheet?i.styleSheet.cssText=n:i.appendChild(document.createTextNode(n)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},mE=function(){var e,t=(e=fE(),function(t,r){s.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])});return function(e){var r=e.styles,i=e.dynamic;return t(r,i),null}},gE={left:0,top:0,right:0,gap:0},vE=function(e){return parseInt(e||"",10)||0},bE=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return gE;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],i=t["padding"===e?"paddingTop":"marginTop"],n=t["padding"===e?"paddingRight":"marginRight"];return[vE(r),vE(i),vE(n)]}(e),r=document.documentElement.clientWidth,i=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,i-r+t[2]-t[0])}},yE=mE(),wE="data-scroll-locked",_E=function(e,t,r,i){var n=e.left,s=e.top,o=e.right,a=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(i,";\n padding-right: ").concat(a,"px ").concat(i,";\n }\n body[").concat(wE,"] {\n overflow: hidden ").concat(i,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(i,";"),"margin"===r&&"\n padding-left: ".concat(n,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(o,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(a,"px ").concat(i,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(i,";")].filter(Boolean).join(""),"\n }\n \n .").concat(rE," {\n right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(iE," {\n margin-right: ").concat(a,"px ").concat(i,";\n }\n \n .").concat(rE," .").concat(rE," {\n right: 0 ").concat(i,";\n }\n \n .").concat(iE," .").concat(iE," {\n margin-right: 0 ").concat(i,";\n }\n \n body[").concat(wE,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},SE=function(){var e=parseInt(document.body.getAttribute(wE)||"0",10);return isFinite(e)?e:0},CE=function(e){var t=e.noRelative,r=e.noImportant,i=e.gapMode,n=void 0===i?"margin":i;s.useEffect(function(){return document.body.setAttribute(wE,(SE()+1).toString()),function(){var e=SE()-1;e<=0?document.body.removeAttribute(wE):document.body.setAttribute(wE,e.toString())}},[]);var o=s.useMemo(function(){return bE(n)},[n]);return s.createElement(yE,{styles:_E(o,!t,n,r?"":"!important")})},RE=!1;if("undefined"!=typeof window)try{var kE=Object.defineProperty({},"passive",{get:function(){return RE=!0,!0}});window.addEventListener("test",kE,kE),window.removeEventListener("test",kE,kE)}catch(AD){RE=!1}var TE=!!RE&&{passive:!1},PE=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},OE=function(e,t){var r=t.ownerDocument,i=t;do{if("undefined"!=typeof ShadowRoot&&i instanceof ShadowRoot&&(i=i.host),EE(e,i)){var n=DE(e,i);if(n[1]>n[2])return!0}i=i.parentNode}while(i&&i!==r.body);return!1},EE=function(e,t){return"v"===e?function(e){return PE(e,"overflowY")}(t):function(e){return PE(e,"overflowX")}(t)},DE=function(e,t){return"v"===e?function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]}(t):function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t)},xE=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},IE=function(e){return[e.deltaX,e.deltaY]},ME=function(e){return e&&"current"in e?e.current:e},jE=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},LE=0,AE=[];function NE(e){for(var t=null;null!==e;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var BE,FE=(BE=function(e){var t=s.useRef([]),r=s.useRef([0,0]),i=s.useRef(),n=s.useState(LE++)[0],o=s.useState(mE)[0],a=s.useRef(e);s.useEffect(function(){a.current=e},[e]),s.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(n));var t=function(e,t,r){if(r||2===arguments.length)for(var i,n=0,s=t.length;n<s;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(ME),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add("allow-interactivity-".concat(n))}),function(){document.body.classList.remove("block-interactivity-".concat(n)),t.forEach(function(e){return e.classList.remove("allow-interactivity-".concat(n))})}}},[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback(function(e,t){if("touches"in e&&2===e.touches.length||"wheel"===e.type&&e.ctrlKey)return!a.current.allowPinchZoom;var n,s=xE(e),o=r.current,c="deltaX"in e?e.deltaX:o[0]-s[0],d="deltaY"in e?e.deltaY:o[1]-s[1],l=e.target,u=Math.abs(c)>Math.abs(d)?"h":"v";if("touches"in e&&"h"===u&&"range"===l.type)return!1;var p=OE(u,l);if(!p)return!0;if(p?n=u:(n="v"===u?"h":"v",p=OE(u,l)),!p)return!1;if(!i.current&&"changedTouches"in e&&(c||d)&&(i.current=n),!n)return!0;var h=i.current||n;return function(e,t,r,i){var n=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),s=n*i,o=r.target,a=t.contains(o),c=!1,d=s>0,l=0,u=0;do{if(!o)break;var p=DE(e,o),h=p[0],f=p[1]-p[2]-n*h;(h||f)&&EE(e,o)&&(l+=f,u+=h);var m=o.parentNode;o=m&&m.nodeType===Node.DOCUMENT_FRAGMENT_NODE?m.host:m}while(!a&&o!==document.body||a&&(t.contains(o)||t===o));return(d&&Math.abs(l)<1||!d&&Math.abs(u)<1)&&(c=!0),c}(h,t,e,"h"===h?c:d)},[]),d=s.useCallback(function(e){var r=e;if(AE.length&&AE[AE.length-1]===o){var i="deltaY"in r?IE(r):xE(r),n=t.current.filter(function(e){return e.name===r.type&&(e.target===r.target||r.target===e.shadowParent)&&(t=e.delta,n=i,t[0]===n[0]&&t[1]===n[1]);var t,n})[0];if(n&&n.should)r.cancelable&&r.preventDefault();else if(!n){var s=(a.current.shards||[]).map(ME).filter(Boolean).filter(function(e){return e.contains(r.target)});(s.length>0?c(r,s[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}},[]),l=s.useCallback(function(e,r,i,n){var s={name:e,delta:r,target:i,should:n,shadowParent:NE(i)};t.current.push(s),setTimeout(function(){t.current=t.current.filter(function(e){return e!==s})},1)},[]),u=s.useCallback(function(e){r.current=xE(e),i.current=void 0},[]),p=s.useCallback(function(t){l(t.type,IE(t),t.target,c(t,e.lockRef.current))},[]),h=s.useCallback(function(t){l(t.type,xE(t),t.target,c(t,e.lockRef.current))},[]);s.useEffect(function(){return AE.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,TE),document.addEventListener("touchmove",d,TE),document.addEventListener("touchstart",u,TE),function(){AE=AE.filter(function(e){return e!==o}),document.removeEventListener("wheel",d,TE),document.removeEventListener("touchmove",d,TE),document.removeEventListener("touchstart",u,TE)}},[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:jE(n)}):null,f?s.createElement(CE,{noRelative:e.noRelative,gapMode:e.gapMode}):null)},lE.useMedium(BE),dE),zE=s.forwardRef(function(e,t){return s.createElement(pE,IR({},e,{ref:t,sideCar:FE}))});zE.classNames=pE.classNames;var VE="Popover",[UE,$E]=Zk(VE,[RO]),GE=RO(),[qE,HE]=UE(VE),WE=e=>{const{__scopePopover:t,children:r,open:i,defaultOpen:n,onOpenChange:o,modal:a=!1}=e,c=GE(t),d=s.useRef(null),[l,u]=s.useState(!1),[p,h]=KO({prop:i,defaultProp:n??!1,onChange:o,caller:VE});return Yk.jsx(zO,{...c,children:Yk.jsx(qE,{scope:t,contentId:DT(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:s.useCallback(()=>h(e=>!e),[h]),hasCustomAnchor:l,onCustomAnchorAdd:s.useCallback(()=>u(!0),[]),onCustomAnchorRemove:s.useCallback(()=>u(!1),[]),modal:a,children:r})})};WE.displayName=VE;var KE="PopoverAnchor";s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=HE(KE,r),o=GE(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:c}=n;return s.useEffect(()=>(a(),()=>c()),[a,c]),Yk.jsx(VO,{...o,...i,ref:t})}).displayName=KE;var JE="PopoverTrigger",QE=s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=HE(JE,r),s=GE(r),o=Kk(t,n.triggerRef),a=Yk.jsx(sT.button,{type:"button","aria-haspopup":"dialog","aria-expanded":n.open,"aria-controls":n.contentId,"data-state":cD(n.open),...i,ref:o,onClick:qk(e.onClick,n.onOpenToggle)});return n.hasCustomAnchor?a:Yk.jsx(VO,{asChild:!0,...s,children:a})});QE.displayName=JE;var XE="PopoverPortal",[YE,ZE]=UE(XE,{forceMount:void 0}),eD=e=>{const{__scopePopover:t,forceMount:r,children:i,container:n}=e,s=HE(XE,t);return Yk.jsx(YE,{scope:t,forceMount:r,children:Yk.jsx(qO,{present:r||s.open,children:Yk.jsx(GO,{asChild:!0,container:n,children:i})})})};eD.displayName=XE;var tD="PopoverContent",rD=s.forwardRef((e,t)=>{const r=ZE(tD,e.__scopePopover),{forceMount:i=r.forceMount,...n}=e,s=HE(tD,e.__scopePopover);return Yk.jsx(qO,{present:i||s.open,children:s.modal?Yk.jsx(nD,{...n,ref:t}):Yk.jsx(sD,{...n,ref:t})})});rD.displayName=tD;var iD=tT("PopoverContent.RemoveScroll"),nD=s.forwardRef((e,t)=>{const r=HE(tD,e.__scopePopover),i=s.useRef(null),n=Kk(t,i),o=s.useRef(!1);return s.useEffect(()=>{const e=i.current;if(e)return tE(e)},[]),Yk.jsx(zE,{as:iD,allowPinchZoom:!0,children:Yk.jsx(oD,{...e,ref:n,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:qk(e.onCloseAutoFocus,e=>{e.preventDefault(),o.current||r.triggerRef.current?.focus()}),onPointerDownOutside:qk(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,i=2===t.button||r;o.current=i},{checkForDefaultPrevented:!1}),onFocusOutside:qk(e.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1})})})}),sD=s.forwardRef((e,t)=>{const r=HE(tD,e.__scopePopover),i=s.useRef(!1),n=s.useRef(!1);return Yk.jsx(oD,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(i.current||r.triggerRef.current?.focus(),t.preventDefault()),i.current=!1,n.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(i.current=!0,"pointerdown"===t.detail.originalEvent.type&&(n.current=!0));const s=t.target,o=r.triggerRef.current?.contains(s);o&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&n.current&&t.preventDefault()}})}),oD=s.forwardRef((e,t)=>{const{__scopePopover:r,trapFocus:i,onOpenAutoFocus:n,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=HE(tD,r),f=GE(r);return s.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??gT()),document.body.insertAdjacentElement("beforeend",e[1]??gT()),mT++,()=>{1===mT&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),mT--}},[]),Yk.jsx(wT,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:n,onUnmountAutoFocus:o,children:Yk.jsx(pT,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1),children:Yk.jsx(UO,{"data-state":cD(h.open),role:"dialog",id:h.contentId,...f,...p,ref:t,style:{...p.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)"}})})})}),aD="PopoverClose";s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=HE(aD,r);return Yk.jsx(sT.button,{type:"button",...i,ref:t,onClick:qk(e.onClick,()=>n.onOpenChange(!1))})}).displayName=aD;function cD(e){return e?"open":"closed"}s.forwardRef((e,t)=>{const{__scopePopover:r,...i}=e,n=GE(r);return Yk.jsx($O,{...n,...i,ref:t})}).displayName="PopoverArrow";var dD=eD,lD=rD;const uD=WE,pD=QE,hD=s.forwardRef((e,t)=>{var{style:r,align:i="center",sideOffset:n=4}=e,o=MR(e,["style","align","sideOffset"]);return s.createElement(dD,null,s.createElement(lD,Object.assign({ref:t,align:i,sideOffset:n,style:Object.assign({width:"200px",backgroundColor:"#fff",border:"1px solid #e5e5e5",borderRadius:"0.375rem",boxShadow:"0 1px 2px 0 rgb(0 0 0 / 0.05)",color:"#333",fontSize:"14px",lineHeight:"1.5",padding:"16px",zIndex:50,outline:"none"},r)},o)))});hD.displayName=lD.displayName;const fD=s.createContext({}),mD=s.createContext({}),gD=()=>{const e=s.useContext(fD),t=s.useContext(mD);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},vD=s.createContext({}),bD=e=>{const{children:t}=e,r=MR(e,["children"]),[i,n]=s.useState(!1);return s.createElement(vD.Provider,{value:{open:i,setOpen:n}},s.createElement(uD,Object.assign({},r,{open:i,onOpenChange:n}),t))},yD=s.forwardRef((e,t)=>{var{children:r,style:i}=e,n=MR(e,["children","style"]);return s.createElement(hD,Object.assign({ref:t,style:Object.assign({display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minWidth:"180px",maxWidth:"300px",maxHeight:"100vh",overflowY:"auto",padding:0},i)},n),r)});yD.displayName="ParticipantMenuContent";const wD=s.forwardRef((e,t)=>{var{children:r,style:i}=e,n=MR(e,["children","style"]);return s.createElement(pD,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},i)},n),r)});wD.displayName=pD.displayName;const _D=s.forwardRef((e,t)=>{var{children:r,style:i,participantAction:n}=e,o=MR(e,["children","style","participantAction"]);const{participant:a,setOpen:c,maximizedParticipant:d,setMaximizedParticipant:l,setFloatingParticipant:u,floatingParticipant:p}=(()=>{const e=s.useContext(vD),t=gD();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),h=jR(),f=LR(MS).find(e=>e.id===a.id),m=(null==d?void 0:d.id)===a.id,g=(null==p?void 0:p.id)===a.id;let v;switch(n){case"maximize":v=()=>{l(m?null:a),c(!1)};break;case"spotlight":v=()=>{h(f?xS({id:a.id}):DS({id:a.id})),c(!1)};break;case"float":v=()=>{u(g?null:a),c(!1)}}return s.createElement("button",Object.assign({ref:t,role:"menuitem",tabIndex:-1,onClick:null!=v?v:o.onClick,style:Object.assign({alignItems:"stretch",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",height:"40px",lineHeight:"40px",minWidth:"140px",padding:"0 12px",textAlign:"left",textDecoration:"none",whiteSpace:"nowrap",width:"100%"},i)},o),r)});function SD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("g",null,s.createElement("circle",{cx:"6",cy:"12",r:"2"}),s.createElement("circle",{cx:"12",cy:"12",r:"2"}),s.createElement("circle",{cx:"18",cy:"12",r:"2"})))}function CD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m13.875 3c0 .62132.5037 1.125 1.125 1.125h3.284l-4.0795 4.0795c-.4393.43934-.4393 1.15166 0 1.591.4393.4393 1.1517.4393 1.591 0l4.0795-4.07951v3.28401c0 .62132.5037 1.125 1.125 1.125s1.125-.50368 1.125-1.125v-6c0-.15254-.0304-.29799-.0854-.43063-.0536-.12968-.1326-.25135-.2368-.35749l-.0147-.01469c-.203-.19928-.4812-.32219-.7881-.32219h-6c-.6213 0-1.125.50368-1.125 1.125zm-9.75 12c0-.6213-.50368-1.125-1.125-1.125s-1.125.5037-1.125 1.125v6c0 .3069.12291.5851.32219.7881.00486.005.00975.0099.01469.0147.10614.1042.22781.1832.35749.2368.13264.055.27809.0854.43063.0854h6c.62132 0 1.125-.5037 1.125-1.125s-.50368-1.125-1.125-1.125h-3.28401l4.07951-4.0795c.4393-.4393.4393-1.1517 0-1.591-.43934-.4393-1.15166-.4393-1.591 0l-4.0795 4.0795z"}))}function RD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m15.241.146691c-.1011-.1955882-.3809-.1955879-.482 0l-1.1063 2.139639c-.0258.04991-.0665.09058-.1164.11639l-2.1396 1.10629c-.1956.10113-.1956.38085 0 .48198l2.1396 1.10629c.0499.02581.0906.06648.1164.11639l1.1063 2.13964c.1011.19559.3809.19559.482 0l1.1063-2.13964c.0258-.04991.0665-.09058.1164-.11639l2.1396-1.10629c.1956-.10113.1956-.38085 0-.48198l-2.1396-1.10629c-.0499-.02581-.0906-.06648-.1164-.11639zm-13.741 2.900259v14.67495c0 .0511.00116.1018.00345.1523-.00229.0418-.00345.0837-.00345.1258 0 .5674.21005 1.1103.59339 1.6103.24265.3472.55042.6455.90566.8773 1.61225 1.213 4.36988 2.0124 7.50095 2.0124 4.3315 0 7.9484-1.53 8.8068-3.5681.0651-.1472.1148-.3024.1455-.4658.0315-.1532.0477-.3087.0477-.4661 0-.6032-.2374-1.1788-.668-1.7045-.1377-.1975-.2995-.4017-.4877-.6127l-14.22219-13.74809c-.28845-.27884-.67396-.43471-1.07516-.43471-.85436 0-1.54695.69259-1.54695 1.54695zm19.2646 4.59631c.0988-.19101.372-.19101.4708 0l.8546 1.65303c.0253.04874.065.08846.1137.11366l1.653.85465c.1911.0988.1911.372 0 .4708l-1.653.8546c-.0487.0253-.0884.065-.1137.1137l-.8546 1.653c-.0988.1911-.372.1911-.4708 0l-.8546-1.653c-.0253-.0487-.065-.0884-.1137-.1137l-1.653-.8546c-.1911-.0988-.1911-.372 0-.4708l1.653-.85465c.0487-.0252.0884-.06492.1137-.11366zm-3.2651 10.35684c0 .0769-.1144.6851-1.5305 1.3931-1.2964.6482-3.2274 1.1069-5.4695 1.1069s-4.17308-.4587-5.46952-1.1069c-1.41607-.708-1.53047-1.3162-1.53047-1.3931 0-.077.1144-.6851 1.53047-1.3932 1.29644-.6482 3.22742-1.1068 5.46952-1.1068s4.1731.4586 5.4695 1.1068c1.4161.7081 1.5305 1.3162 1.5305 1.3932z"}))}function kD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm1.875 19.5c0-.6213.5037-1.125 1.125-1.125h3.284l-5.5795-5.5795c-.4393-.4393-.4393-1.1517 0-1.591s1.1517-.4393 1.591 0l5.5795 5.5795v-3.284c0-.6213.5037-1.125 1.125-1.125s1.125.5037 1.125 1.125v6c0 .308-.1238.5872-.3244.7903-.0033.0034-.0067.0068-.0101.0102-.1067.1054-.2292.1851-.3599.2391-.1326.055-.2781.0854-.4306.0854h-6c-.6213 0-1.125-.5037-1.125-1.125z"}))}function TD(e){return s.createElement("svg",Object.assign({width:"100%",height:"100%",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},e),s.createElement("path",{clipRule:"evenodd",fillRule:"evenodd",d:"m2.25 3v4.5c0 .41421.33579.75.75.75h4.5c.41421 0 .75-.33579.75-.75v-4.5c0-.41421-.33579-.75-.75-.75h-4.5c-.41421 0-.75.33579-.75.75zm-2.25 4.5v-4.5c0-1.65685 1.34315-3 3-3h4.5c1.65685 0 3 1.34315 3 3v4.5c0 1.65685-1.34315 3-3 3h-4.5c-1.65685 0-3-1.34315-3-3zm2.25 9v4.5c0 .4142.33579.75.75.75h4.5c.41421 0 .75-.3358.75-.75v-4.5c0-.4142-.33579-.75-.75-.75h-4.5c-.41421 0-.75.3358-.75.75zm-2.25 4.5v-4.5c0-1.6569 1.34315-3 3-3h4.5c1.65685 0 3 1.3431 3 3v4.5c0 1.6569-1.34315 3-3 3h-4.5c-1.65685 0-3-1.3431-3-3zm15.75-13.5v-4.5c0-.41421.3358-.75.75-.75h4.5c.4142 0 .75.33579.75.75v4.5c0 .41421-.3358.75-.75.75h-4.5c-.4142 0-.75-.33579-.75-.75zm-2.25-4.5v4.5c0 1.65685 1.3431 3 3 3h4.5c1.6569 0 3-1.34315 3-3v-4.5c0-1.65685-1.3431-3-3-3h-4.5c-1.6569 0-3 1.34315-3 3zm8.625 12c0 .6213-.5037 1.125-1.125 1.125h-3.284l5.5795 5.5795c.4393.4393.4393 1.1517 0 1.591s-1.1517.4393-1.591 0l-5.5795-5.5795v3.284c0 .6213-.5037 1.125-1.125 1.125s-1.125-.5037-1.125-1.125v-6c0-.3081.1238-.5872.3244-.7904.0034-.0034.0068-.0068.0102-.0102.1067-.1053.2292-.185.3598-.239.1326-.055.2781-.0854.4306-.0854h6c.6213 0 1.125.5037 1.125 1.125z"}))}function PD({participant:e}){const t=LR(MS).find(t=>t.id===e.id),{isHovered:r,maximizedParticipant:i,floatingParticipant:n}=gD(),o=(null==i?void 0:i.id)===e.id,a=(null==n?void 0:n.id)===e.id;return r?s.createElement(bD,null,s.createElement(wD,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(SD,{height:20,width:20,transform:"rotate(90)"})),s.createElement(yD,null,e.isLocalClient?s.createElement(_D,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},a?s.createElement(s.Fragment,null,s.createElement(TD,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(kD,{height:16,width:16}),"Pop out")):null,s.createElement(_D,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(CD,{height:16,width:16}),o?"Minimize":"Maximize"),s.createElement(_D,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(RD,{height:16,width:16}),t?"Remove spotlight":"Spotlight"))):null}_D.displayName="ParticipantMenuItem";const OD=s.forwardRef(({className:e,participant:t,children:r},i)=>{const[n,o]=s.useState(!1),a=s.useCallback(()=>{o(!0)},[]),c=s.useCallback(()=>{o(!1)},[]);return s.createElement(mD.Provider,{value:{participant:t,isHovered:n}},s.createElement("div",{ref:i,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))});OD.displayName="GridCell";const ED=s.forwardRef((e,t)=>{var{stream:r,style:i}=e,n=MR(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=gD();if(!d)return null;const u=c[d.id];s.useImperativeHandle(t,()=>o.current);const p=s.useCallback(()=>{const e=o.current&&o.current.captureAspectRatio();e&&e!==u&&d.id&&a({aspectRatio:e,clientId:d.id})},[c,d.id,a]),h=r||d.stream;return h&&d.isVideoEnabled?s.createElement(NR,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),i),muted:d.isLocalClient},n,{stream:h,onVideoResize:p})):s.createElement(Gk,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0,muted:d.isLocalClient,stream:d.stream})});function DD({cellView:e,enableParticipantMenu:t,render:r}){const i=null==e?void 0:e.client;if(i)return"video"===e.type?s.createElement(OD,{participant:i},s.createElement(s.Fragment,null,r?r({participant:i}):s.createElement(s.Fragment,null,s.createElement(ED,null),t?s.createElement(PD,{participant:i}):null))):void 0}return ED.displayName="GridVideoView",e.GridCell=OD,e.GridVideoView=ED,e.ParticipantMenu=bD,e.ParticipantMenuContent=yD,e.ParticipantMenuItem=_D,e.ParticipantMenuTrigger=wD,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableParticipantMenu:a,enableConstrainedGrid:c}){const d=s.useRef(null),{containerFrame:l,cellViewsFloating:u,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,videoStage:g,setContainerBounds:v,setClientAspectRatios:b,maximizedParticipant:y,setMaximizedParticipant:w,isConstrained:_,floatingParticipant:S,setFloatingParticipant:C}=Tk({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:i,videoGridGap:n,enableSubgrid:o,enableConstrainedGrid:c}),R=s.useCallback(({aspectRatio:e,clientId:t})=>{b(r=>Object.assign(Object.assign({},r),{[t]:e}))},[b]),k=s.useMemo(()=>DD(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{})),[u]),T=s.useMemo(()=>h.map(t=>DD(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[h]),P=s.useMemo(()=>p.map(t=>DD(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))),[p]),O=s.useMemo(()=>f.map(e=>DD({cellView:e,enableParticipantMenu:a})),[f]);return s.useEffect(()=>{if(!d.current)return;const e=new ResizeObserver(zw(()=>{var e,t,r,i;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(i=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==i?i:480})},{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}},[]),s.createElement(fD.Provider,{value:{onSetClientAspectRatio:R,cellViewsVideoGrid:p,cellViewsInPresentationGrid:h,cellViewsInSubgrid:f,clientAspectRatios:m,maximizedParticipant:y,setMaximizedParticipant:w,floatingParticipant:S,setFloatingParticipant:C,isConstrained:_}},s.createElement("div",{ref:d,style:{width:"100%",height:"100%",position:"relative"}},s.createElement(ZR,{containerFrame:l,floatingContent:k,layoutVideoStage:g,presentationGridContent:T,gridContent:P,subgridContent:O})))},e.VideoView=NR,e.WherebyProvider=function({children:e}){const t=(({preloadedState:e,injectServices:t})=>ct({devTools:!1,reducer:HC,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(Wy.middleware),preloadedState:e}))({injectServices:function(){const e=wR.create({baseUrl:OR}),t=new cR({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:OR}),r=new TR({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=hg({host:new URL(e).host});return new PR({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}()});return s.createElement(_,{context:ER,store:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){const t=jR(),r=LR(zR);return s.useEffect(()=>(t(s_(e)),()=>{t(o_())}),[]),{state:r,actions:{setCameraDevice:s.useCallback(e=>t($w({deviceId:e})),[t]),setMicrophoneDevice:s.useCallback(e=>t(Gw({deviceId:e})),[t]),setSpeakerDevice:s.useCallback(e=>t(qw({deviceId:e})),[t]),toggleCameraEnabled:s.useCallback(e=>t(Hw({enabled:e})),[t]),toggleMicrophoneEnabled:s.useCallback(e=>t(Ww({enabled:e})),[t]),toggleLowDataModeEnabled:s.useCallback(e=>t(Kw({enabled:e})),[t])}}},e.useRoomConnection=function(e,t=FR){const r=jR(),i=LR(BR),n=s.useMemo(()=>{const r=new URL(e),i=new URLSearchParams(r.search),n=t.roomKey||i.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:n,roomUrl:e,userAgent:"browser-sdk:3.12.21",externalId:t.externalId||null}},[e,t]);s.useEffect(()=>()=>{r(Xy())},[]);const o=s.useCallback(e=>r(z_({text:e})),[r]),a=s.useCallback(()=>r(xC()),[r]),c=s.useCallback(e=>r(gC({displayName:e})),[r]),d=s.useCallback(e=>r(Hw({enabled:e})),[r]),l=s.useCallback(e=>r(Ww({enabled:e})),[r]),u=s.useCallback(e=>r(Kw({enabled:e})),[r]),p=s.useCallback(e=>r(yC({enabled:e})),[r]),h=s.useCallback(e=>r(nS({clientIds:[e],enable:!0})),[r]),f=s.useCallback(e=>r(sS({clientIds:[e],enable:!0})),[r]),m=s.useCallback(e=>r($C({participantId:e})),[r]),g=s.useCallback(e=>r(GC({participantId:e})),[r]),v=s.useCallback(()=>r($_()),[r]),b=s.useCallback(()=>r(uS()),[r]),y=s.useCallback(()=>r(G_()),[r]),w=s.useCallback(()=>r(pS()),[r]),_=s.useCallback(()=>r(Yy(n)),[r]),S=s.useCallback(()=>r(Xy()),[r]),C=s.useCallback(e=>r(vS({locked:e})),[r]),R=s.useCallback(e=>r(nS({clientIds:e,enable:!1})),[r]),k=s.useCallback(e=>r(sS({clientIds:e,enable:!1})),[r]),T=s.useCallback(e=>r(DS({id:e})),[r]),P=s.useCallback(e=>r(xS({id:e})),[r]),O=s.useCallback(e=>r(bS({clientId:e})),[r]),E=s.useCallback(e=>r(yS({stayBehind:e})),[r]),D=s.useCallback(e=>r(M_({group:e})),[r]),x=s.useCallback(()=>r(M_({group:""})),[r]),{events:I}=i;return{state:MR(i,["events"]),events:I,actions:{toggleLowDataMode:u,toggleRaiseHand:p,askToSpeak:h,askToTurnOnCamera:f,acceptWaitingParticipant:m,knock:a,joinRoom:_,leaveRoom:S,lockRoom:C,muteParticipants:R,turnOffParticipantCameras:k,kickParticipant:O,endMeeting:E,rejectWaitingParticipant:g,sendChatMessage:o,setDisplayName:c,startCloudRecording:v,startScreenshare:b,stopCloudRecording:y,stopScreenshare:w,toggleCamera:d,toggleMicrophone:l,spotlightParticipant:T,removeSpotlight:P,joinBreakoutGroup:D,joinBreakoutMainRoom:x}}},e}({},React,ReactDOM);