@whereby.com/browser-sdk 3.10.5 → 3.10.6
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.
- package/dist/cdn/v3-react.js +2 -2
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.esm.js +1 -1
- package/package.json +2 -2
package/dist/cdn/v3-react.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}function i(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 n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}var s=n(t),o=n(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(new 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},n=e.useSyncExternalStore,i=e.useRef,s=e.useEffect,o=e.useMemo,a=e.useDebugValue;u.useSyncExternalStoreWithSelector=function(e,t,c,d,l){var u,p=i(null);null===p.current?(u={hasValue:!1,value:null},p.current=u):u=p.current;var h=o((function(){var e,n,i=!1,s=function(t){if(!i){i=!0,e=t;var s=d(t);if(void 0!==l&&u.hasValue){var o=u.value;if(l(o,s))return n=o,o}return n=s,s}var a=n;if(r(e,t))return a;var c=d(t);return void 0!==l&&l(a,c)?a:(e=t,n=c,c)},o=void 0===c?null:c;return[function(){return s(t())},null===o?void 0:function(){return s(o())}]}),[t,c,d,l]),f=h[0],m=h[1],g=n(e,f,m);return s((function(){u.hasValue=!0,u.value=g}),[g]),a(g),g},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),u);var p=l.exports,h="default"in s?s.default:s,f=Symbol.for("react-redux-context"),m="undefined"!=typeof globalThis?globalThis:{};function g(){if(!h.createContext)return{};const e=m[f]??(m[f]=new Map);let t=e.get(h.createContext);return t||(t=h.createContext(null),t.displayName="ReactRedux",e.set(h.createContext,t)),t}var v=g();function b(e=v){return function(){const t=h.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 y=b(),w=()=>{throw new Error("uSES not initialized!")},_=(e,t)=>e===t;var S={notify(){},get:()=>[]};var C=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),R="undefined"!=typeof navigator&&"ReactNative"===navigator.product,T=C||R?h.useLayoutEffect:h.useEffect;var k=function({store:e,context:t,children:r,serverState:n,stabilityCheck:i="once",identityFunctionCheck:s="once"}){const o=h.useMemo((()=>{const t=function(e,t){let r,n=S,i=0,s=!1;function o(){d.onStateChange&&d.onStateChange()}function a(){i++,r||(r=t?t.addNestedSub(o):e.subscribe(o),n=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 n=!0;const i=t={callback:r,next:null,prev:t};return i.prev?i.prev.next=i:e=i,function(){n&&null!==e&&(n=!1,i.next?i.next.prev=i.prev:t=i.prev,i.prev?i.prev.next=i.next:e=i.next)}}}}())}function c(){i--,r&&0===i&&(r(),r=void 0,n.clear(),n=S)}const d={addNestedSub:function(e){a();const t=n.subscribe(e);let r=!1;return()=>{r||(r=!0,t(),c())}},notifyNestedSubs:function(){n.notify()},handleChangeWrapper:o,isSubscribed:function(){return s},trySubscribe:function(){s||(s=!0,a())},tryUnsubscribe:function(){s&&(s=!1,c())},getListeners:()=>n};return d}(e);return{store:e,subscription:t,getServerState:n?()=>n:void 0,stabilityCheck:i,identityFunctionCheck:s}}),[e,n,i,s]),a=h.useMemo((()=>e.getState()),[e]);T((()=>{const{subscription:t}=o;return t.onStateChange=t.notifyNestedSubs,t.trySubscribe(),a!==e.getState()&&t.notifyNestedSubs(),()=>{t.tryUnsubscribe(),t.onStateChange=void 0}}),[o,a]);const c=t||v;return h.createElement(c.Provider,{value:o},r)};function P(e=v){const t=e===v?y:b(e),r=()=>{const{store:e}=t();return e};return Object.assign(r,{withTypes:()=>r}),r}var E,O=P();E=p.useSyncExternalStoreWithSelector,w=E;var I=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),D=()=>Math.random().toString(36).substring(7).split("").join("."),x={INIT:`@@redux/INIT${D()}`,REPLACE:`@@redux/REPLACE${D()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${D()}`};function M(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 j(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 L(e){let t=typeof e;return t=j(e),t}function A(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${L(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: '${L(r)}'`);return r(A)(e,t)}let n=e,i=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 i}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${L(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(!M(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${L(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: '${L(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,i=n(i,e)}finally{c=!1}return(s=o).forEach((e=>{e()})),e}p({type:x.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: '${L(e)}`);n=e,p({type:x.REPLACE})},[I]: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: '${L(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[I](){return this}}}}}function N(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function B(e){const t=Object.keys(e),r={};for(let n=0;n<t.length;n++){const i=t[n];void 0===e[i]&&N(`No reducer provided for key "${i}"`),"function"==typeof e[i]&&(r[i]=e[i])}const n=Object.keys(r);let i,s;i={};try{!function(e){Object.keys(e).forEach((t=>{const r=e[t];if(void 0===r(void 0,{type:x.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:x.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 '${x.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 n=function(e,t,r,n){const i=Object.keys(t),s=r&&r.type===x.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===i.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!M(e))return`The ${s} has unexpected type of "${L(e)}". Expected argument to be an object with the following keys: "${i.join('", "')}"`;const o=Object.keys(e).filter((e=>!t.hasOwnProperty(e)&&!n[e]));return o.forEach((e=>{n[e]=!0})),r&&r.type===x.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: "${i.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,i);n&&N(n)}let o=!1;const a={};for(let i=0;i<n.length;i++){const s=n[i],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||n.length!==Object.keys(e).length,o?a:e}}function F(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce(((e,t)=>(...r)=>e(t(...r))))}function z(e){return M(e)&&"type"in e&&"string"==typeof e.type}var V=Symbol.for("immer-nothing"),U=Symbol.for("immer-draftable"),$=Symbol.for("immer-state"),G=[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 q(e,...t){{const r=G[e],n="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}}var H=Object.getPrototypeOf;function W(e){return!!e&&!!e[$]}function K(e){return!!e&&(Q(e)||Array.isArray(e)||!!e[U]||!!e.constructor?.[U]||te(e)||re(e))}var J=Object.prototype.constructor.toString();function Q(e){if(!e||"object"!=typeof e)return!1;const t=H(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)===J}function X(e,t){0===Y(e)?Object.entries(e).forEach((([r,n])=>{t(r,n,e)})):e.forEach(((r,n)=>t(n,r,e)))}function Y(e){const t=e[$];return t?t.type_:Array.isArray(e)?1:te(e)?2:re(e)?3:0}function Z(e,t){return 2===Y(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ee(e,t,r){const n=Y(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function te(e){return e instanceof Map}function re(e){return e instanceof Set}function ne(e){return e.copy_||e.base_}function ie(e,t){if(te(e))return new Map(e);if(re(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&Q(e)){if(!H(e)){const t=Object.create(null);return Object.assign(t,e)}return{...e}}const r=Object.getOwnPropertyDescriptors(e);delete r[$];let n=Reflect.ownKeys(r);for(let t=0;t<n.length;t++){const i=n[t],s=r[i];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(r[i]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[i]})}return Object.create(H(e),r)}function se(e,t=!1){return ae(e)||W(e)||!K(e)||(Y(e)>1&&(e.set=e.add=e.clear=e.delete=oe),Object.freeze(e),t&&X(e,((e,t)=>se(t,!0)))),e}function oe(){q(2)}function ae(e){return Object.isFrozen(e)}var ce,de={};function le(e){const t=de[e];return t||q(0,e),t}function ue(){return ce}function pe(e,t){t&&(le("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function he(e){fe(e),e.drafts_.forEach(ge),e.drafts_=null}function fe(e){e===ce&&(ce=e.parent_)}function me(e){return ce={drafts_:[],parent_:ce,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ge(e){const t=e[$];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ve(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[$].modified_&&(he(t),q(4)),K(e)&&(e=be(t,e),t.parent_||we(t,e)),t.patches_&&le("Patches").generateReplacementPatches_(r[$].base_,e,t.patches_,t.inversePatches_)):e=be(t,r,[]),he(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==V?e:void 0}function be(e,t,r){if(ae(t))return t;const n=t[$];if(!n)return X(t,((i,s)=>ye(e,n,t,i,s,r))),t;if(n.scope_!==e)return t;if(!n.modified_)return we(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let i=t,s=!1;3===n.type_&&(i=new Set(t),t.clear(),s=!0),X(i,((i,o)=>ye(e,n,t,i,o,r,s))),we(e,t,!1),r&&e.patches_&&le("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function ye(e,t,r,n,i,s,o){if(i===r&&q(5),W(i)){const o=be(e,i,s&&t&&3!==t.type_&&!Z(t.assigned_,n)?s.concat(n):void 0);if(ee(r,n,o),!W(o))return;e.canAutoFreeze_=!1}else o&&r.add(i);if(K(i)&&!ae(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;be(e,i),t&&t.scope_.parent_||we(e,i)}}function we(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&se(t,r)}var _e={get(e,t){if(t===$)return e;const r=ne(e);if(!Z(r,t))return function(e,t,r){const n=Re(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,r,t);const n=r[t];return e.finalized_||!K(n)?n:n===Ce(e.base_,t)?(ke(e),e.copy_[t]=Pe(n,e)):n},has:(e,t)=>t in ne(e),ownKeys:e=>Reflect.ownKeys(ne(e)),set(e,t,r){const n=Re(ne(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=Ce(ne(e),t),o=n?.[$];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((i=r)===(s=n)?0!==i||1/i==1/s:i!=i&&s!=s)&&(void 0!==r||Z(e.base_,t)))return!0;ke(e),Te(e)}var i,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!==Ce(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,ke(e),Te(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=ne(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty(){q(11)},getPrototypeOf:e=>H(e.base_),setPrototypeOf(){q(12)}},Se={};function Ce(e,t){const r=e[$];return(r?ne(r):e)[t]}function Re(e,t){if(!(t in e))return;let r=H(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=H(r)}}function Te(e){e.modified_||(e.modified_=!0,e.parent_&&Te(e.parent_))}function ke(e){e.copy_||(e.copy_=ie(e.base_,e.scope_.immer_.useStrictShallowCopy_))}X(_e,((e,t)=>{Se[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),Se.deleteProperty=function(e,t){return isNaN(parseInt(t))&&q(13),Se.set.call(this,e,t,void 0)},Se.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&q(14),_e.set.call(this,e[0],t,r,e[0])};function Pe(e,t){const r=te(e)?le("MapSet").proxyMap_(e,t):re(e)?le("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:ue(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=n,s=_e;r&&(i=[n],s=Se);const{revoke:o,proxy:a}=Proxy.revocable(i,s);return n.draft_=a,n.revoke_=o,a}(e,t);return(t?t.scope_:ue()).drafts_.push(r),r}function Ee(e){return W(e)||q(10,e),Oe(e)}function Oe(e){if(!K(e)||ae(e))return e;const t=e[$];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=ie(e,t.scope_.immer_.useStrictShallowCopy_)}else r=ie(e,!0);return X(r,((e,t)=>{ee(r,e,Oe(t))})),t&&(t.finalized_=!1),r}var Ie=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 n=this;return function(e=r,...i){return n.produce(e,(e=>t.call(this,e,...i)))}}let n;if("function"!=typeof t&&q(6),void 0!==r&&"function"!=typeof r&&q(7),K(e)){const i=me(this),s=Pe(e,void 0);let o=!0;try{n=t(s),o=!1}finally{o?he(i):fe(i)}return pe(i,r),ve(n,i)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===V&&(n=void 0),this.autoFreeze_&&se(n,!0),r){const t=[],i=[];le("Patches").generateReplacementPatches_(e,n,t,i),r(t,i)}return n}q(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,(t=>e(t,...r)));let r,n;return[this.produce(e,t,((e,t)=>{r=e,n=t})),r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){K(e)||q(8),W(e)&&(e=Ee(e));const t=me(this),r=Pe(e,void 0);return r[$].isManual_=!0,fe(t),r}finishDraft(e,t){const r=e&&e[$];r&&r.isManual_||q(9);const{scope_:n}=r;return pe(n,t),ve(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=le("Patches").applyPatches_;return W(e)?n(e,t):this.produce(e,(e=>n(e,t)))}},De=Ie.produce;Ie.produceWithPatches.bind(Ie),Ie.setAutoFreeze.bind(Ie),Ie.setUseStrictShallowCopy.bind(Ie),Ie.applyPatches.bind(Ie),Ie.createDraft.bind(Ie),Ie.finishDraft.bind(Ie);var xe=(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})}}},Me=(e,t,r)=>{const{memoize:n,memoizeOptions:i}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=n((()=>({})),...i);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})}},je={inputStabilityCheck:"once",identityFunctionCheck:"once"};var Le=e=>Array.isArray(e)?e:[e];function Ae(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 Ne(e,t){const r=[],{length:n}=e;for(let i=0;i<n;i++)r.push(e[i].apply(null,t));return r}var Be="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},Fe=0,ze=1;function Ve(){return{s:Fe,v:void 0,o:null,p:null}}function Ue(e,t={}){let r=Ve();const{resultEqualityCheck:n}=t;let i,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 n=e.get(r);void 0===n?(t=Ve(),e.set(r,t)):t=n}else{let e=t.p;null===e&&(t.p=e=new Map);const n=e.get(r);void 0===n?(t=Ve(),e.set(r,t)):t=n}}const a=t;let c;if(t.s===ze?c=t.v:(c=e.apply(null,arguments),s++),a.s=ze,n){const e=i?.deref?.()??i;null!=e&&n(e,c)&&(c=e,0!==s&&s--);i="object"==typeof c&&null!==c||"function"==typeof c?new Be(c):c}return a.v=c,c}return o.clearCache=()=>{r=Ve(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function $e(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,n=(...e)=>{let t,n=0,i=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=Ue,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=Le(d),f=Le(u),m=Ae(e),g=c((function(){return n++,o.apply(null,arguments)}),...h);let v=!0;const b=l((function(){i++;const e=Ne(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:n}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:n}={...je,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:xe},inputStabilityCheck:{shouldRun:"always"===n||"once"===n&&e,run:Me}}})(v,p);if(r.shouldRun&&r.run(o,e,t),n.shouldRun){const t=Ne(m,arguments);n.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:()=>i,resetDependencyRecomputations:()=>{i=0},lastResult:()=>t,recomputations:()=>n,resetRecomputations:()=>{n=0},memoize:c,argsMemoize:l})};return Object.assign(n,{withTypes:()=>n}),n}var Ge=$e(Ue),qe=Object.assign(((e,t=Ge)=>{!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),n=t(r.map((t=>e[t])),((...e)=>e.reduce(((e,t,n)=>(e[r[n]]=t,e)),{})));return n}),{withTypes:()=>qe});function He(e){return({dispatch:t,getState:r})=>n=>i=>"function"==typeof i?i(t,r,e):n(i)}var We=He(),Ke=He;((...e)=>{const t=$e(...e),r=Object.assign(((...e)=>{const r=t(...e),n=(e,...t)=>r(W(e)?Ee(e):e,...t);return Object.assign(n,r),n}),{withTypes:()=>r})})(Ue);var Je="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?F:F.apply(null,arguments)},Qe=e=>e&&"function"==typeof e.match;function Xe(e,t){function r(...r){if(t){let n=t(...r);if(!n)throw new Error("prepareAction did not return an object");return{type:e,payload:n.payload,..."meta"in n&&{meta:n.meta},..."error"in n&&{error:n.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>z(t)&&t.type===e,r}function Ye(e){return"function"==typeof e&&"type"in e&&Qe(e)}function Ze(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.`)}}}function et(e,t){for(const r of e)if(t(r))return r}var tt=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 rt(e){return K(e)?De(e,(()=>{})):e}function nt(e,t,r){if(e.has(t)){let n=e.get(t);return r.update&&(n=r.update(n,t,e),e.set(t,n)),n}if(!r.insert)throw new Error("No insert provided for key not already in map");const n=r.insert(t,e);return e.set(t,n),n}function it(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function st(e,t,r){const n=ot(e,t,r);return{detectMutations:()=>at(e,t,n,r)}}function ot(e,t=[],r,n="",i=new Set){const s={value:r};if(!e(r)&&!i.has(r)){i.add(r),s.children={};for(const i in r){const o=n?n+"."+i:i;t.length&&-1!==t.indexOf(o)||(s.children[i]=ot(e,t,r[i],o))}}return s}function at(e,t=[],r,n,i=!1,s=""){const o=r?r.value:void 0,a=o===n;if(i&&!a&&!Number.isNaN(n))return{wasMutated:!0,path:s};if(e(o)||e(n))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in n)c[e]=!0;const d=t.length>0;for(let i in c){const o=s?s+"."+i:i;if(d){if(t.some((e=>e instanceof RegExp?e.test(o):o===e)))continue}const c=at(e,t,r.children[i],n[i],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function ct(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||M(e)}function dt(e,t="",r=ct,n,i=[],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!=n?n(e):Object.entries(e),c=i.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(i.some((e=>e instanceof RegExp?e.test(a):a===e)))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=dt(d,a,r,n,i,s),o))return o}return s&<(e)&&s.add(e),!1}function lt(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!lt(t))return!1;return!0}function ut(e){return"boolean"==typeof e}var pt=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:n=!0,actionCreatorCheck:i=!0}=e??{};let s=new tt;if(t&&(ut(t)?s.push(We):s.push(Ke(t.extraArgument))),r){let e={};ut(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,n,i){return JSON.stringify(e,r(t,i),n)},r=function(e,t){let r=[],n=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+n.slice(0,r.indexOf(t)).join(".")+"]"}),function(i,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?n.splice(o,1/0,i):n.push(i),~r.indexOf(s)&&(s=t.call(this,i,s))}else r.push(s);return null==e?s:e.call(this,i,s)}},{isImmutable:n=it,ignoredPaths:i,warnAfter:s=32}=e;const o=st.bind(null,n,i);return({getState:e})=>{let r,n=e(),i=o(n);return a=>c=>{const d=Ze(s,"ImmutableStateInvariantMiddleware");d.measureTime((()=>{if(n=e(),r=i.detectMutations(),i=o(n),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(n=e(),r=i.detectMutations(),i=o(n),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(n){let e={};ut(n)||(e=n),s.push(function(e={}){{const{isSerializable:t=ct,getEntries:r,ignoredActions:n=[],ignoredActionPaths:i=["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(!z(u))return d(u);const p=d(u),h=Ze(o,"SerializableStateInvariantMiddleware");return c||n.length&&-1!==n.indexOf(u.type)||h.measureTime((()=>{const e=dt(u,"",t,r,i,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 n=dt(e.getState(),"",t,r,s,l);if(n){const{keyPath:e,value:t}=n;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(i){let e={};ut(i)||(e=i),s.unshift(function(e={}){const{isActionCreator:t=Ye}=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},ht=e=>t=>{setTimeout(t,e)},ft="undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:ht(10),mt=e=>function(t){const{autoBatch:r=!0}=t??{};let n=new tt(e);return r&&n.push(((e={type:"raf"})=>t=>(...r)=>{const n=t(...r);let i=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?ft:"callback"===e.type?e.queueNotification:ht(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach((e=>e())))};return Object.assign({},n,{subscribe(e){const t=n.subscribe((()=>i&&e()));return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return i=!e?.meta?.RTK_autoBatch,s=!i,s&&(o||(o=!0,c(d))),n.dispatch(e)}finally{i=!0}}})})("object"==typeof r?r:void 0)),n};function gt(e){const t=pt(),{reducer:r,middleware:n,devTools:i=!0,preloadedState:s,enhancers:o}=e||{};let a,c;if("function"==typeof r)a=r;else{if(!M(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");a=B(r)}if(n&&"function"!=typeof n)throw new Error("`middleware` field must be a callback");if("function"==typeof n){if(c=n(t),!Array.isArray(c))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else c=t();if(c.some((e=>"function"!=typeof e)))throw new Error("each middleware provided to configureStore must be a function");let d=F;i&&(d=Je({trace:!0,..."object"==typeof i&&i}));const l=function(...e){return t=>(r,n)=>{const i=t(r,n);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:i.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map((e=>e(o)));return s=F(...a)(i.dispatch),{...i,dispatch:s}}}(...c),u=mt(l);if(o&&"function"!=typeof o)throw new Error("`enhancers` field must be a callback");let p="function"==typeof o?o(u):u();if(!Array.isArray(p))throw new Error("`enhancers` callback must return an array");if(p.some((e=>"function"!=typeof e)))throw new Error("each enhancer provided to configureStore must be a function");c.length&&!p.includes(l)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return A(a,s,d(...p))}function vt(e){const t={},r=[];let n;const i={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(n)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,i},addMatcher(e,t){if(n)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),i},addDefaultCase(e){if(n)throw new Error("`builder.addDefaultCase` can only be called once");return n=e,i}};return e(i),[t,r,n]}var bt=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t};function yt(...e){return t=>e.some((e=>((e,t)=>Qe(e)?e.match(t):e(t))(e,t)))}var wt=["name","message","stack","code"],_t=class{constructor(e,t){this.payload=e,this.meta=t}_type},St=class{constructor(e,t){this.payload=e,this.meta=t}_type},Ct=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of wt)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},Rt=(()=>{function e(e,t,r){const n=Xe(e+"/fulfilled",((e,t,r,n)=>({payload:e,meta:{...n||{},arg:r,requestId:t,requestStatus:"fulfilled"}}))),i=Xe(e+"/pending",((e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}}))),s=Xe(e+"/rejected",((e,t,n,i,s)=>({payload:i,error:(r&&r.serializeError||Ct)(e||"Rejected"),meta:{...s||{},arg:n,requestId:t,rejectedWithValue:!!i,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}})));return Object.assign((function(e){return(o,a,c)=>{const d=r?.idGenerator?r.idGenerator(e):bt(),l=new AbortController;let u,p;function h(e){p=e,l.abort()}const f=async function(){let f;try{let s=r?.condition?.(e,{getState:a,extra:c});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||l.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise(((e,t)=>{u=()=>{t({name:"AbortError",message:p||"Aborted"})},l.signal.addEventListener("abort",u)}));o(i(d,e,r?.getPendingMeta?.({requestId:d,arg:e},{getState:a,extra:c}))),f=await Promise.race([m,Promise.resolve(t(e,{dispatch:o,getState:a,extra:c,requestId:d,signal:l.signal,abort:h,rejectWithValue:(e,t)=>new _t(e,t),fulfillWithValue:(e,t)=>new St(e,t)})).then((t=>{if(t instanceof _t)throw t;return t instanceof St?n(t.payload,d,e,t.meta):n(t,d,e)}))])}catch(t){f=t instanceof _t?s(null,d,e,t.payload,t.meta):s(t,d,e)}finally{u&&l.signal.removeEventListener("abort",u)}return r&&!r.dispatchConditionRejection&&s.match(f)&&f.meta.condition||o(f),f}();return Object.assign(f,{abort:h,requestId:d,arg:e,unwrap:()=>f.then(Tt)})}}),{pending:i,rejected:s,fulfilled:n,settled:yt(s,n),typePrefix:e})}return e.withTypes=()=>e,e})();function Tt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var kt=Symbol.for("rtk-slice-createasyncthunk");function Pt(e,t){return`${e}/${t}`}function Et({creators:e}={}){const t=e?.asyncThunk?.[kt];return function(e){const{name:r,reducerPath:n=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const i=("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(i),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=[],n]="function"==typeof e.extraReducers?vt(e.extraReducers):[e.extraReducers],i={...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,[n,i,s]=vt(t);if("function"==typeof e)r=()=>rt(e());else{const t=rt(e);r=()=>t}function o(e=r(),t){let o=[n[t.type],...i.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(W(e)){const n=r(e,t);return void 0===n?e:n}if(K(e))return De(e,(e=>r(e,t)));{const n=r(e,t);if(void 0===n){if(null===e)return e;throw new Error("A case reducer on a non-draftable value must not return undefined")}return n}}return e}),e)}return o.getInitialState=r,o}(e.initialState,(e=>{for(let t in i)e.addCase(t,i[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);n&&e.addDefaultCase(n)}))}s.forEach((n=>{const s=i[n],o={reducerName:n,type:Pt(r,n),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},n,i){let s,o;if("reducer"in n){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(n))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=n.reducer,o=n.prepare}else s=n;i.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?Xe(e,o):Xe(e))}(o,s,a):function({type:e,reducerName:t},r,n,i){if(!i)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=i(e,s,l);n.exposeAction(t,u),o&&n.addCase(u.fulfilled,o);a&&n.addCase(u.pending,a);c&&n.addCase(u.rejected,c);d&&n.addMatcher(u.settled,d);n.exposeCaseReducer(t,{fulfilled:o||Dt,pending:a||Dt,rejected:c||Dt,settled:d||Dt})}(o,s,a,t)}));const d=e=>e,l=new Map;let u;function p(e,t){return u||(u=c()),u(e,t)}function h(){return u||(u=c()),u.getInitialState()}function f(t,r=!1){function n(e){let n=e[t];if(void 0===n){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");n=h()}return n}function i(t=d){const n=nt(l,r,{insert:()=>new WeakMap});return nt(n,t,{insert:()=>{const n={};for(const[i,s]of Object.entries(e.selectors??{}))n[i]=Ot(s,t,h,r);return n}})}return{reducerPath:t,getSelectors:i,get selectors(){return i(n)},selectSlice:n}}const m={name:r,reducer:p,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:h,...f(n),injectInto(e,{reducerPath:t,...r}={}){const i=t??n;return e.inject({reducerPath:i,reducer:p},r),{...m,...f(i,!0)}}};return m}}function Ot(e,t,r,n){function i(i,...s){let o=t(i);if(void 0===o){if(!n)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return i.unwrapped=e,i}var It=Et();function Dt(){}var xt="listener",Mt="completed",jt="cancelled",Lt=`task-${jt}`,At=`task-${Mt}`,Nt=`${xt}-${jt}`,Bt=`${xt}-${Mt}`,Ft=class{constructor(e){this.code=e,this.message=`task ${jt} (reason: ${e})`}name="TaskAbortError";message},zt=(e,t)=>{if("function"!=typeof e)throw new Error(`${t} is not a function`)},Vt=()=>{},Ut=(e,t=Vt)=>(e.catch(t),e),$t=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Gt=(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))},qt=e=>{if(e.aborted){const{reason:t}=e;throw new Ft(t)}};function Ht(e,t){let r=Vt;return new Promise(((n,i)=>{const s=()=>i(new Ft(e.reason));e.aborted?s():(r=$t(e,s),t.finally((()=>r())).then(n,i))})).finally((()=>{r=Vt}))}var Wt=e=>t=>Ut(Ht(e,t).then((t=>(qt(e),t)))),Kt=e=>{const t=Wt(e);return e=>t(new Promise((t=>setTimeout(t,e))))},{assign:Jt}=Object,Qt={},Xt="listenerMiddleware",Yt=(e,t)=>(r,n)=>{zt(r,"taskExecutor");const i=new AbortController;var s;s=i,$t(e,(()=>Gt(s,e.reason)));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof Ft?"cancelled":"rejected",error:e}}finally{t?.()}})((async()=>{qt(e),qt(i.signal);const t=await r({pause:Wt(i.signal),delay:Kt(i.signal),signal:i.signal});return qt(i.signal),t}),(()=>Gt(i,At)));return n?.autoJoin&&t.push(o.catch(Vt)),{result:Wt(e)(o),cancel(){Gt(i,Lt)}}},Zt=(e,t)=>(r,n)=>Ut((async(r,n)=>{qt(t);let i=()=>{};const s=[new Promise(((t,n)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});i=()=>{s(),n()}}))];null!=n&&s.push(new Promise((e=>setTimeout(e,n,null))));try{const e=await Ht(t,Promise.race(s));return qt(t),e}finally{i()}})(r,n)),er=e=>{let{type:t,actionCreator:r,matcher:n,predicate:i,effect:s}=e;if(t)i=Xe(t).match;else if(r)t=r.type,i=r.match;else if(n)i=n;else if(!i)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return zt(s,"options.listener"),{predicate:i,type:t,effect:s}},tr=Object.assign((e=>{const{type:t,predicate:r,effect:n}=er(e);return{id:bt(),effect:n,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}}),{withTypes:()=>tr}),rr=e=>{e.pending.forEach((e=>{Gt(e,Nt)}))},nr=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout((()=>{throw e}),0)}},ir=Object.assign(Xe(`${Xt}/add`),{withTypes:()=>ir}),sr=Xe(`${Xt}/removeAll`),or=Object.assign(Xe(`${Xt}/remove`),{withTypes:()=>or}),ar=(...e)=>{console.error(`${Xt}/error`,...e)};let cr=!0,dr=!0;function lr(e,t,r){const n=e.match(t);return n&&n.length>=r&&parseInt(n[r],10)}function ur(e,t,r){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),i.apply(this,[e,s])};const s=n.removeEventListener;n.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 n=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,n])},Object.defineProperty(n,"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 pr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(cr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function hr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(dr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function fr(){if("object"==typeof window){if(cr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function mr(e,t){dr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function gr(e){return"[object Object]"===Object.prototype.toString.call(e)}function vr(e){return gr(e)?Object.keys(e).reduce((function(t,r){const n=gr(e[r]),i=n?vr(e[r]):e[r],s=n&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function br(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?br(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach((t=>{br(e,e.get(t),r)}))})))}function yr(e,t,r){const n=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===n&&r.trackId===t.id&&br(e,r,i)}))})),i}const wr=fr;function _r(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const n=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 n="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[i("min",r)]=n.ideal,t.optional.push(e),e={},e[i("max",r)]=n.ideal,t.optional.push(e)):(e[i("",r)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(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=n(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=n(e.video),wr("chrome: "+JSON.stringify(e)),i(e)}))}e.video=n(e.video)}return wr("chrome: "+JSON.stringify(e)),i(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,n){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(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 Sr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Cr(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 n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ur(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Rr(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,n){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.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 n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.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 Tr(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=>yr(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}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>yr(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,n;return this.getSenders().forEach((r=>{r.track===e&&(t?n=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?n=!0:r=t),t.track===e))),n||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 kr(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 n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};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 n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const i=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]})),i.apply(this,arguments)}}function Pr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return kr(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 n=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}n.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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 n=[].slice.call(arguments,1);if(1!==n.length||!n[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 i=this._streams[r.id];if(i)i.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[r.id]=n,this._reverseStreams[n.id]=r,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],n={[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]=n[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 n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.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 Er(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],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Or(e,t){ur(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Ir=Object.freeze({__proto__:null,fixNegotiationNeeded:Or,shimAddTrackRemoveTrack:Pr,shimAddTrackRemoveTrackWithNative:kr,shimGetSendersWithDtmf:Rr,shimGetUserMedia:_r,shimMediaStream:Sr,shimOnTrack:Cr,shimPeerConnection:Er,shimSenderReceiverGetStats:Tr});function Dr(e,t){const r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,n){mr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,n)},!(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)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.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 xr(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 Mr(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],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function jr(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 Lr(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}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ar(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){mr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Nr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Br(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 n=t.apply(this,arguments);if(r){const{sender:t}=n,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 n})}function Fr(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 zr(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 Vr(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 Ur=Object.freeze({__proto__:null,shimAddTransceiver:Br,shimCreateAnswer:Vr,shimCreateOffer:zr,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:Fr,shimGetUserMedia:Dr,shimOnTrack:xr,shimPeerConnection:Mr,shimRTCDataChannel:Nr,shimReceiverGetStats:Lr,shimRemoveStream:Ar,shimSenderGetStats:jr});function $r(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 Gr(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 qr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,r){const n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,r){const n=o.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=a}function Hr(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(Wr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))}function Wr(e){return e&&void 0!==e.video?Object.assign({},e,{video:vr(e.video)}):e}function Kr(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 n=e.iceServers[r];void 0===n.urls&&n.url?(mr("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):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 Jr(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 Qr(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 Xr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Yr=Object.freeze({__proto__:null,shimAudioContext:Xr,shimCallbacksAPI:qr,shimConstraints:Wr,shimCreateOfferLegacy:Qr,shimGetUserMedia:Hr,shimLocalStreamsAPI:$r,shimRTCIceServerUrls:Kr,shimRemoteStreamsAPI:Gr,shimTrackEventTransceiver:Jr}),Zr={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 n=e.type;return t.push("typ"),t.push(n),"host"!==n&&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 n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)r=n[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 n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+r+" "+n.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)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+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 n=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return n&&i?{usernameFragment:n.substring(12),password:i.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:[]},n=t.splitLines(e)[0].split(" ");r.profile=n[2];for(let i=3;i<n.length;i++){const s=n[i],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=i.length?t.parseFmtp(i[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{i.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 n="";n+="m="+e+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let i=0;return r.codecs.forEach((e=>{e.maxptime>i&&(i=e.maxptime)})),i>0&&(n+="a=maxptime:"+i+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const r=[],n=t.parseRtpParameters(e),i=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.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]),n.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),i&&(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={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.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 n=t.matchPrefix(e,"a=msid:");if(1===n.length)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0?(r=i[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let i;n.length>0&&(i=parseInt(n[0].substring(19),10)),isNaN(i)&&(i=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:i};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:i}}},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,n){let i;const s=void 0!==r?r:2;i=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+i+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[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}(Zr);var en=Zr.exports,tn=c(en),rn=i({__proto__:null,default:tn},[en]);function nn(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),n=tn.parseCandidate(e.candidate);for(const e in n)e in r||Object.defineProperty(r,e,{value:n[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,ur(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function sn(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ur(e,"icecandidate",(e=>{if(e.candidate){const t=tn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function on(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=tn.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=tn.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),n=function(e,r){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const i=tn.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?n=parseInt(i[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],e);let i;i=0===r&&0===n?Number.POSITIVE_INFINITY:0===r||0===n?Math.max(r,n):Math.min(r,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>i}),this._sctp=s}return r.apply(this,arguments)}}function an(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>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},ur(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function cn(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 dn(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)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 ln(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 un(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 pn=Object.freeze({__proto__:null,removeExtmapAllowMixed:dn,shimAddIceCandidateNullOrEmpty:ln,shimConnectionState:cn,shimMaxMessageSize:on,shimParameterlessSetLocalDescription:un,shimRTCIceCandidate:nn,shimRTCIceCandidateRelayProtocol:sn,shimSendThrowTypeError:an});const hn=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=fr,n=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=lr(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=lr(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=lr(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),i={browserDetails:n,commonShim:pn,extractVersion:lr,disableLog:pr,disableWarnings:hr,sdp:rn};switch(n.browser){case"chrome":if(!Ir||!Er||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===n.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=Ir,ln(e,n),un(e),_r(e,n),Sr(e),Er(e,n),Cr(e),Pr(e,n),Rr(e),Tr(e),Or(e,n),nn(e),sn(e),cn(e),on(e,n),an(e),dn(e,n);break;case"firefox":if(!Ur||!Mr||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Ur,ln(e,n),un(e),Dr(e,n),Mr(e,n),xr(e),Ar(e),jr(e),Lr(e),Nr(e),Br(e),Fr(e),zr(e),Vr(e),nn(e),cn(e),on(e,n),an(e);break;case"safari":if(!Yr||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=Yr,ln(e,n),un(e),Kr(e),Qr(e),qr(e),$r(e),Gr(e),Jr(e),Hr(e),Xr(e),nn(e),sn(e),on(e,n),an(e),dn(e,n);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});function fn(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 mn=function(e,t,r){var n=0,i=!!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_"+n++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach((function(e){delete e.credential})),r.browserType=i?"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),n=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach((function(r){var n=t[r];delete n.id,e[r]&&Object.keys(n).forEach((function(i){n[i]===e[r][i]&&delete t[r][i],(0===Object.keys(n).length||1===Object.keys(n).length&&n.timestamp)&&delete t[r]}))}));var r=-1/0;return Object.keys(t).forEach((function(e){var n=t[e];n.timestamp>r&&(r=n.timestamp)})),Object.keys(t).forEach((function(e){var n=t[e];n.timestamp===r&&(n.timestamp=0)})),t.timestamp=r,t}(o[l]||{},r)),o[l]=n}))};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 n=arguments[0],i=n.getTracks().map((function(e){return e.kind+":"+e.id})).join(",");return e(t,this.__rtcStatsId,n.id+" "+i),r.apply(this,arguments)})})),["addTrack"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0],i=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,n.kind+":"+n.id+" "+(i.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 n=arguments[0].track;return e(t,this.__rtcStatsId,n?n.kind+":"+n.id:"null"),r.apply(this,arguments)})})),["createOffer","createAnswer"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n,i=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?n=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(n=arguments[2]),e(t,this.__rtcStatsId,n),r.apply(this,n?[n]:void 0).then((function(r){if(e(t+"OnSuccess",i,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])}),(function(r){if(e(t+"OnFailure",i,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 n=this.__rtcStatsId,i=arguments;return e(t,this.__rtcStatsId,i[0]),r.apply(this,[i[0]]).then((function(){e(t+"OnSuccess",n,void 0),i.length>=2&&"function"==typeof i[1]&&i[1].apply(null,[])}),(function(r){if(e(t+"OnFailure",n,r.toString()),!(i.length>=3&&"function"==typeof i[2]))throw r;i[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 n=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];n(arguments[0],(function(r){e("getUserMediaOnSuccess",null,fn(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,fn(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,fn(t)),t}),(function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},gn=c(mn);let vn;const bn=new Uint8Array(16);function yn(){if(!vn&&(vn="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!vn))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vn(bn)}const wn=[];for(let iO=0;iO<256;++iO)wn.push((iO+256).toString(16).slice(1));var _n={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Sn(e,t,r){if(_n.randomUUID&&!t&&!e)return _n.randomUUID();const n=(e=e||{}).random||(e.rng||yn)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return wn[e[t+0]]+wn[e[t+1]]+wn[e[t+2]]+wn[e[t+3]]+"-"+wn[e[t+4]]+wn[e[t+5]]+"-"+wn[e[t+6]]+wn[e[t+7]]+"-"+wn[e[t+8]]+wn[e[t+9]]+"-"+wn[e[t+10]]+wn[e[t+11]]+wn[e[t+12]]+wn[e[t+13]]+wn[e[t+14]]+wn[e[t+15]]}(n)}var Cn,Rn,Tn={},kn={exports:{}};function Pn(){if(Rn)return Cn;Rn=1;var e=1e3,t=60*e,r=60*t,n=24*r,i=7*n,s=365.25*n;function o(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return Cn=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*i;case"days":case"day":case"d":return c*n;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(i){var s=Math.abs(i);if(s>=n)return o(i,s,n,"day");if(s>=r)return o(i,s,r,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=n)return Math.round(i/n)+"d";if(s>=r)return Math.round(i/r)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},Cn}var En=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,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,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),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:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}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.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Pn(),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 n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,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")}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=En(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 On=kn.exports,In={},Dn={exports:{}};!function(e,t){!function(r,n){var i,s="",o="function",a="undefined",c="object",d="string",l="major",u="model",p="name",h="type",f="vendor",m="version",g="architecture",v="console",b="mobile",y="tablet",w="smarttv",_="wearable",S="xr",C="embedded",R="inapp",T="user-agent",k="brands",P="formFactors",E="fullVersionList",O="platform",I="platformVersion",D="bitness",x="sec-ch-ua",M=x+"-full-version-list",j=x+"-arch",L=x+"-"+D,A=x+"-form-factors",N=x+"-"+b,B=x+"-"+u,F=x+"-"+O,z=F+"-version",V=[k,E,b,u,O,I,g,P,D],U="browser",$="cpu",G="device",q="engine",H="os",W="result",K="Amazon",J="Apple",Q="ASUS",X="BlackBerry",Y="Google",Z="Huawei",ee="Lenovo",te="LG",re="Microsoft",ne="Motorola",ie="Samsung",se="Sharp",oe="Sony",ae="Xiaomi",ce="Zebra",de="Mobile ",le=" Browser",ue="Chrome",pe="Chromecast",he="Firefox",fe="Opera",me="Facebook",ge="Sogou",ve="Windows",be=typeof r!==a,ye=be&&r.navigator?r.navigator:n,we=ye&&ye.userAgentData?ye.userAgentData:n,_e=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},Se=function(e,t){if(typeof e===c&&e.length>0){for(var r in e)if(ke(e[r])==ke(t))return!0;return!1}return!!Re(e)&&-1!==ke(t).indexOf(ke(e))},Ce=function(e,t){for(var r in e)return/^(browser|cpu|device|engine|os)$/.test(r)||!!t&&Ce(e[r])},Re=function(e){return typeof e===d},Te=function(e){if(!e)return n;for(var t=[],r=Oe(/\\?\"/g,e).split(","),i=0;i<r.length;i++)if(r[i].indexOf(";")>-1){var s=De(r[i]).split(";v=");t[i]={brand:s[0],version:s[1]}}else t[i]=De(r[i]);return t},ke=function(e){return Re(e)?e.toLowerCase():e},Pe=function(e){return Re(e)?Oe(/[^\d\.]/g,e).split(".")[0]:n},Ee=function(e){for(var t in e){var r=e[t];typeof r==c&&2==r.length?this[r[0]]=r[1]:this[r]=n}return this},Oe=function(e,t){return Re(t)?t.replace(e,s):t},Ie=function(e){return Oe(/\\?\"/g,e)},De=function(e,t){if(Re(e))return e=Oe(/^\s\s*/,e),typeof t===a?e:e.substring(0,500)},xe=function(e,t){if(e&&t)for(var r,i,s,a,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=i=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(s=0;s<h.length;s++)l=d[++i],typeof(a=h[s])===c&&a.length>0?2===a.length?typeof a[1]==o?this[a[0]]=a[1].call(this,l):this[a[0]]=a[1]:3===a.length?typeof a[1]!==o||a[1].exec&&a[1].test?this[a[0]]=l?l.replace(a[1],a[2]):n:this[a[0]]=l?a[1].call(this,l,a[2]):n:4===a.length&&(this[a[0]]=l?a[3].call(this,l.replace(a[1],a[2])):n):this[a]=l||n;u+=2}},Me=function(e,t){for(var r in t)if(typeof t[r]===c&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(Se(t[r][i],e))return"?"===r?n:r}else if(Se(t[r],e))return"?"===r?n:r;return t.hasOwnProperty("*")?t["*"]:e},je={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"},Le={embedded:"Automotive",mobile:"Mobile",tablet:["Tablet","EInk"],smarttv:"TV",wearable:"Watch",xr:["VR","XR"],"?":["Desktop","Unknown"],"*":n},Ae={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[m,[p,de+"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[m,[p,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[p,m],[/opios[\/ ]+([\w\.]+)/i],[m,[p,fe+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[m,[p,fe+" GX"]],[/\bopr\/([\w\.]+)/i],[m,[p,fe]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[m,[p,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[m,[p,"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],[p,m],[/quark(?:pc)?\/([-\w\.]+)/i],[m,[p,"Quark"]],[/\bddg\/([\w\.]+)/i],[m,[p,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[m,[p,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[m,[p,"WeChat"]],[/konqueror\/([\w\.]+)/i],[m,[p,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[m,[p,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[m,[p,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[m,[p,"Smart "+ee+le]],[/(avast|avg)\/([\w\.]+)/i],[[p,/(.+)/,"$1 Secure"+le],m],[/\bfocus\/([\w\.]+)/i],[m,[p,he+" Focus"]],[/\bopt\/([\w\.]+)/i],[m,[p,fe+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[m,[p,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[m,[p,"Dolphin"]],[/coast\/([\w\.]+)/i],[m,[p,fe+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[m,[p,"MIUI"+le]],[/fxios\/([\w\.-]+)/i],[m,[p,de+he]],[/\bqihoobrowser\/?([\w\.]*)/i],[m,[p,"360"]],[/\b(qq)\/([\w\.]+)/i],[[p,/(.+)/,"$1Browser"],m],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[p,/(.+)/,"$1"+le],m],[/samsungbrowser\/([\w\.]+)/i],[m,[p,ie+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[m,[p,ge+" Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[p,ge+" Mobile"],m],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[p,m],[/(lbbrowser|rekonq)/i],[p],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[m,p],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[p,me],m,[h,R]],[/(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,/(instagram|snapchat)[\/ ]([-\w\.]+)/i],[p,m,[h,R]],[/\bgsa\/([\w\.]+) .*safari\//i],[m,[p,"GSA"],[h,R]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[m,[p,"TikTok"],[h,R]],[/\[(linkedin)app\]/i],[p,[h,R]],[/(chromium)[\/ ]([-\w\.]+)/i],[p,m],[/headlesschrome(?:\/([\w\.]+)| )/i],[m,[p,ue+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[p,ue+" WebView"],m],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[m,[p,"Android"+le]],[/chrome\/([\w\.]+) mobile/i],[m,[p,de+"Chrome"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[p,m],[/version\/([\w\.\,]+) .*mobile(?:\/\w+ | ?)safari/i],[m,[p,de+"Safari"]],[/iphone .*mobile(?:\/\w+ | ?)safari/i],[[p,de+"Safari"]],[/version\/([\w\.\,]+) .*(safari)/i],[m,p],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[p,[m,"1"]],[/(webkit|khtml)\/([\w\.]+)/i],[p,m],[/(?:mobile|tablet);.*(firefox)\/([\w\.-]+)/i],[[p,de+he],m],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[p,"Netscape"],m],[/(wolvic|librewolf)\/([\w\.]+)/i],[p,m],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[m,[p,he+" 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,/\b(links) \(([\w\.]+)/i],[p,[m,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[p,[m,/[^\d\.]+./,s]]],cpu:[[/\b(?:(amd|x|x86[-_]?|wow|win)64)\b/i],[[g,"amd64"]],[/(ia32(?=;))/i,/((?:i[346]|x)86)[;\)]/i],[[g,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[g,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[g,"armhf"]],[/windows (ce|mobile); ppc;/i],[[g,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[g,/ower/,s,ke]],[/(sun4\w)[;\)]/i],[[g,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[g,ke]]],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],[u,[f,ie],[h,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[f,ie],[h,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[f,J],[h,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[f,J],[h,y]],[/(macintosh);/i],[u,[f,J]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[f,se],[h,b]],[/(?:honor)([-\w ]+)[;\)]/i],[u,[f,"Honor"],[h,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[f,Z],[h,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[f,Z],[h,b]],[/\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],[[u,/_/g," "],[f,ae],[h,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[f,ae],[h,y]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[f,"OPPO"],[h,b]],[/\b(opd2\d{3}a?) bui/i],[u,[f,"OPPO"],[h,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[f,"Vivo"],[h,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[f,"Realme"],[h,b]],[/\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],[u,[f,ne],[h,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[f,ne],[h,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[f,te],[h,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[f,te],[h,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[f,ee],[h,y]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[f,"Nokia"],[h,b]],[/(pixel c)\b/i],[u,[f,Y],[h,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[f,Y],[h,b]],[/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],[u,[f,oe],[h,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[f,oe],[h,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[f,"OnePlus"],[h,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[f,K],[h,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[f,K],[h,b]],[/(playbook);[-\w\),; ]+(rim)/i],[u,f,[h,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[f,X],[h,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[f,Q],[h,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[f,Q],[h,b]],[/(nexus 9)/i],[u,[f,"HTC"],[h,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[u,/_/g," "],[h,b]],[/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],[u,[f,"TCL"],[h,y]],[/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],[u,[f,"TCL"],[h,b]],[/(itel) ((\w+))/i],[[f,ke],u,[h,Me,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[f,"Acer"],[h,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[f,"Meizu"],[h,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[f,"Ulefone"],[h,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[f,"Energizer"],[h,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[f,"Cat"],[h,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[f,"Smartfren"],[h,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[f,"Nothing"],[h,b]],[/(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],[f,u,[h,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i],[f,u,[h,y]],[/(surface duo)/i],[u,[f,re],[h,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[f,"Fairphone"],[h,b]],[/(shield[\w ]+) b/i],[u,[f,"Nvidia"],[h,y]],[/(sprint) (\w+)/i],[f,u,[h,b]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[f,re],[h,b]],[/droid.+; ([c6]+|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[f,ce],[h,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[f,ce],[h,b]],[/smart-tv.+(samsung)/i],[f,[h,w]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[f,ie],[h,w]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,te],[h,w]],[/(apple) ?tv/i],[f,[u,J+" TV"],[h,w]],[/crkey.*devicetype\/chromecast/i],[[u,pe+" Third Generation"],[f,Y],[h,w]],[/crkey.*devicetype\/([^/]*)/i],[[u,/^/,"Chromecast "],[f,Y],[h,w]],[/fuchsia.*crkey/i],[[u,pe+" Nest Hub"],[f,Y],[h,w]],[/crkey/i],[[u,pe],[f,Y],[h,w]],[/droid.+aft(\w+)( bui|\))/i],[u,[f,K],[h,w]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[f,se],[h,w]],[/(bravia[\w ]+)( bui|\))/i],[u,[f,oe],[h,w]],[/(mitv-\w{5}) bui/i],[u,[f,ae],[h,w]],[/Hbbtv.*(technisat) (.*);/i],[f,u,[h,w]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,De],[u,De],[h,w]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,w]],[/(ouya)/i,/(nintendo) (\w+)/i],[f,u,[h,v]],[/droid.+; (shield) bui/i],[u,[f,"Nvidia"],[h,v]],[/(playstation \w+)/i],[u,[f,oe],[h,v]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[f,re],[h,v]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[u,[f,ie],[h,_]],[/((pebble))app/i],[f,u,[h,_]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[f,J],[h,_]],[/droid.+; (wt63?0{2,3})\)/i],[u,[f,ce],[h,_]],[/droid.+; (glass) \d/i],[u,[f,Y],[h,S]],[/(pico) (4|neo3(?: link|pro)?)/i],[f,u,[h,S]],[/; (quest( \d| pro)?)/i],[u,[f,me],[h,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[h,C]],[/(aeobc)\b/i],[u,[f,K],[h,C]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[h,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[h,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,b]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[m,[p,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[p,m],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[m,[p,"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],[p,m],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[m,p]],os:[[/microsoft (windows) (vista|xp)/i],[p,m],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[p,[m,Me,je]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[m,Me,je],[p,ve]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[m,/_/g,"."],[p,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[p,"macOS"],[m,/_/g,"."]],[/android ([\d\.]+).*crkey/i],[m,[p,pe+" Android"]],[/fuchsia.*crkey\/([\d\.]+)/i],[m,[p,pe+" Fuchsia"]],[/crkey\/([\d\.]+).*devicetype\/smartspeaker/i],[m,[p,pe+" SmartSpeaker"]],[/linux.*crkey\/([\d\.]+)/i],[m,[p,pe+" Linux"]],[/crkey\/([\d\.]+)/i],[m,[p,pe]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[m,p],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[p,m],[/\(bb(10);/i],[m,[p,X]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[m,[p,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[m,[p,he+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[m,[p,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[m,[p,"watchOS"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[p,"Chrome OS"],m],[/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,/(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],[p,m],[/(sunos) ?([\w\.\d]*)/i],[[p,"Solaris"],m],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[p,m]]},Ne=(i={init:{},isIgnore:{},isIgnoreRgx:{},toString:{}},Ee.call(i.init,[[U,[p,m,l,h]],[$,[g]],[G,[h,u,f]],[q,[p,m]],[H,[p,m]]]),Ee.call(i.isIgnore,[[U,[m,l]],[q,[m]],[H,[m]]]),Ee.call(i.isIgnoreRgx,[[U,/ ?browser$/i],[H,/ ?os$/i]]),Ee.call(i.toString,[[U,[p,m]],[$,[g]],[G,[f,u]],[q,[p,m]],[H,[p,m]]]),i),Be=function(e,t){var r=Ne.init[t],n=Ne.isIgnore[t]||0,i=Ne.isIgnoreRgx[t]||0,o=Ne.toString[t]||0;function c(){Ee.call(this,r)}return c.prototype.getItem=function(){return e},c.prototype.withClientHints=function(){return we?we.getHighEntropyValues(V).then((function(t){return e.setCH(new Fe(t,!1)).parseCH().get()})):e.parseCH().get()},c.prototype.withFeatureCheck=function(){return e.detectFeature().get()},t!=W&&(c.prototype.is=function(e){var t=!1;for(var r in this)if(this.hasOwnProperty(r)&&!Se(n,r)&&ke(i?Oe(i,this[r]):this[r])==ke(i?Oe(i,e):e)){if(t=!0,e!=a)break}else if(e==a&&t){t=!t;break}return t},c.prototype.toString=function(){var e=s;for(var t in o)typeof this[o[t]]!==a&&(e+=(e?" ":s)+this[o[t]]);return e||a}),we||(c.prototype.then=function(e){var t=this,r=function(){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e])};r.prototype={is:c.prototype.is,toString:c.prototype.toString};var n=new r;return e(n),n}),new c};function Fe(e,t){if(e=e||{},Ee.call(this,V),t)Ee.call(this,[[k,Te(e[x])],[E,Te(e[M])],[b,/\?1/.test(e[N])],[u,Ie(e[B])],[O,Ie(e[F])],[I,Ie(e[z])],[g,Ie(e[j])],[P,Te(e[A])],[D,Ie(e[L])]]);else for(var r in e)this.hasOwnProperty(r)&&typeof e[r]!==a&&(this[r]=e[r])}function ze(e,t,r,i){return this.get=function(e){return e?this.data.hasOwnProperty(e)?this.data[e]:n: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(ye&&ye.userAgent==this.ua)switch(this.itemType){case U:ye.brave&&typeof ye.brave.isBrave==o&&this.set(p,"Brave");break;case G:!this.get(h)&&we&&we[b]&&this.set(h,b),"Macintosh"==this.get(u)&&ye&&typeof ye.standalone!==a&&ye.maxTouchPoints&&ye.maxTouchPoints>2&&this.set(u,"iPad").set(h,y);break;case H:!this.get(p)&&we&&we[O]&&this.set(p,we[O]);break;case W:var e=this.data,t=function(t){return e[t].getItem().detectFeature().get()};this.set(U,t(U)).set($,t($)).set(G,t(G)).set(q,t(q)).set(H,t(H))}return this},this.parseUA=function(){return this.itemType!=W&&xe.call(this.data,this.ua,this.rgxMap),this.itemType==U&&this.set(l,Pe(this.get(m))),this},this.parseCH=function(){var e=this.uaCH,t=this.rgxMap;switch(this.itemType){case U:var r,i=e[E]||e[k];if(i)for(var s in i){var o=Oe(/(Google|Microsoft) /,i[s].brand||i[s]),a=i[s].version;/not.a.brand/i.test(o)||r&&(!/chrom/i.test(r)||/chromi/i.test(o))||(this.set(p,o).set(m,a).set(l,Pe(a)),r=o)}break;case $:var c=e[g];c&&(c&&"64"==e[D]&&(c+="64"),xe.call(this.data,c+";",t));break;case G:if(e[b]&&this.set(h,b),e[u]&&this.set(u,e[u]),"Xbox"==e[u]&&this.set(h,v).set(f,re),e[P]){var d;if("string"!=typeof e[P])for(var y=0;!d&&y<e[P].length;)d=Me(e[P][y++],Le);else d=Me(e[P],Le);this.set(h,d)}break;case H:var w=e[O];if(w){var _=e[I];w==ve&&(_=parseInt(Pe(_),10)>=13?"11":"10"),this.set(p,w).set(m,_)}this.get(p)==ve&&"Xbox"==e[u]&&this.set(p,"Xbox").set(m,n);break;case W:var S=this.data,C=function(t){return S[t].getItem().setCH(e).parseCH().get()};this.set(U,C(U)).set($,C($)).set(G,C(G)).set(q,C(q)).set(H,C(H))}return this},Ee.call(this,[["itemType",e],["ua",t],["uaCH",i],["rgxMap",r],["data",Be(this,e)]]),this}function Ve(e,t,r){if(typeof e===c?(Ce(e,!0)?(typeof t===c&&(r=t),t=e):(r=e,t=n),e=n):typeof e!==d||Ce(t,!0)||(r=t,t=n),r&&typeof r.append===o){var i={};r.forEach((function(e,t){i[t]=e})),r=i}if(!(this instanceof Ve))return new Ve(e,t,r).getResult();var a=typeof e===d?e:r&&r[T]?r[T]:ye&&ye.userAgent?ye.userAgent:s,l=new Fe(r,!0),u=t?function(e,t){var r={},n=t;if(!Ce(t))for(var i in n={},t)for(var s in t[i])n[s]=t[i][s].concat(n[s]?n[s]:[]);for(var o in e)r[o]=n[o]&&n[o].length%2==0?n[o].concat(e[o]):e[o];return r}(Ae,t):Ae,p=function(e){return e==W?function(){return new ze(e,a,u,l).set("ua",a).set(U,this.getBrowser()).set($,this.getCPU()).set(G,this.getDevice()).set(q,this.getEngine()).set(H,this.getOS()).get()}:function(){return new ze(e,a,u[e],l).parseUA().get()}};return Ee.call(this,[["getBrowser",p(U)],["getCPU",p($)],["getDevice",p(G)],["getEngine",p(q)],["getOS",p(H)],["getResult",p(W)],["getUA",function(){return a}],["setUA",function(e){return Re(e)&&(a=e.length>500?De(e,500):e),this}]]).setUA(a),this}Ve.VERSION="2.0.0",Ve.BROWSER=_e([p,m,l,h]),Ve.CPU=_e([g]),Ve.DEVICE=_e([u,f,h,v,b,w,y,_,C]),Ve.ENGINE=Ve.OS=_e([p,m]),e.exports&&(t=e.exports=Ve),t.UAParser=Ve;var Ue=be&&(r.jQuery||r.Zepto);if(Ue&&!Ue.ua){var $e=new Ve;Ue.ua=$e.getResult(),Ue.ua.get=function(){return $e.getUA()},Ue.ua.set=function(e){$e.setUA(e);var t=$e.getResult();for(var r in t)Ue.ua[r]=t[r]}}}("object"==typeof window?window:a)}(Dn,Dn.exports);var xn=Dn.exports,Mn={},jn=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.Logger=void 0;const Ln=jn(On),An="mediasoup-client";Mn.Logger=class{constructor(e){e?(this._debug=(0,Ln.default)(`${An}:${e}`),this._warn=(0,Ln.default)(`${An}:WARN:${e}`),this._error=(0,Ln.default)(`${An}:ERROR:${e}`)):(this._debug=(0,Ln.default)(An),this._warn=(0,Ln.default)(`${An}:WARN`),this._error=(0,Ln.default)(`${An}: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 Nn,Bn={},Fn={exports:{}},zn="object"==typeof Reflect?Reflect:null,Vn=zn&&"function"==typeof zn.apply?zn.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};Nn=zn&&"function"==typeof zn.ownKeys?zn.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Un=Number.isNaN||function(e){return e!=e};function $n(){$n.init.call(this)}Fn.exports=$n,Fn.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}Zn(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Zn(e,"error",t,r)}(e,i,{once:!0})}))},$n.EventEmitter=$n,$n.prototype._events=void 0,$n.prototype._eventsCount=0,$n.prototype._maxListeners=void 0;var Gn=10;function qn(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function Hn(e){return void 0===e._maxListeners?$n.defaultMaxListeners:e._maxListeners}function Wn(e,t,r,n){var i,s,o;if(qn(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]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=Hn(e))>0&&o.length>i&&!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 Kn(){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 Jn(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=Kn.bind(n);return i.listener=r,n.wrapFn=i,i}function Qn(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]: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}(i):Yn(i,i.length)}function Xn(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 Yn(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function Zn(e,t,r,n){if("function"==typeof e.on)n.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 i(s){n.once&&e.removeEventListener(t,i),r(s)}))}}Object.defineProperty($n,"defaultMaxListeners",{enumerable:!0,get:function(){return Gn},set:function(e){if("number"!=typeof e||e<0||Un(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Gn=e}}),$n.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},$n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Un(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},$n.prototype.getMaxListeners=function(){return Hn(this)},$n.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,i=this._events;if(void 0!==i)n=n&&void 0===i.error;else if(!n)return!1;if(n){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=i[e];if(void 0===a)return!1;if("function"==typeof a)Vn(a,this,t);else{var c=a.length,d=Yn(a,c);for(r=0;r<c;++r)Vn(d[r],this,t)}return!0},$n.prototype.addListener=function(e,t){return Wn(this,e,t,!1)},$n.prototype.on=$n.prototype.addListener,$n.prototype.prependListener=function(e,t){return Wn(this,e,t,!0)},$n.prototype.once=function(e,t){return qn(t),this.on(e,Jn(this,e,t)),this},$n.prototype.prependOnceListener=function(e,t){return qn(t),this.prependListener(e,Jn(this,e,t)),this},$n.prototype.removeListener=function(e,t){var r,n,i,s,o;if(qn(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},$n.prototype.off=$n.prototype.removeListener,$n.prototype.removeAllListeners=function(e){var t,r,n;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 i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);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(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},$n.prototype.listeners=function(e){return Qn(this,e,!0)},$n.prototype.rawListeners=function(e){return Qn(this,e,!1)},$n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Xn.call(e,t)},$n.prototype.listenerCount=Xn,$n.prototype.eventNames=function(){return this._eventsCount>0?Nn(this._events):[]};var ei=Fn.exports;Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.EnhancedEventEmitter=void 0;const ti=ei,ri=new Mn.Logger("EnhancedEventEmitter");class ni extends ti.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){ri.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)}}Bn.EnhancedEventEmitter=ni;var ii={};Object.defineProperty(ii,"__esModule",{value:!0}),ii.InvalidStateError=ii.UnsupportedError=void 0;class si extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,si):this.stack=new Error(e).stack}}ii.UnsupportedError=si;class oi extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,oi):this.stack=new Error(e).stack}}ii.InvalidStateError=oi;var ai={};Object.defineProperty(ai,"__esModule",{value:!0}),ai.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},ai.generateRandomNumber=function(){return Math.round(1e7*Math.random())},ai.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var ci,di,li={},ui={},pi={},hi={exports:{}};function fi(){if(di)return ci;di=1;var e=1e3,t=60*e,r=60*t,n=24*r,i=7*n,s=365.25*n;function o(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return ci=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*i;case"days":case"day":case"d":return c*n;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(i){var s=Math.abs(i);if(s>=n)return o(i,s,n,"day");if(s>=r)return o(i,s,r,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=n)return Math.round(i/n)+"d";if(s>=r)return Math.round(i/r)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},ci}var mi=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,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,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),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:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}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.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=fi(),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 n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,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")}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;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&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$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=mi(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(hi,hi.exports);var gi=hi.exports,vi=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pi,"__esModule",{value:!0}),pi.Logger=void 0;const bi=vi(gi),yi="h264-profile-level-id";pi.Logger=class{constructor(e){e?(this._debug=(0,bi.default)(`${yi}:${e}`),this._warn=(0,bi.default)(`${yi}:WARN:${e}`),this._error=(0,bi.default)(`${yi}:ERROR:${e}`)):(this._debug=(0,bi.default)(yi),this._warn=(0,bi.default)(`${yi}:WARN`),this._error=(0,bi.default)(`${yi}: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(ui,"__esModule",{value:!0}),ui.generateProfileLevelIdStringForAnswer=ui.isSameProfile=ui.parseSdpProfileLevelId=ui.levelToString=ui.profileToString=ui.profileLevelIdToString=ui.parseProfileLevelId=ui.ProfileLevelId=ui.Level=ui.Profile=void 0;const wi=new pi.Logger;var _i,Si;!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"}(_i||(ui.Profile=_i={})),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"}(Si||(ui.Level=Si={}));class Ci{constructor(e,t){this.profile=e,this.level=t}}ui.ProfileLevelId=Ci;const Ri=new Ci(_i.ConstrainedBaseline,Si.L3_1);class Ti{constructor(e){this.mask=~Di("x",e),this.masked_value=Di("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class ki{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const Pi=[new ki(66,new Ti("x1xx0000"),_i.ConstrainedBaseline),new ki(77,new Ti("1xxx0000"),_i.ConstrainedBaseline),new ki(88,new Ti("11xx0000"),_i.ConstrainedBaseline),new ki(66,new Ti("x0xx0000"),_i.Baseline),new ki(88,new Ti("10xx0000"),_i.Baseline),new ki(77,new Ti("0x0x0000"),_i.Main),new ki(100,new Ti("00000000"),_i.High),new ki(100,new Ti("00001100"),_i.ConstrainedHigh),new ki(244,new Ti("00000000"),_i.PredictiveHigh444)];function Ei(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,n=t>>8&255,i=t>>16&255;let s;switch(r){case Si.L1_1:s=0!=(16&n)?Si.L1_b:Si.L1_1;break;case Si.L1:case Si.L1_2:case Si.L1_3:case Si.L2:case Si.L2_1:case Si.L2_2:case Si.L3:case Si.L3_1:case Si.L3_2:case Si.L4:case Si.L4_1:case Si.L4_2:case Si.L5:case Si.L5_1:case Si.L5_2:s=r;break;default:return void wi.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const e of Pi)if(i===e.profile_idc&&e.profile_iop.isMatch(n))return new Ci(e.profile,s);wi.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function Oi(e){if(e.level==Si.L1_b)switch(e.profile){case _i.ConstrainedBaseline:return"42f00b";case _i.Baseline:return"42100b";case _i.Main:return"4d100b";default:return void wi.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case _i.ConstrainedBaseline:t="42e0";break;case _i.Baseline:t="4200";break;case _i.Main:t="4d00";break;case _i.ConstrainedHigh:t="640c";break;case _i.High:t="6400";break;case _i.PredictiveHigh444:t="f400";break;default:return void wi.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function Ii(e={}){const t=e["profile-level-id"];return t?Ei(t):Ri}function Di(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)<<0}function xi(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}ui.parseProfileLevelId=Ei,ui.profileLevelIdToString=Oi,ui.profileToString=function(e){switch(e){case _i.ConstrainedBaseline:return"ConstrainedBaseline";case _i.Baseline:return"Baseline";case _i.Main:return"Main";case _i.ConstrainedHigh:return"ConstrainedHigh";case _i.High:return"High";case _i.PredictiveHigh444:return"PredictiveHigh444";default:return void wi.warn(`profileToString() | unrecognized profile ${e}`)}},ui.levelToString=function(e){switch(e){case Si.L1_b:return"1b";case Si.L1:return"1";case Si.L1_1:return"1.1";case Si.L1_2:return"1.2";case Si.L1_3:return"1.3";case Si.L2:return"2";case Si.L2_1:return"2.1";case Si.L2_2:return"2.2";case Si.L3:return"3";case Si.L3_1:return"3.1";case Si.L3_2:return"3.2";case Si.L4:return"4";case Si.L4_1:return"4.1";case Si.L4_2:return"4.2";case Si.L5:return"5";case Si.L5_1:return"5.1";case Si.L5_2:return"5.2";default:return void wi.warn(`levelToString() | unrecognized level ${e}`)}},ui.parseSdpProfileLevelId=Ii,ui.isSameProfile=function(e={},t={}){const r=Ii(e),n=Ii(t);return Boolean(r&&n&&r.profile===n.profile)},ui.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void wi.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=Ii(e),n=Ii(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==n.profile)throw new TypeError("H264 Profile mismatch");const i=xi(e)&&xi(t),s=r.level,o=n.level,a=function(e,t){return e===Si.L1_b?t!==Si.L1&&t!==Si.L1_b:t===Si.L1_b?e!==Si.L1:e<t}(c=s,d=o)?c:d;var c,d;const l=i?s:a;return wi.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${l}]`),Oi(new Ci(r.profile,l))};var Mi,ji=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Li=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ai=a&&a.__importStar||(Mi=function(e){return Mi=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},Mi(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=Mi(e),n=0;n<r.length;n++)"default"!==r[n]&&ji(t,e,r[n]);return Li(t,e),t});Object.defineProperty(li,"__esModule",{value:!0}),li.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)$i(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)qi(t)},li.validateRtpParameters=Ui,li.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")},li.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)},li.getExtendedRtpCapabilities=function(e,t){const r={codecs:[],headerExtensions:[]};for(const n of t.codecs??[]){if(Ji(n))continue;const t=(e.codecs??[]).find((e=>Qi(e,n,{strict:!0,modify:!0})));if(!t)continue;const i={mimeType:t.mimeType,kind:t.kind,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:n.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters,remoteParameters:n.parameters,rtcpFeedback:Yi(t,n)};r.codecs.push(i)}for(const n of r.codecs){const r=e.codecs.find((e=>Ji(e)&&e.parameters.apt===n.localPayloadType)),i=t.codecs.find((e=>Ji(e)&&e.parameters.apt===n.remotePayloadType));r&&i&&(n.localRtxPayloadType=r.preferredPayloadType,n.remoteRtxPayloadType=i.preferredPayloadType)}for(const n of t.headerExtensions){const t=e.headerExtensions.find((e=>Xi(e,n)));if(!t)continue;const i={kind:n.kind,uri:n.uri,sendId:t.preferredId,recvId:n.preferredId,encrypt:t.preferredEncrypt,direction:"sendrecv"};switch(n.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}r.headerExtensions.push(i)}return r},li.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 n={mimeType:`${r.kind}/rtx`,kind:r.kind,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(n)}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},li.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},li.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.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},li.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(Qi(e[n],t,{strict:!0})){r.push(e[n]),Ji(e[n+1])&&r.push(e[n+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),Ji(e[1])&&r.push(e[1]);return r},li.generateProbatorRtpParameters=function(e){Ui(e=Bi.clone(e));const t={mid:Fi,codecs:[],headerExtensions:[],encodings:[{ssrc:zi}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=Vi,t.headerExtensions=e.headerExtensions,t},li.canSend=function(e,t){return t.codecs.some((t=>t.kind===e))},li.canReceive=function(e,t){if(Ui(e),0===e.codecs.length)return!1;const r=e.codecs[0];return t.codecs.some((e=>e.remotePayloadType===r.payloadType))};const Ni=Ai(ui),Bi=Ai(ai),Fi="probator",zi=1234,Vi=127;function Ui(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)Hi(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)Wi(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)Ki(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 $i(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)Gi(t)}function Gi(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 qi(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 Hi(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)Gi(t)}function Wi(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 Ki(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 Ji(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Qi(e,t,{strict:r=!1,modify:n=!1}={}){const i=e.mimeType.toLowerCase();if(i!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(i){case"video/h264":if(r){if((e.parameters["packetization-mode"]||0)!==(t.parameters["packetization-mode"]||0))return!1;if(!Ni.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=Ni.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}n&&(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 Xi(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function Yi(e,t){const r=[];for(const n of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find((e=>e.type===n.type&&(e.parameter===n.parameter||!e.parameter&&!n.parameter)));e&&r.push(e)}return r}var Zi={},es={},ts={};Object.defineProperty(ts,"__esModule",{value:!0}),ts.Logger=void 0;const rs=gi,ns="awaitqueue";ts.Logger=class{constructor(e){e?(this._debug=(0,rs.default)(`${ns}:${e}`),this._warn=(0,rs.default)(`${ns}:WARN:${e}`),this._error=(0,rs.default)(`${ns}:ERROR:${e}`)):(this._debug=(0,rs.default)(ns),this._warn=(0,rs.default)(`${ns}:WARN`),this._error=(0,rs.default)(`${ns}: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(es,"__esModule",{value:!0}),es.AwaitQueue=es.AwaitQueueRemovedTaskError=es.AwaitQueueStoppedError=void 0;const is=new ts.Logger;class ss extends Error{constructor(e){super(e??"AwaitQueue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,ss)}}es.AwaitQueueStoppedError=ss;class os extends Error{constructor(e){super(e??"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,os)}}es.AwaitQueueRemovedTaskError=os;
|
|
1
|
+
this.whereby=this.whereby||{},this.whereby.react=function(e,t,r){"use strict";function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}function i(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 n=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}var s=n(t),o=n(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(new 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},n=e.useSyncExternalStore,i=e.useRef,s=e.useEffect,o=e.useMemo,a=e.useDebugValue;u.useSyncExternalStoreWithSelector=function(e,t,c,d,l){var u,p=i(null);null===p.current?(u={hasValue:!1,value:null},p.current=u):u=p.current;var h=o((function(){var e,n,i=!1,s=function(t){if(!i){i=!0,e=t;var s=d(t);if(void 0!==l&&u.hasValue){var o=u.value;if(l(o,s))return n=o,o}return n=s,s}var a=n;if(r(e,t))return a;var c=d(t);return void 0!==l&&l(a,c)?a:(e=t,n=c,c)},o=void 0===c?null:c;return[function(){return s(t())},null===o?void 0:function(){return s(o())}]}),[t,c,d,l]),f=h[0],m=h[1],g=n(e,f,m);return s((function(){u.hasValue=!0,u.value=g}),[g]),a(g),g},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),u);var p=l.exports,h="default"in s?s.default:s,f=Symbol.for("react-redux-context"),m="undefined"!=typeof globalThis?globalThis:{};function g(){if(!h.createContext)return{};const e=m[f]??(m[f]=new Map);let t=e.get(h.createContext);return t||(t=h.createContext(null),t.displayName="ReactRedux",e.set(h.createContext,t)),t}var v=g();function b(e=v){return function(){const t=h.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 y=b(),w=()=>{throw new Error("uSES not initialized!")},_=(e,t)=>e===t;var S={notify(){},get:()=>[]};var C=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),R="undefined"!=typeof navigator&&"ReactNative"===navigator.product,T=C||R?h.useLayoutEffect:h.useEffect;var k=function({store:e,context:t,children:r,serverState:n,stabilityCheck:i="once",identityFunctionCheck:s="once"}){const o=h.useMemo((()=>{const t=function(e,t){let r,n=S,i=0,s=!1;function o(){d.onStateChange&&d.onStateChange()}function a(){i++,r||(r=t?t.addNestedSub(o):e.subscribe(o),n=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 n=!0;const i=t={callback:r,next:null,prev:t};return i.prev?i.prev.next=i:e=i,function(){n&&null!==e&&(n=!1,i.next?i.next.prev=i.prev:t=i.prev,i.prev?i.prev.next=i.next:e=i.next)}}}}())}function c(){i--,r&&0===i&&(r(),r=void 0,n.clear(),n=S)}const d={addNestedSub:function(e){a();const t=n.subscribe(e);let r=!1;return()=>{r||(r=!0,t(),c())}},notifyNestedSubs:function(){n.notify()},handleChangeWrapper:o,isSubscribed:function(){return s},trySubscribe:function(){s||(s=!0,a())},tryUnsubscribe:function(){s&&(s=!1,c())},getListeners:()=>n};return d}(e);return{store:e,subscription:t,getServerState:n?()=>n:void 0,stabilityCheck:i,identityFunctionCheck:s}}),[e,n,i,s]),a=h.useMemo((()=>e.getState()),[e]);T((()=>{const{subscription:t}=o;return t.onStateChange=t.notifyNestedSubs,t.trySubscribe(),a!==e.getState()&&t.notifyNestedSubs(),()=>{t.tryUnsubscribe(),t.onStateChange=void 0}}),[o,a]);const c=t||v;return h.createElement(c.Provider,{value:o},r)};function P(e=v){const t=e===v?y:b(e),r=()=>{const{store:e}=t();return e};return Object.assign(r,{withTypes:()=>r}),r}var E,O=P();E=p.useSyncExternalStoreWithSelector,w=E;var I=(()=>"function"==typeof Symbol&&Symbol.observable||"@@observable")(),D=()=>Math.random().toString(36).substring(7).split("").join("."),x={INIT:`@@redux/INIT${D()}`,REPLACE:`@@redux/REPLACE${D()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${D()}`};function M(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 j(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 L(e){let t=typeof e;return t=j(e),t}function A(e,t,r){if("function"!=typeof e)throw new Error(`Expected the root reducer to be a function. Instead, received: '${L(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: '${L(r)}'`);return r(A)(e,t)}let n=e,i=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 i}function u(e){if("function"!=typeof e)throw new Error(`Expected the listener to be a function. Instead, received: '${L(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(!M(e))throw new Error(`Actions must be plain objects. Instead, the actual type was: '${L(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: '${L(e.type)}'. Value was: '${e.type}' (stringified)`);if(c)throw new Error("Reducers may not dispatch actions.");try{c=!0,i=n(i,e)}finally{c=!1}return(s=o).forEach((e=>{e()})),e}p({type:x.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: '${L(e)}`);n=e,p({type:x.REPLACE})},[I]: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: '${L(t)}'`);function r(){const e=t;e.next&&e.next(l())}r();return{unsubscribe:e(r)}},[I](){return this}}}}}function N(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}function B(e){const t=Object.keys(e),r={};for(let n=0;n<t.length;n++){const i=t[n];void 0===e[i]&&N(`No reducer provided for key "${i}"`),"function"==typeof e[i]&&(r[i]=e[i])}const n=Object.keys(r);let i,s;i={};try{!function(e){Object.keys(e).forEach((t=>{const r=e[t];if(void 0===r(void 0,{type:x.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:x.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 '${x.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 n=function(e,t,r,n){const i=Object.keys(t),s=r&&r.type===x.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(0===i.length)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!M(e))return`The ${s} has unexpected type of "${L(e)}". Expected argument to be an object with the following keys: "${i.join('", "')}"`;const o=Object.keys(e).filter((e=>!t.hasOwnProperty(e)&&!n[e]));return o.forEach((e=>{n[e]=!0})),r&&r.type===x.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: "${i.join('", "')}". Unexpected keys will be ignored.`:void 0}(e,r,t,i);n&&N(n)}let o=!1;const a={};for(let i=0;i<n.length;i++){const s=n[i],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||n.length!==Object.keys(e).length,o?a:e}}function F(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce(((e,t)=>(...r)=>e(t(...r))))}function z(e){return M(e)&&"type"in e&&"string"==typeof e.type}var V=Symbol.for("immer-nothing"),U=Symbol.for("immer-draftable"),$=Symbol.for("immer-state"),G=[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 q(e,...t){{const r=G[e],n="function"==typeof r?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}}var H=Object.getPrototypeOf;function W(e){return!!e&&!!e[$]}function K(e){return!!e&&(Q(e)||Array.isArray(e)||!!e[U]||!!e.constructor?.[U]||te(e)||re(e))}var J=Object.prototype.constructor.toString();function Q(e){if(!e||"object"!=typeof e)return!1;const t=H(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)===J}function X(e,t){0===Y(e)?Object.entries(e).forEach((([r,n])=>{t(r,n,e)})):e.forEach(((r,n)=>t(n,r,e)))}function Y(e){const t=e[$];return t?t.type_:Array.isArray(e)?1:te(e)?2:re(e)?3:0}function Z(e,t){return 2===Y(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ee(e,t,r){const n=Y(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function te(e){return e instanceof Map}function re(e){return e instanceof Set}function ne(e){return e.copy_||e.base_}function ie(e,t){if(te(e))return new Map(e);if(re(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&Q(e)){if(!H(e)){const t=Object.create(null);return Object.assign(t,e)}return{...e}}const r=Object.getOwnPropertyDescriptors(e);delete r[$];let n=Reflect.ownKeys(r);for(let t=0;t<n.length;t++){const i=n[t],s=r[i];!1===s.writable&&(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(r[i]={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[i]})}return Object.create(H(e),r)}function se(e,t=!1){return ae(e)||W(e)||!K(e)||(Y(e)>1&&(e.set=e.add=e.clear=e.delete=oe),Object.freeze(e),t&&X(e,((e,t)=>se(t,!0)))),e}function oe(){q(2)}function ae(e){return Object.isFrozen(e)}var ce,de={};function le(e){const t=de[e];return t||q(0,e),t}function ue(){return ce}function pe(e,t){t&&(le("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function he(e){fe(e),e.drafts_.forEach(ge),e.drafts_=null}function fe(e){e===ce&&(ce=e.parent_)}function me(e){return ce={drafts_:[],parent_:ce,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function ge(e){const t=e[$];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ve(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];return void 0!==e&&e!==r?(r[$].modified_&&(he(t),q(4)),K(e)&&(e=be(t,e),t.parent_||we(t,e)),t.patches_&&le("Patches").generateReplacementPatches_(r[$].base_,e,t.patches_,t.inversePatches_)):e=be(t,r,[]),he(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==V?e:void 0}function be(e,t,r){if(ae(t))return t;const n=t[$];if(!n)return X(t,((i,s)=>ye(e,n,t,i,s,r))),t;if(n.scope_!==e)return t;if(!n.modified_)return we(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let i=t,s=!1;3===n.type_&&(i=new Set(t),t.clear(),s=!0),X(i,((i,o)=>ye(e,n,t,i,o,r,s))),we(e,t,!1),r&&e.patches_&&le("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function ye(e,t,r,n,i,s,o){if(i===r&&q(5),W(i)){const o=be(e,i,s&&t&&3!==t.type_&&!Z(t.assigned_,n)?s.concat(n):void 0);if(ee(r,n,o),!W(o))return;e.canAutoFreeze_=!1}else o&&r.add(i);if(K(i)&&!ae(i)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;be(e,i),t&&t.scope_.parent_||we(e,i)}}function we(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&se(t,r)}var _e={get(e,t){if(t===$)return e;const r=ne(e);if(!Z(r,t))return function(e,t,r){const n=Re(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,r,t);const n=r[t];return e.finalized_||!K(n)?n:n===Ce(e.base_,t)?(ke(e),e.copy_[t]=Pe(n,e)):n},has:(e,t)=>t in ne(e),ownKeys:e=>Reflect.ownKeys(ne(e)),set(e,t,r){const n=Re(ne(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=Ce(ne(e),t),o=n?.[$];if(o&&o.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(((i=r)===(s=n)?0!==i||1/i==1/s:i!=i&&s!=s)&&(void 0!==r||Z(e.base_,t)))return!0;ke(e),Te(e)}var i,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!==Ce(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,ke(e),Te(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=ne(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty(){q(11)},getPrototypeOf:e=>H(e.base_),setPrototypeOf(){q(12)}},Se={};function Ce(e,t){const r=e[$];return(r?ne(r):e)[t]}function Re(e,t){if(!(t in e))return;let r=H(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=H(r)}}function Te(e){e.modified_||(e.modified_=!0,e.parent_&&Te(e.parent_))}function ke(e){e.copy_||(e.copy_=ie(e.base_,e.scope_.immer_.useStrictShallowCopy_))}X(_e,((e,t)=>{Se[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),Se.deleteProperty=function(e,t){return isNaN(parseInt(t))&&q(13),Se.set.call(this,e,t,void 0)},Se.set=function(e,t,r){return"length"!==t&&isNaN(parseInt(t))&&q(14),_e.set.call(this,e[0],t,r,e[0])};function Pe(e,t){const r=te(e)?le("MapSet").proxyMap_(e,t):re(e)?le("MapSet").proxySet_(e,t):function(e,t){const r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:ue(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let i=n,s=_e;r&&(i=[n],s=Se);const{revoke:o,proxy:a}=Proxy.revocable(i,s);return n.draft_=a,n.revoke_=o,a}(e,t);return(t?t.scope_:ue()).drafts_.push(r),r}function Ee(e){return W(e)||q(10,e),Oe(e)}function Oe(e){if(!K(e)||ae(e))return e;const t=e[$];let r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=ie(e,t.scope_.immer_.useStrictShallowCopy_)}else r=ie(e,!0);return X(r,((e,t)=>{ee(r,e,Oe(t))})),t&&(t.finalized_=!1),r}var Ie=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 n=this;return function(e=r,...i){return n.produce(e,(e=>t.call(this,e,...i)))}}let n;if("function"!=typeof t&&q(6),void 0!==r&&"function"!=typeof r&&q(7),K(e)){const i=me(this),s=Pe(e,void 0);let o=!0;try{n=t(s),o=!1}finally{o?he(i):fe(i)}return pe(i,r),ve(n,i)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===V&&(n=void 0),this.autoFreeze_&&se(n,!0),r){const t=[],i=[];le("Patches").generateReplacementPatches_(e,n,t,i),r(t,i)}return n}q(1,e)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...r)=>this.produceWithPatches(t,(t=>e(t,...r)));let r,n;return[this.produce(e,t,((e,t)=>{r=e,n=t})),r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){K(e)||q(8),W(e)&&(e=Ee(e));const t=me(this),r=Pe(e,void 0);return r[$].isManual_=!0,fe(t),r}finishDraft(e,t){const r=e&&e[$];r&&r.isManual_||q(9);const{scope_:n}=r;return pe(n,t),ve(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=le("Patches").applyPatches_;return W(e)?n(e,t):this.produce(e,(e=>n(e,t)))}},De=Ie.produce;Ie.produceWithPatches.bind(Ie),Ie.setAutoFreeze.bind(Ie),Ie.setUseStrictShallowCopy.bind(Ie),Ie.applyPatches.bind(Ie),Ie.createDraft.bind(Ie),Ie.finishDraft.bind(Ie);var xe=(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})}}},Me=(e,t,r)=>{const{memoize:n,memoizeOptions:i}=t,{inputSelectorResults:s,inputSelectorResultsCopy:o}=e,a=n((()=>({})),...i);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})}},je={inputStabilityCheck:"once",identityFunctionCheck:"once"};var Le=e=>Array.isArray(e)?e:[e];function Ae(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 Ne(e,t){const r=[],{length:n}=e;for(let i=0;i<n;i++)r.push(e[i].apply(null,t));return r}var Be="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},Fe=0,ze=1;function Ve(){return{s:Fe,v:void 0,o:null,p:null}}function Ue(e,t={}){let r=Ve();const{resultEqualityCheck:n}=t;let i,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 n=e.get(r);void 0===n?(t=Ve(),e.set(r,t)):t=n}else{let e=t.p;null===e&&(t.p=e=new Map);const n=e.get(r);void 0===n?(t=Ve(),e.set(r,t)):t=n}}const a=t;let c;if(t.s===ze?c=t.v:(c=e.apply(null,arguments),s++),a.s=ze,n){const e=i?.deref?.()??i;null!=e&&n(e,c)&&(c=e,0!==s&&s--);i="object"==typeof c&&null!==c||"function"==typeof c?new Be(c):c}return a.v=c,c}return o.clearCache=()=>{r=Ve(),o.resetResultsCount()},o.resultsCount=()=>s,o.resetResultsCount=()=>{s=0},o}function $e(e,...t){const r="function"==typeof e?{memoize:e,memoizeOptions:t}:e,n=(...e)=>{let t,n=0,i=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=Ue,argsMemoizeOptions:u=[],devModeChecks:p={}}=a,h=Le(d),f=Le(u),m=Ae(e),g=c((function(){return n++,o.apply(null,arguments)}),...h);let v=!0;const b=l((function(){i++;const e=Ne(m,arguments);t=g.apply(null,e);{const{identityFunctionCheck:r,inputStabilityCheck:n}=((e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:n}={...je,...t};return{identityFunctionCheck:{shouldRun:"always"===r||"once"===r&&e,run:xe},inputStabilityCheck:{shouldRun:"always"===n||"once"===n&&e,run:Me}}})(v,p);if(r.shouldRun&&r.run(o,e,t),n.shouldRun){const t=Ne(m,arguments);n.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:()=>i,resetDependencyRecomputations:()=>{i=0},lastResult:()=>t,recomputations:()=>n,resetRecomputations:()=>{n=0},memoize:c,argsMemoize:l})};return Object.assign(n,{withTypes:()=>n}),n}var Ge=$e(Ue),qe=Object.assign(((e,t=Ge)=>{!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),n=t(r.map((t=>e[t])),((...e)=>e.reduce(((e,t,n)=>(e[r[n]]=t,e)),{})));return n}),{withTypes:()=>qe});function He(e){return({dispatch:t,getState:r})=>n=>i=>"function"==typeof i?i(t,r,e):n(i)}var We=He(),Ke=He;((...e)=>{const t=$e(...e),r=Object.assign(((...e)=>{const r=t(...e),n=(e,...t)=>r(W(e)?Ee(e):e,...t);return Object.assign(n,r),n}),{withTypes:()=>r})})(Ue);var Je="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?F:F.apply(null,arguments)},Qe=e=>e&&"function"==typeof e.match;function Xe(e,t){function r(...r){if(t){let n=t(...r);if(!n)throw new Error("prepareAction did not return an object");return{type:e,payload:n.payload,..."meta"in n&&{meta:n.meta},..."error"in n&&{error:n.error}}}return{type:e,payload:r[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=t=>z(t)&&t.type===e,r}function Ye(e){return"function"==typeof e&&"type"in e&&Qe(e)}function Ze(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.`)}}}function et(e,t){for(const r of e)if(t(r))return r}var tt=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 rt(e){return K(e)?De(e,(()=>{})):e}function nt(e,t,r){if(e.has(t)){let n=e.get(t);return r.update&&(n=r.update(n,t,e),e.set(t,n)),n}if(!r.insert)throw new Error("No insert provided for key not already in map");const n=r.insert(t,e);return e.set(t,n),n}function it(e){return"object"!=typeof e||null==e||Object.isFrozen(e)}function st(e,t,r){const n=ot(e,t,r);return{detectMutations:()=>at(e,t,n,r)}}function ot(e,t=[],r,n="",i=new Set){const s={value:r};if(!e(r)&&!i.has(r)){i.add(r),s.children={};for(const i in r){const o=n?n+"."+i:i;t.length&&-1!==t.indexOf(o)||(s.children[i]=ot(e,t,r[i],o))}}return s}function at(e,t=[],r,n,i=!1,s=""){const o=r?r.value:void 0,a=o===n;if(i&&!a&&!Number.isNaN(n))return{wasMutated:!0,path:s};if(e(o)||e(n))return{wasMutated:!1};const c={};for(let e in r.children)c[e]=!0;for(let e in n)c[e]=!0;const d=t.length>0;for(let i in c){const o=s?s+"."+i:i;if(d){if(t.some((e=>e instanceof RegExp?e.test(o):o===e)))continue}const c=at(e,t,r.children[i],n[i],a,o);if(c.wasMutated)return c}return{wasMutated:!1}}function ct(e){const t=typeof e;return null==e||"string"===t||"boolean"===t||"number"===t||Array.isArray(e)||M(e)}function dt(e,t="",r=ct,n,i=[],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!=n?n(e):Object.entries(e),c=i.length>0;for(const[e,d]of a){const a=t?t+"."+e:e;if(c){if(i.some((e=>e instanceof RegExp?e.test(a):a===e)))continue}if(!r(d))return{keyPath:a,value:d};if("object"==typeof d&&(o=dt(d,a,r,n,i,s),o))return o}return s&<(e)&&s.add(e),!1}function lt(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if("object"==typeof t&&null!==t&&!lt(t))return!1;return!0}function ut(e){return"boolean"==typeof e}var pt=()=>function(e){const{thunk:t=!0,immutableCheck:r=!0,serializableCheck:n=!0,actionCreatorCheck:i=!0}=e??{};let s=new tt;if(t&&(ut(t)?s.push(We):s.push(Ke(t.extraArgument))),r){let e={};ut(r)||(e=r),s.unshift(function(e={}){{let t=function(e,t,n,i){return JSON.stringify(e,r(t,i),n)},r=function(e,t){let r=[],n=[];return t||(t=function(e,t){return r[0]===t?"[Circular ~]":"[Circular ~."+n.slice(0,r.indexOf(t)).join(".")+"]"}),function(i,s){if(r.length>0){var o=r.indexOf(this);~o?r.splice(o+1):r.push(this),~o?n.splice(o,1/0,i):n.push(i),~r.indexOf(s)&&(s=t.call(this,i,s))}else r.push(s);return null==e?s:e.call(this,i,s)}},{isImmutable:n=it,ignoredPaths:i,warnAfter:s=32}=e;const o=st.bind(null,n,i);return({getState:e})=>{let r,n=e(),i=o(n);return a=>c=>{const d=Ze(s,"ImmutableStateInvariantMiddleware");d.measureTime((()=>{if(n=e(),r=i.detectMutations(),i=o(n),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(n=e(),r=i.detectMutations(),i=o(n),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(n){let e={};ut(n)||(e=n),s.push(function(e={}){{const{isSerializable:t=ct,getEntries:r,ignoredActions:n=[],ignoredActionPaths:i=["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(!z(u))return d(u);const p=d(u),h=Ze(o,"SerializableStateInvariantMiddleware");return c||n.length&&-1!==n.indexOf(u.type)||h.measureTime((()=>{const e=dt(u,"",t,r,i,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 n=dt(e.getState(),"",t,r,s,l);if(n){const{keyPath:e,value:t}=n;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(i){let e={};ut(i)||(e=i),s.unshift(function(e={}){const{isActionCreator:t=Ye}=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},ht=e=>t=>{setTimeout(t,e)},ft="undefined"!=typeof window&&window.requestAnimationFrame?window.requestAnimationFrame:ht(10),mt=e=>function(t){const{autoBatch:r=!0}=t??{};let n=new tt(e);return r&&n.push(((e={type:"raf"})=>t=>(...r)=>{const n=t(...r);let i=!0,s=!1,o=!1;const a=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?ft:"callback"===e.type?e.queueNotification:ht(e.timeout),d=()=>{o=!1,s&&(s=!1,a.forEach((e=>e())))};return Object.assign({},n,{subscribe(e){const t=n.subscribe((()=>i&&e()));return a.add(e),()=>{t(),a.delete(e)}},dispatch(e){try{return i=!e?.meta?.RTK_autoBatch,s=!i,s&&(o||(o=!0,c(d))),n.dispatch(e)}finally{i=!0}}})})("object"==typeof r?r:void 0)),n};function gt(e){const t=pt(),{reducer:r,middleware:n,devTools:i=!0,preloadedState:s,enhancers:o}=e||{};let a,c;if("function"==typeof r)a=r;else{if(!M(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");a=B(r)}if(n&&"function"!=typeof n)throw new Error("`middleware` field must be a callback");if("function"==typeof n){if(c=n(t),!Array.isArray(c))throw new Error("when using a middleware builder function, an array of middleware must be returned")}else c=t();if(c.some((e=>"function"!=typeof e)))throw new Error("each middleware provided to configureStore must be a function");let d=F;i&&(d=Je({trace:!0,..."object"==typeof i&&i}));const l=function(...e){return t=>(r,n)=>{const i=t(r,n);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:i.getState,dispatch:(e,...t)=>s(e,...t)},a=e.map((e=>e(o)));return s=F(...a)(i.dispatch),{...i,dispatch:s}}}(...c),u=mt(l);if(o&&"function"!=typeof o)throw new Error("`enhancers` field must be a callback");let p="function"==typeof o?o(u):u();if(!Array.isArray(p))throw new Error("`enhancers` callback must return an array");if(p.some((e=>"function"!=typeof e)))throw new Error("each enhancer provided to configureStore must be a function");c.length&&!p.includes(l)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");return A(a,s,d(...p))}function vt(e){const t={},r=[];let n;const i={addCase(e,s){if(r.length>0)throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");if(n)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,i},addMatcher(e,t){if(n)throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:e,reducer:t}),i},addDefaultCase(e){if(n)throw new Error("`builder.addDefaultCase` can only be called once");return n=e,i}};return e(i),[t,r,n]}var bt=(e=21)=>{let t="",r=e;for(;r--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t};function yt(...e){return t=>e.some((e=>((e,t)=>Qe(e)?e.match(t):e(t))(e,t)))}var wt=["name","message","stack","code"],_t=class{constructor(e,t){this.payload=e,this.meta=t}_type},St=class{constructor(e,t){this.payload=e,this.meta=t}_type},Ct=e=>{if("object"==typeof e&&null!==e){const t={};for(const r of wt)"string"==typeof e[r]&&(t[r]=e[r]);return t}return{message:String(e)}},Rt=(()=>{function e(e,t,r){const n=Xe(e+"/fulfilled",((e,t,r,n)=>({payload:e,meta:{...n||{},arg:r,requestId:t,requestStatus:"fulfilled"}}))),i=Xe(e+"/pending",((e,t,r)=>({payload:void 0,meta:{...r||{},arg:t,requestId:e,requestStatus:"pending"}}))),s=Xe(e+"/rejected",((e,t,n,i,s)=>({payload:i,error:(r&&r.serializeError||Ct)(e||"Rejected"),meta:{...s||{},arg:n,requestId:t,rejectedWithValue:!!i,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}})));return Object.assign((function(e){return(o,a,c)=>{const d=r?.idGenerator?r.idGenerator(e):bt(),l=new AbortController;let u,p;function h(e){p=e,l.abort()}const f=async function(){let f;try{let s=r?.condition?.(e,{getState:a,extra:c});if(function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(s)&&(s=await s),!1===s||l.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise(((e,t)=>{u=()=>{t({name:"AbortError",message:p||"Aborted"})},l.signal.addEventListener("abort",u)}));o(i(d,e,r?.getPendingMeta?.({requestId:d,arg:e},{getState:a,extra:c}))),f=await Promise.race([m,Promise.resolve(t(e,{dispatch:o,getState:a,extra:c,requestId:d,signal:l.signal,abort:h,rejectWithValue:(e,t)=>new _t(e,t),fulfillWithValue:(e,t)=>new St(e,t)})).then((t=>{if(t instanceof _t)throw t;return t instanceof St?n(t.payload,d,e,t.meta):n(t,d,e)}))])}catch(t){f=t instanceof _t?s(null,d,e,t.payload,t.meta):s(t,d,e)}finally{u&&l.signal.removeEventListener("abort",u)}return r&&!r.dispatchConditionRejection&&s.match(f)&&f.meta.condition||o(f),f}();return Object.assign(f,{abort:h,requestId:d,arg:e,unwrap:()=>f.then(Tt)})}}),{pending:i,rejected:s,fulfilled:n,settled:yt(s,n),typePrefix:e})}return e.withTypes=()=>e,e})();function Tt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var kt=Symbol.for("rtk-slice-createasyncthunk");function Pt(e,t){return`${e}/${t}`}function Et({creators:e}={}){const t=e?.asyncThunk?.[kt];return function(e){const{name:r,reducerPath:n=r}=e;if(!r)throw new Error("`name` is a required option for createSlice");const i=("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(i),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=[],n]="function"==typeof e.extraReducers?vt(e.extraReducers):[e.extraReducers],i={...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,[n,i,s]=vt(t);if("function"==typeof e)r=()=>rt(e());else{const t=rt(e);r=()=>t}function o(e=r(),t){let o=[n[t.type],...i.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(W(e)){const n=r(e,t);return void 0===n?e:n}if(K(e))return De(e,(e=>r(e,t)));{const n=r(e,t);if(void 0===n){if(null===e)return e;throw new Error("A case reducer on a non-draftable value must not return undefined")}return n}}return e}),e)}return o.getInitialState=r,o}(e.initialState,(e=>{for(let t in i)e.addCase(t,i[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of r)e.addMatcher(t.matcher,t.reducer);n&&e.addDefaultCase(n)}))}s.forEach((n=>{const s=i[n],o={reducerName:n,type:Pt(r,n),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(s)?function({type:e,reducerName:t,createNotation:r},n,i){let s,o;if("reducer"in n){if(r&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(n))throw new Error("Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");s=n.reducer,o=n.prepare}else s=n;i.addCase(e,s).exposeCaseReducer(t,s).exposeAction(t,o?Xe(e,o):Xe(e))}(o,s,a):function({type:e,reducerName:t},r,n,i){if(!i)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=i(e,s,l);n.exposeAction(t,u),o&&n.addCase(u.fulfilled,o);a&&n.addCase(u.pending,a);c&&n.addCase(u.rejected,c);d&&n.addMatcher(u.settled,d);n.exposeCaseReducer(t,{fulfilled:o||Dt,pending:a||Dt,rejected:c||Dt,settled:d||Dt})}(o,s,a,t)}));const d=e=>e,l=new Map;let u;function p(e,t){return u||(u=c()),u(e,t)}function h(){return u||(u=c()),u.getInitialState()}function f(t,r=!1){function n(e){let n=e[t];if(void 0===n){if(!r)throw new Error("selectSlice returned undefined for an uninjected slice reducer");n=h()}return n}function i(t=d){const n=nt(l,r,{insert:()=>new WeakMap});return nt(n,t,{insert:()=>{const n={};for(const[i,s]of Object.entries(e.selectors??{}))n[i]=Ot(s,t,h,r);return n}})}return{reducerPath:t,getSelectors:i,get selectors(){return i(n)},selectSlice:n}}const m={name:r,reducer:p,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:h,...f(n),injectInto(e,{reducerPath:t,...r}={}){const i=t??n;return e.inject({reducerPath:i,reducer:p},r),{...m,...f(i,!0)}}};return m}}function Ot(e,t,r,n){function i(i,...s){let o=t(i);if(void 0===o){if(!n)throw new Error("selectState returned undefined for an uninjected slice reducer");o=r()}return e(o,...s)}return i.unwrapped=e,i}var It=Et();function Dt(){}var xt="listener",Mt="completed",jt="cancelled",Lt=`task-${jt}`,At=`task-${Mt}`,Nt=`${xt}-${jt}`,Bt=`${xt}-${Mt}`,Ft=class{constructor(e){this.code=e,this.message=`task ${jt} (reason: ${e})`}name="TaskAbortError";message},zt=(e,t)=>{if("function"!=typeof e)throw new Error(`${t} is not a function`)},Vt=()=>{},Ut=(e,t=Vt)=>(e.catch(t),e),$t=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Gt=(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))},qt=e=>{if(e.aborted){const{reason:t}=e;throw new Ft(t)}};function Ht(e,t){let r=Vt;return new Promise(((n,i)=>{const s=()=>i(new Ft(e.reason));e.aborted?s():(r=$t(e,s),t.finally((()=>r())).then(n,i))})).finally((()=>{r=Vt}))}var Wt=e=>t=>Ut(Ht(e,t).then((t=>(qt(e),t)))),Kt=e=>{const t=Wt(e);return e=>t(new Promise((t=>setTimeout(t,e))))},{assign:Jt}=Object,Qt={},Xt="listenerMiddleware",Yt=(e,t)=>(r,n)=>{zt(r,"taskExecutor");const i=new AbortController;var s;s=i,$t(e,(()=>Gt(s,e.reason)));const o=(async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof Ft?"cancelled":"rejected",error:e}}finally{t?.()}})((async()=>{qt(e),qt(i.signal);const t=await r({pause:Wt(i.signal),delay:Kt(i.signal),signal:i.signal});return qt(i.signal),t}),(()=>Gt(i,At)));return n?.autoJoin&&t.push(o.catch(Vt)),{result:Wt(e)(o),cancel(){Gt(i,Lt)}}},Zt=(e,t)=>(r,n)=>Ut((async(r,n)=>{qt(t);let i=()=>{};const s=[new Promise(((t,n)=>{let s=e({predicate:r,effect:(e,r)=>{r.unsubscribe(),t([e,r.getState(),r.getOriginalState()])}});i=()=>{s(),n()}}))];null!=n&&s.push(new Promise((e=>setTimeout(e,n,null))));try{const e=await Ht(t,Promise.race(s));return qt(t),e}finally{i()}})(r,n)),er=e=>{let{type:t,actionCreator:r,matcher:n,predicate:i,effect:s}=e;if(t)i=Xe(t).match;else if(r)t=r.type,i=r.match;else if(n)i=n;else if(!i)throw new Error("Creating or removing a listener requires one of the known fields for matching an action");return zt(s,"options.listener"),{predicate:i,type:t,effect:s}},tr=Object.assign((e=>{const{type:t,predicate:r,effect:n}=er(e);return{id:bt(),effect:n,type:t,predicate:r,pending:new Set,unsubscribe:()=>{throw new Error("Unsubscribe not initialized")}}}),{withTypes:()=>tr}),rr=e=>{e.pending.forEach((e=>{Gt(e,Nt)}))},nr=(e,t,r)=>{try{e(t,r)}catch(e){setTimeout((()=>{throw e}),0)}},ir=Object.assign(Xe(`${Xt}/add`),{withTypes:()=>ir}),sr=Xe(`${Xt}/removeAll`),or=Object.assign(Xe(`${Xt}/remove`),{withTypes:()=>or}),ar=(...e)=>{console.error(`${Xt}/error`,...e)};let cr=!0,dr=!0;function lr(e,t,r){const n=e.match(t);return n&&n.length>=r&&parseInt(n[r],10)}function ur(e,t,r){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return i.apply(this,arguments);const s=e=>{const t=r(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),i.apply(this,[e,s])};const s=n.removeEventListener;n.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 n=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,n])},Object.defineProperty(n,"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 pr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(cr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function hr(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(dr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function fr(){if("object"==typeof window){if(cr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function mr(e,t){dr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function gr(e){return"[object Object]"===Object.prototype.toString.call(e)}function vr(e){return gr(e)?Object.keys(e).reduce((function(t,r){const n=gr(e[r]),i=n?vr(e[r]):e[r],s=n&&!Object.keys(i).length;return void 0===i||s?t:Object.assign(t,{[r]:i})}),{}):e}function br(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?br(e,e.get(t[n]),r):n.endsWith("Ids")&&t[n].forEach((t=>{br(e,e.get(t),r)}))})))}function yr(e,t,r){const n=r?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===n&&r.trackId===t.id&&br(e,r,i)}))})),i}const wr=fr;function _r(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const n=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 n="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[i("min",r)]=n.ideal,t.optional.push(e),e={},e[i("max",r)]=n.ideal,t.optional.push(e)):(e[i("",r)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",r)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,r)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(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=n(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=n(e.video),wr("chrome: "+JSON.stringify(e)),i(e)}))}e.video=n(e.video)}return wr("chrome: "+JSON.stringify(e)),i(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,n){i(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{n&&n(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return i(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 Sr(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Cr(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 n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const i=new Event("track");i.track=r.track,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)})),t.stream.getTracks().forEach((r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const i=new Event("track");i.track=r,i.receiver=n,i.transceiver={receiver:n},i.streams=[t.stream],this.dispatchEvent(i)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else ur(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Rr(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,n){let i=r.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.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 n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.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 Tr(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=>yr(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}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>yr(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,n;return this.getSenders().forEach((r=>{r.track===e&&(t?n=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?n=!0:r=t),t.track===e))),n||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 kr(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 n=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(n)&&this._shimmedLocalStreams[r.id].push(n):this._shimmedLocalStreams[r.id]=[r,n],n};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 n=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const i=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]})),i.apply(this,arguments)}}function Pr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return kr(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 n=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}n.apply(this,[t])};const i=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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 n=[].slice.call(arguments,1);if(1!==n.length||!n[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 i=this._streams[r.id];if(i)i.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[r.id]=n,this._reverseStreams[n.id]=r,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],n={[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]=n[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 n=e._reverseStreams[t],i=e._streams[n.id];r=r.replace(new RegExp(n.id,"g"),i.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 Er(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],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Or(e,t){ur(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Ir=Object.freeze({__proto__:null,fixNegotiationNeeded:Or,shimAddTrackRemoveTrack:Pr,shimAddTrackRemoveTrackWithNative:kr,shimGetSendersWithDtmf:Rr,shimGetUserMedia:_r,shimMediaStream:Sr,shimOnTrack:Cr,shimPeerConnection:Er,shimSenderReceiverGetStats:Tr});function Dr(e,t){const r=e&&e.navigator,n=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,n){mr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,n)},!(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)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.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 xr(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 Mr(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],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,s]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!i)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(i,s)}}function jr(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 Lr(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}),ur(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ar(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){mr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Nr(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Br(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 n=t.apply(this,arguments);if(r){const{sender:t}=n,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 n})}function Fr(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 zr(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 Vr(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 Ur=Object.freeze({__proto__:null,shimAddTransceiver:Br,shimCreateAnswer:Vr,shimCreateOffer:zr,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:Fr,shimGetUserMedia:Dr,shimOnTrack:xr,shimPeerConnection:Mr,shimRTCDataChannel:Nr,shimReceiverGetStats:Lr,shimRemoveStream:Ar,shimSenderGetStats:jr});function $r(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 Gr(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 qr(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,n=t.createAnswer,i=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};let a=function(e,t,r){const n=i.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,r){const n=s.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,r){const n=o.apply(this,[e]);return r?(n.then(t,r),Promise.resolve()):n},t.addIceCandidate=a}function Hr(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(Wr(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,n){t.mediaDevices.getUserMedia(e).then(r,n)}.bind(t))}function Wr(e){return e&&void 0!==e.video?Object.assign({},e,{video:vr(e.video)}):e}function Kr(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 n=e.iceServers[r];void 0===n.urls&&n.url?(mr("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):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 Jr(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 Qr(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 Xr(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Yr=Object.freeze({__proto__:null,shimAudioContext:Xr,shimCallbacksAPI:qr,shimConstraints:Wr,shimCreateOfferLegacy:Qr,shimGetUserMedia:Hr,shimLocalStreamsAPI:$r,shimRTCIceServerUrls:Kr,shimRemoteStreamsAPI:Gr,shimTrackEventTransceiver:Jr}),Zr={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 n=e.type;return t.push("typ"),t.push(n),"host"!==n&&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 n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)r=n[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 n=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)})),t+="a=fmtp:"+r+" "+n.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)},n=e.indexOf(":",t);return n>-1?(r.attribute=e.substring(t+1,n),r.value=e.substring(n+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 n=t.matchPrefix(e+r,"a=ice-ufrag:")[0],i=t.matchPrefix(e+r,"a=ice-pwd:")[0];return n&&i?{usernameFragment:n.substring(12),password:i.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:[]},n=t.splitLines(e)[0].split(" ");r.profile=n[2];for(let i=3;i<n.length;i++){const s=n[i],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),i=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=i.length?t.parseFmtp(i[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{r.headerExtensions.push(t.parseExtmap(e))}));const i=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach((e=>{i.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 n="";n+="m="+e+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let i=0;return r.codecs.forEach((e=>{e.maxptime>i&&(i=e.maxptime)})),i>0&&(n+="a=maxptime:"+i+"\r\n"),r.headerExtensions&&r.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const r=[],n=t.parseRtpParameters(e),i=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.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]),n.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),i&&(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={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const i=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=i.length>0,r.compound=0===i.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 n=t.matchPrefix(e,"a=msid:");if(1===n.length)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return i.length>0?(r=i[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(e){const r=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let i;n.length>0&&(i=parseInt(n[0].substring(19),10)),isNaN(i)&&(i=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:i};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:i}}},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,n){let i;const s=void 0!==r?r:2;i=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+i+" "+s+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,r){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[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}(Zr);var en=Zr.exports,tn=c(en),rn=i({__proto__:null,default:tn},[en]);function nn(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),n=tn.parseCandidate(e.candidate);for(const e in n)e in r||Object.defineProperty(r,e,{value:n[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,ur(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function sn(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||ur(e,"icecandidate",(e=>{if(e.candidate){const t=tn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function on(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=tn.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=tn.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),n=function(e,r){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const i=tn.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?n=parseInt(i[0].substring(19),10):"firefox"===t.browser&&-1!==r&&(n=2147483637),n}(arguments[0],e);let i;i=0===r&&0===n?Number.POSITIVE_INFINITY:0===r||0===n?Math.max(r,n):Math.min(r,n);const s={};Object.defineProperty(s,"maxMessageSize",{get:()=>i}),this._sctp=s}return r.apply(this,arguments)}}function an(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const n=arguments[0],i=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&i>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},ur(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function cn(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 dn(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)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 ln(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 un(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 pn=Object.freeze({__proto__:null,removeExtmapAllowMixed:dn,shimAddIceCandidateNullOrEmpty:ln,shimConnectionState:cn,shimMaxMessageSize:on,shimParameterlessSetLocalDescription:un,shimRTCIceCandidate:nn,shimRTCIceCandidateRelayProtocol:sn,shimSendThrowTypeError:an});const hn=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const r=fr,n=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=lr(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=lr(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=lr(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),i={browserDetails:n,commonShim:pn,extractVersion:lr,disableLog:pr,disableWarnings:hr,sdp:rn};switch(n.browser){case"chrome":if(!Ir||!Er||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),i;if(null===n.version)return r("Chrome shim can not determine version, not shimming."),i;r("adapter.js shimming chrome."),i.browserShim=Ir,ln(e,n),un(e),_r(e,n),Sr(e),Er(e,n),Cr(e),Pr(e,n),Rr(e),Tr(e),Or(e,n),nn(e),sn(e),cn(e),on(e,n),an(e),dn(e,n);break;case"firefox":if(!Ur||!Mr||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),i;r("adapter.js shimming firefox."),i.browserShim=Ur,ln(e,n),un(e),Dr(e,n),Mr(e,n),xr(e),Ar(e),jr(e),Lr(e),Nr(e),Br(e),Fr(e),zr(e),Vr(e),nn(e),cn(e),on(e,n),an(e);break;case"safari":if(!Yr||!t.shimSafari)return r("Safari shim is not included in this adapter release."),i;r("adapter.js shimming safari."),i.browserShim=Yr,ln(e,n),un(e),Kr(e),Qr(e),qr(e),$r(e),Gr(e),Jr(e),Hr(e),Xr(e),nn(e),sn(e),on(e,n),an(e),dn(e,n);break;default:r("Unsupported browser!")}return i}({window:"undefined"==typeof window?void 0:window});function fn(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 mn=function(e,t,r){var n=0,i=!!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_"+n++;d.__rtcStatsId=l,r||(r={nullConfig:!0}),((r=JSON.parse(JSON.stringify(r)))&&r.iceServers||[]).forEach((function(e){delete e.credential})),r.browserType=i?"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),n=JSON.parse(JSON.stringify(r));e("getstats",l,function(e,t){t=JSON.parse(JSON.stringify(t)),Object.keys(t).forEach((function(r){var n=t[r];delete n.id,e[r]&&Object.keys(n).forEach((function(i){n[i]===e[r][i]&&delete t[r][i],(0===Object.keys(n).length||1===Object.keys(n).length&&n.timestamp)&&delete t[r]}))}));var r=-1/0;return Object.keys(t).forEach((function(e){var n=t[e];n.timestamp>r&&(r=n.timestamp)})),Object.keys(t).forEach((function(e){var n=t[e];n.timestamp===r&&(n.timestamp=0)})),t.timestamp=r,t}(o[l]||{},r)),o[l]=n}))};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 n=arguments[0],i=n.getTracks().map((function(e){return e.kind+":"+e.id})).join(",");return e(t,this.__rtcStatsId,n.id+" "+i),r.apply(this,arguments)})})),["addTrack"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n=arguments[0],i=[].slice.call(arguments,1);return e(t,this.__rtcStatsId,n.kind+":"+n.id+" "+(i.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 n=arguments[0].track;return e(t,this.__rtcStatsId,n?n.kind+":"+n.id:"null"),r.apply(this,arguments)})})),["createOffer","createAnswer"].forEach((function(t){var r=a.prototype[t];r&&(a.prototype[t]=function(){var n,i=this.__rtcStatsId,s=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?n=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(n=arguments[2]),e(t,this.__rtcStatsId,n),r.apply(this,n?[n]:void 0).then((function(r){if(e(t+"OnSuccess",i,r),!(s.length>0&&"function"==typeof s[0]))return r;s[0].apply(null,[r])}),(function(r){if(e(t+"OnFailure",i,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 n=this.__rtcStatsId,i=arguments;return e(t,this.__rtcStatsId,i[0]),r.apply(this,[i[0]]).then((function(){e(t+"OnSuccess",n,void 0),i.length>=2&&"function"==typeof i[1]&&i[1].apply(null,[])}),(function(r){if(e(t+"OnFailure",n,r.toString()),!(i.length>=3&&"function"==typeof i[2]))throw r;i[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 n=navigator[r].bind(navigator);navigator[r]=function(){e("getUserMedia",null,arguments[0]);var t=arguments[1],r=arguments[2];n(arguments[0],(function(r){e("getUserMediaOnSuccess",null,fn(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,fn(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,fn(t)),t}),(function(t){return e("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))}.bind(navigator.mediaDevices)}return{resetDelta(){o={}}}},gn=c(mn);let vn;const bn=new Uint8Array(16);function yn(){if(!vn&&(vn="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!vn))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vn(bn)}const wn=[];for(let oO=0;oO<256;++oO)wn.push((oO+256).toString(16).slice(1));var _n={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Sn(e,t,r){if(_n.randomUUID&&!t&&!e)return _n.randomUUID();const n=(e=e||{}).random||(e.rng||yn)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return wn[e[t+0]]+wn[e[t+1]]+wn[e[t+2]]+wn[e[t+3]]+"-"+wn[e[t+4]]+wn[e[t+5]]+"-"+wn[e[t+6]]+wn[e[t+7]]+"-"+wn[e[t+8]]+wn[e[t+9]]+"-"+wn[e[t+10]]+wn[e[t+11]]+wn[e[t+12]]+wn[e[t+13]]+wn[e[t+14]]+wn[e[t+15]]}(n)}var Cn={},Rn={exports:{}},Tn=Rn.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(Tn).forEach((function(e){Tn[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var kn=Rn.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=kn,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[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=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+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,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(Cn);var Pn=kn,En=/%[sdv%]/g,On=function(e){var t=1,r=arguments,n=r.length;return e.replace(En,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},In=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return On.apply(null,n)},Dn=["v","o","s","i","u","e","p","c","b","t","r","z","a"],xn=["i","c","b","a"],Mn=Cn,jn=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||Dn,n=t.innerOrder||xn,i=[];return r.forEach((function(t){Pn[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(In(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(In(t,r,e))}))}))})),e.media.forEach((function(e){i.push(In("m",Pn.m[0],e)),n.forEach((function(t){Pn[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(In(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(In(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},Ln=jn,An=Mn.parse,Nn={},Bn={},Fn={};Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.isCorrect=Fn.isInSubnet=void 0,Fn.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},Fn.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var zn={};Object.defineProperty(zn,"__esModule",{value:!0}),zn.RE_SUBNET_STRING=zn.RE_ADDRESS=zn.GROUPS=zn.BITS=void 0,zn.BITS=32,zn.GROUPS=4,zn.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,zn.RE_SUBNET_STRING=/\/\d{1,2}$/;var Vn={};Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.AddressError=void 0;class Un extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}Vn.AddressError=Un;var $n,Gn={exports:{}};$n=Gn,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 n="undefined"!=typeof navigator;n&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,n,i,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;i=((c=o*c+((32767&l)<<15)+r[n]+(1073741823&i))>>>30)+(l>>>15)+a*d+(i>>>30),r[n++]=1073741823&c}return i},e=30):n&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this[e++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=67108863&o}return i},e=26):(t.prototype.am=function(e,t,r,n,i,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;i=((c=o*c+((16383&l)<<14)+r[n]+i)>>28)+(l>>14)+a*d,r[n++]=268435455&c}return i},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 i,s,o="0123456789abcdefghijklmnopqrstuvwxyz",a=new Array;for(i="0".charCodeAt(0),s=0;s<=9;++s)a[i++]=s;for(i="a".charCodeAt(0),s=10;s<36;++s)a[i++]=s;for(i="A".charCodeAt(0),s=10;s<36;++s)a[i++]=s;function c(e){return o.charAt(e)}function d(e,t){var r=a[e.charCodeAt(t)];return null==r?-1:r}function l(e){var t=r();return t.fromInt(e),t}function u(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 p(e){this.m=e}function h(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 f(e,t){return e&t}function m(e,t){return e|t}function g(e,t){return e^t}function v(e,t){return e&~t}function b(e){if(0==e)return-1;var t=0;return 0==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function y(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function w(){}function _(e){return e}function S(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}p.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},p.prototype.revert=function(e){return e},p.prototype.reduce=function(e){e.divRemTo(this.m,null,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)},h.prototype.convert=function(e){var n=r();return e.abs().dlShiftTo(this.m.t,n),n.divRemTo(this.m,null,n),e.s<0&&n.compareTo(t.ZERO)>0&&this.m.subTo(n,n),n},h.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},h.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],n=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,n,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)},h.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},h.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 n;if(16==r)n=4;else if(8==r)n=3;else if(256==r)n=8;else if(2==r)n=1;else if(32==r)n=5;else{if(4!=r)return void this.fromRadix(e,r);n=2}this.t=0,this.s=0;for(var i=e.length,s=!1,o=0;--i>=0;){var a=8==n?255&e[i]:d(e,i);a<0?"-"==e.charAt(i)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+n>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+=n)>=this.DB&&(o-=this.DB))}8==n&&0!=(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,n=e%this.DB,i=this.DB-n,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>i|a,a=(this[r]&s)<<n;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 n=e%this.DB,i=this.DB-n,s=(1<<n)-1;t[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<i,t[o-r]=this[o]>>n;n>0&&(t[this.t-r-1]|=(this.s&s)<<i),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]-e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e[r],t[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var n=this.abs(),i=e.abs(),s=n.t;for(r.t=s+i.t;--s>=0;)r[s]=0;for(s=0;s<i.t;++s)r[s+n.t]=n.am(0,i[s],r,s,0,n.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 n=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,n,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,n,i){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=n&&n.fromInt(0),void(null!=i&&this.copyTo(i));null==i&&(i=r());var a=r(),c=this.s,d=e.s,l=this.DB-u(s[s.t-1]);l>0?(s.lShiftTo(l,a),o.lShiftTo(l,i)):(s.copyTo(a),o.copyTo(i));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=i.t,y=b-p,w=null==n?r():n;for(a.dlShiftTo(y,w),i.compareTo(w)>=0&&(i[i.t++]=1,i.subTo(w,i)),t.ONE.dlShiftTo(p,w),w.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var _=i[--b]==h?this.DM:Math.floor(i[b]*m+(i[b-1]+v)*g);if((i[b]+=a.am(0,_,i,y,0,p))<_)for(a.dlShiftTo(y,w),i.subTo(w,i);i[b]<--_;)i.subTo(w,i)}null!=n&&(i.drShiftTo(p,n),c!=d&&t.ZERO.subTo(n,n)),i.t=p,i.clamp(),l>0&&i.rShiftTo(l,i),c<0&&t.ZERO.subTo(i,i)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(0==(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,n){if(e>4294967295||e<1)return t.ONE;var i=r(),s=r(),o=n.convert(this),a=u(e)-1;for(o.copyTo(i);--a>=0;)if(n.sqrTo(i,s),(e&1<<a)>0)n.mulTo(s,o,i);else{var c=i;i=s,s=c}return n.revert(i)},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,n=(1<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(r=this[o]>>a)>0&&(i=!0,s=c(r));o>=0;)a<t?(r=(this[o]&(1<<a)-1)<<t-a,r|=this[--o]>>(a+=this.DB-t)):(r=this[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=c(r));return i?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)+u(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var n=r();return this.abs().divRemTo(e,null,n),this.s<0&&n.compareTo(t.ZERO)>0&&e.subTo(n,n),n},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new p(t):new h(t),this.exp(e,r)},t.ZERO=l(0),t.ONE=l(1),w.prototype.convert=_,w.prototype.revert=_,w.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},w.prototype.sqrTo=function(e,t){e.squareTo(t)},S.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},S.prototype.revert=function(e){return e},S.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)},S.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},S.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var C,R,T,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],P=(1<<26)/k[k.length-1];function E(){var e;e=(new Date).getTime(),R[T++]^=255&e,R[T++]^=e>>8&255,R[T++]^=e>>16&255,R[T++]^=e>>24&255,T>=L&&(T-=L)}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),n=Math.pow(e,t),i=l(n),s=r(),o=r(),a="";for(this.divRemTo(i,s,o);s.signum()>0;)a=(n+o.intValue()).toString(e).substr(1)+a,s.divRemTo(i,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var n=this.chunkSize(r),i=Math.pow(r,n),s=!1,o=0,a=0,c=0;c<e.length;++c){var l=d(e,c);l<0?"-"==e.charAt(c)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=n&&(this.dMultiply(i),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,n){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,n),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),m,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 i=new Array,s=7&e;i.length=1+(e>>3),r.nextBytes(i),s>0?i[0]&=(1<<s)-1:i[0]=0,this.fromString(i,256)}},t.prototype.bitwiseTo=function(e,t,r){var n,i,s=Math.min(e.t,this.t);for(n=0;n<s;++n)r[n]=t(this[n],e[n]);if(e.t<this.t){for(i=e.s&this.DM,n=s;n<this.t;++n)r[n]=t(this[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<e.t;++n)r[n]=t(i,e[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var n=t.ONE.shiftLeft(e);return this.bitwiseTo(n,r,n),n},t.prototype.addTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]+e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e[r],t[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),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 n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i<n;++i)r[i+this.t]=this.am(0,e[i],r,i,0,this.t);for(n=Math.min(e.t,t);i<n;++i)this.am(0,e[i],r,i,0,t-i);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r[this.t+n-t]=this.am(t-n,e[n],r,0,0,this.t+n-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 n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r},t.prototype.millerRabin=function(e){var n=this.subtract(t.ONE),i=n.getLowestSetBit();if(i<=0)return!1;var s=n.shiftRight(i);(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(n)){for(var d=1;d++<i&&0!=c.compareTo(n);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(n))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,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n<this.DB&&(r=this[e]>>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<<this.DB-n);e>=0;)n<8?(r=(this[e]&(1<<n)-1)<<8-n,r|=this[--e]>>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=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,f,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,v,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+b(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+=y(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:0!=(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,m)},t.prototype.clearBit=function(e){return this.changeBit(e,v)},t.prototype.flipBit=function(e){return this.changeBit(e,g)},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(),n=r();return this.divRemTo(e,t,n),new Array(t,n)},t.prototype.modPow=function(e,t){var n,i,s=e.bitLength(),o=l(1);if(s<=0)return o;n=s<18?1:s<48?3:s<144?4:s<768?5:6,i=s<8?new p(t):t.isEven()?new S(t):new h(t);var a=new Array,c=3,d=n-1,f=(1<<n)-1;if(a[1]=i.convert(this),n>1){var m=r();for(i.sqrTo(a[1],m);c<=f;)a[c]=r(),i.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,w=r();for(s=u(e[b])-1;b>=0;){for(s>=d?g=e[b]>>s-d&f:(g=(e[b]&(1<<s+1)-1)<<d-s,b>0&&(g|=e[b-1]>>this.DB+s-d)),c=n;0==(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)i.sqrTo(o,w),i.sqrTo(w,o),c-=2;c>0?i.sqrTo(o,w):(v=o,o=w,w=v),i.mulTo(w,a[g],o)}for(;b>=0&&0==(e[b]&1<<s);)i.sqrTo(o,w),v=o,o=w,w=v,--s<0&&(s=this.DB-1,--b)}return i.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var n=e.clone(),i=this.clone(),s=l(1),o=l(0),a=l(0),c=l(1);0!=n.signum();){for(;n.isEven();)n.rShiftTo(1,n),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(;i.isEven();)i.rShiftTo(1,i),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);n.compareTo(i)>=0?(n.subTo(i,n),r&&s.subTo(a,s),o.subTo(c,o)):(i.subTo(n,i),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=i.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 w)},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 n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,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 n=k[t],i=t+1;i<k.length&&n<P;)n*=k[i++];for(n=r.modInt(n);t<i;)if(n%k[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=S,null==R){var O;if(R=new Array,T=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var I=new Uint8Array(32);for(window.crypto.getRandomValues(I),O=0;O<32;++O)R[T++]=I[O]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var D=window.crypto.random(32);for(O=0;O<D.length;++O)R[T++]=255&D.charCodeAt(O)}for(;T<L;)O=Math.floor(65536*Math.random()),R[T++]=O>>>8,R[T++]=255&O;T=0,E()}function x(){if(null==C){for(E(),(C=new j).init(R),T=0;T<R.length;++T)R[T]=0;T=0}return C.next()}function M(){}function j(){this.i=0,this.j=0,this.S=new Array}M.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=x()},j.prototype.init=function(e){var t,r,n;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,n=this.S[t],this.S[t]=this.S[r],this.S[r]=n;this.i=0,this.j=0},j.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 L=256;$n.exports={default:t,BigInteger:t,SecureRandom:M}}.call(a);var qn=Gn.exports,Hn={};!function(e){!function(){var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_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,n){var i,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(i=n[h],o=0;o<a.keys.length;o++){if(null==i)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));i=i[a.keys[o]]}else i=a.param_no?n[a.param_no]:n[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&i instanceof Function&&(i=i()),t.numeric_arg.test(a.type)&&"number"!=typeof i&&isNaN(i))throw new TypeError(r("[sprintf] expecting number but found %T",i));switch(t.number.test(a.type)&&(u=i>=0),a.type){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,a.width?parseInt(a.width):0);break;case"e":i=a.precision?parseFloat(i).toExponential(a.precision):parseFloat(i).toExponential();break;case"f":i=a.precision?parseFloat(i).toFixed(a.precision):parseFloat(i);break;case"g":i=a.precision?String(Number(i.toPrecision(a.precision))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=a.precision?i.substring(0,a.precision):i;break;case"t":i=String(!!i),i=a.precision?i.substring(0,a.precision):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=a.precision?i.substring(0,a.precision):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=a.precision?i.substring(0,a.precision):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=i:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",i=i.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+i).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+i+c:"0"===d?p+c+i:c+p+i)}return m}(function(e){if(i[e])return i[e];var r,n=e,s=[],o=0;for(;n;){if(null!==(r=t.text.exec(n)))s.push(r[0]);else if(null!==(r=t.modulo.exec(n)))s.push("%");else{if(null===(r=t.placeholder.exec(n)))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]})}n=n.substring(r[0].length)}return i[e]=s}(e),arguments)}function n(e,t){return r.apply(null,[e].concat(t||[]))}var i=Object.create(null);e.sprintf=r,e.vsprintf=n,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=n)}()}(Hn);var Wn=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Kn=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Jn=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)&&Wn(t,e,r);return Kn(t,e),t};Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.Address4=void 0;const Qn=Jn(Fn),Xn=Jn(zn),Yn=Vn,Zn=qn,ei=Hn;class ti{constructor(e){this.groups=Xn.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=Qn.isCorrect(Xn.BITS),this.isInSubnet=Qn.isInSubnet,this.address=e;const t=Xn.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>Xn.BITS)throw new Yn.AddressError("Invalid subnet mask.");e=e.replace(Xn.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new ti(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Xn.RE_ADDRESS))throw new Yn.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 n;for(n=0;n<8;n+=2){const e=t.slice(n,n+2);r.push(parseInt(e,16))}return new ti(r.join("."))}static fromInteger(e){return ti.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new ti(t)}toHex(){return this.parsedAddress.map((e=>(0,ei.sprintf)("%02x",parseInt(e,10)))).join(":")}toArray(){return this.parsedAddress.map((e=>parseInt(e,10)))}toGroup6(){const e=[];let t;for(t=0;t<Xn.GROUPS;t+=2){const r=(0,ei.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,ei.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Zn.BigInteger(this.parsedAddress.map((e=>(0,ei.sprintf)("%02x",parseInt(e,10)))).join(""),16)}_startAddress(){return new Zn.BigInteger(this.mask()+"0".repeat(Xn.BITS-this.subnetMask),2)}startAddress(){return ti.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Zn.BigInteger("1");return ti.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Zn.BigInteger(this.mask()+"1".repeat(Xn.BITS-this.subnetMask),2)}endAddress(){return ti.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Zn.BigInteger("1");return ti.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return ti.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,ei.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new ti("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Xn.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Xn.RE_ADDRESS,(0,ei.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(".")))}}Bn.Address4=ti;var ri={},ni={};Object.defineProperty(ni,"__esModule",{value:!0}),ni.RE_URL_WITH_PORT=ni.RE_URL=ni.RE_ZONE_STRING=ni.RE_SUBNET_STRING=ni.RE_BAD_ADDRESS=ni.RE_BAD_CHARACTERS=ni.TYPES=ni.SCOPES=ni.GROUPS=ni.BITS=void 0,ni.BITS=128,ni.GROUPS=8,ni.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},ni.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"},ni.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,ni.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,ni.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,ni.RE_ZONE_STRING=/%.*$/,ni.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),ni.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var ii={};Object.defineProperty(ii,"__esModule",{value:!0}),ii.simpleGroup=ii.spanLeadingZeroes=ii.spanAll=ii.spanAllZeroes=void 0;const si=Hn;function oi(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function ai(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}ii.spanAllZeroes=oi,ii.spanAll=function(e,t=0){return e.split("").map(((e,r)=>(0,si.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,oi(e)))).join("")},ii.spanLeadingZeroes=function(e){return e.split(":").map((e=>ai(e))).join(":")},ii.simpleGroup=function(e,t=0){return e.split(":").map(((e,r)=>/group-v4/.test(e)?e:(0,si.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,ai(e))))};var ci={},di=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),li=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ui=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)&&di(t,e,r);return li(t,e),t};Object.defineProperty(ci,"__esModule",{value:!0}),ci.possibleElisions=ci.simpleRegularExpression=ci.ADDRESS_BOUNDARY=ci.padGroup=ci.groupPossibilities=void 0;const pi=ui(ni),hi=Hn;function fi(e){return(0,hi.sprintf)("(%s)",e.join("|"))}function mi(e){return e.length<4?(0,hi.sprintf)("0{0,%d}%s",4-e.length,e):e}ci.groupPossibilities=fi,ci.padGroup=mi,ci.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",ci.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===pi.GROUPS-1?":":"";return fi([mi(e),t])}return mi(e)})).join(":")));return r.push(e.map(mi).join(":")),fi(r)},ci.possibleElisions=function(e,t,r){const n=t?"":":",i=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,hi.sprintf)("%s(:0{1,4}){1,%d}",n,e-1)),s.push((0,hi.sprintf)("(0{1,4}:){1,%d}%s",e-1,i)),s.push((0,hi.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,hi.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return fi(s)};var gi=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),vi=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bi=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)&&gi(t,e,r);return vi(t,e),t};Object.defineProperty(ri,"__esModule",{value:!0}),ri.Address6=void 0;const yi=bi(Fn),wi=bi(zn),_i=bi(ni),Si=bi(ii),Ci=Bn,Ri=ci,Ti=Vn,ki=qn,Pi=Hn;function Ei(e){if(!e)throw new Error("Assertion failed.")}function Oi(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 Ii(e){return(0,Pi.sprintf)("%04x",parseInt(e,16))}function Di(e){return 255&e}class xi{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=yi.isInSubnet,this.isCorrect=yi.isCorrect(_i.BITS),this.groups=void 0===t?_i.GROUPS:t,this.address=e;const r=_i.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>_i.BITS)throw new Ti.AddressError("Invalid subnet mask.");e=e.replace(_i.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new Ti.AddressError("Invalid subnet mask.");const n=_i.RE_ZONE_STRING.exec(e);n&&(this.zone=n[0],e=e.replace(_i.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new xi(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let n;for(n=0;n<_i.GROUPS;n++)r.push(t.slice(4*n,4*(n+1)));return new xi(r.join(":"))}static fromURL(e){let t,r,n=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=_i.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],n=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=_i.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 n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new xi(t),port:n}}static fromAddress4(e){const t=new Ci.Address4(e),r=_i.BITS-(wi.BITS-t.subnetMask);return new xi(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new Ti.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 xi(t)}microsoftTranscription(){return(0,Pi.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=_i.BITS-this.subnetMask-Math.abs(e-_i.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 ki.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new ki.BigInteger(this.mask()+"0".repeat(_i.BITS-this.subnetMask),2)}startAddress(){return xi.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new ki.BigInteger("1");return xi.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new ki.BigInteger(this.mask()+"1".repeat(_i.BITS-this.subnetMask),2)}endAddress(){return xi.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new ki.BigInteger("1");return xi.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=_i.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(_i.TYPES))if(this.isInSubnet(new xi(e)))return _i.TYPES[e];return"Global unicast"}getBits(e,t){return new ki.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,_i.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,Pi.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const n=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&n.push([e-r,e-1]),r=0)}r>1&&n.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const i=n.map((e=>e[1]-e[0]+1));if(n.length>0){const e=i.indexOf(Math.max(...i));t=function(e,t){const r=[],n=[];let i;for(i=0;i<e.length;i++)i<t[0]?r.push(e[i]):i>t[1]&&n.push(e[i]);return r.concat(["compact"]).concat(n)}(this.parsedAddress,n[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(_i.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(wi.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new Ci.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new Ti.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(wi.RE_ADDRESS,this.address4.parsedAddress.map(Oi).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(_i.RE_BAD_CHARACTERS);if(t)throw new Ti.AddressError((0,Pi.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(_i.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(_i.RE_BAD_ADDRESS);if(r)throw new Ti.AddressError((0,Pi.sprintf)("Address failed regex: %s",r.join("")),e.replace(_i.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let n=[];const i=e.split("::");if(2===i.length){let e=i[0].split(":"),t=i[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 Ti.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,n=n.concat(e);for(let e=0;e<r;e++)n.push("0");n=n.concat(t)}else{if(1!==i.length)throw new Ti.AddressError("Too many :: groups found");n=e.split(":"),this.elidedGroups=0}if(n=n.map((e=>(0,Pi.sprintf)("%x",parseInt(e,16)))),n.length!==this.groups)throw new Ti.AddressError("Incorrect number of groups found");return n}canonicalForm(){return this.parsedAddress.map(Ii).join(":")}decimal(){return this.parsedAddress.map((e=>(0,Pi.sprintf)("%05d",parseInt(e,16)))).join(":")}bigInteger(){return new ki.BigInteger(this.parsedAddress.map(Ii).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return Ci.Address4.fromHex(new ki.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new xi(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 ki.BigInteger("ffff",16)).toString(),r=Ci.Address4.fromHex(this.getBitsBase16(32,64)),n=Ci.Address4.fromHex(this.getBits(96,128).xor(new ki.BigInteger("ffffffff",16)).toString(16)),i=this.getBits(64,80),s=this.getBitsBase2(64,80),o=i.testBit(15),a=i.testBit(14),c=i.testBit(8),d=i.testBit(9),l=new ki.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Pi.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:n.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=Ci.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Pi.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 xi(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(Di)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(Di))}static fromUnsignedByteArray(e){const t=new ki.BigInteger("256",10);let r=new ki.BigInteger("0",10),n=new ki.BigInteger("1",10);for(let i=e.length-1;i>=0;i--)r=r.add(n.multiply(new ki.BigInteger(e[i].toString(10),10))),n=n.multiply(t);return xi.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 xi("2001::/32"))}is6to4(){return this.isInSubnet(new xi("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Pi.sprintf)(":%s",e),(0,Pi.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,Pi.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Pi.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return Si.simpleGroup(this.address).join(":");Ei("number"==typeof this.elidedGroups),Ei("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...Si.simpleGroup(t)):e.push("");const n=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)n.push((0,Pi.sprintf)("group-%d",e));return e.push((0,Pi.sprintf)('<span class="%s"></span>',n.join(" "))),r.length?e.push(...Si.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Ei(this.address4 instanceof Ci.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new xi(this.correctForm());if(0===r.elidedGroups)t.push((0,Ri.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===_i.GROUPS)t.push((0,Ri.possibleElisions)(_i.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,Ri.simpleRegularExpression)(e[0].split(":"))),Ei("number"==typeof r.elidedGroups),t.push((0,Ri.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,Ri.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",Ri.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",Ri.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}ri.Address6=xi,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=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}),n=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(n,e,i);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const i=Bn;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});const s=ri;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=Vn;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=n(ii);e.v6={helpers:c}}(Nn);var Mi={exports:{}};!function(e){(function(){var t,r,n,i,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,n){var i,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;n>0;){if((s=r-n)<0&&(s=0),e[i]>>s!=t[i]>>s)return!1;n-=r,i+=1}return!0},r.subnetMatch=function(e,t,r){var n,i,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),n=0,i=o.length;n<i;n++)if(a=o[n],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,n;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<=(n=e[t])&&n<=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,n,i,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,i=!1,t=r=3;r>=0;t=r+=-1){if(!((n=this.octets[t])in o))return null;if(s=o[n],i&&0!==s)return null;8!==s&&(i=!0),e+=s}return 32-e},e}(),n="(0?\\d+|0x[a-f0-9]+)",i={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},r.IPv4.parser=function(e){var t,r,n,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(i.fourOctet))return function(){var e,i,s,o;for(o=[],e=0,i=(s=t.slice(1,6)).length;e<i;e++)n=s[e],o.push(r(n));return o}();if(t=e.match(i.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,n,i,s,o,a;if(16===e.length)for(this.parts=[],r=n=0;n<=14;r=n+=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(i=0,s=(a=this.parts).length;i<s;i++)if(!(0<=(o=a[i])&&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,n,i;for(n=/((^|:)(0(:|$)){2,})/g,i=this.toNormalizedString(),e=0,t=-1;r=n.exec(i);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?i:i.substring(0,e)+"::"+i.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,n,i;for(e=[],t=0,r=(i=this.parts).length;t<r;t++)n=i[t],e.push(n>>8),e.push(255&n);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16));return i}.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,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16).padStart(4,"0"));return i}.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,n;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(n=this.parts.slice(-2))[0],t=n[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,n,i,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,i=!1,t=r=7;r>=0;t=r+=-1){if(!((n=this.parts[t])in o))return null;if(s=o[n],i&&0!==s)return null;16!==s&&(i=!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+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"("+c+")?$","i")},t=function(e,t){var r,n,i,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,n=-1;(n=e.indexOf(":",n+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,n,s;for(s=[],t=0,r=(n=e.split(":")).length;t<r;t++)i=n[t],s.push(parseInt(i,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,n,i,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(n=0,i=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;n<i;n++)if(!(0<=(a=c[n])&&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,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,n;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(n=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)n[r]=255,r++;return t<4&&(n[t]=Math.pow(2,e%8)-1<<8-e%8),new this(n)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)|255^parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;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)}(Mi);var ji=Mi.exports,Li=function(e,t){if("string"==typeof t)return Ai(e,t);if("object"==typeof t){for(var r=!1,n=0;n<t.length;n++)if(Ai(e,t[n])){r=!0;break}return r}};function Ai(e,t){try{var r=ji.process(e);if(-1===t.indexOf("/")){var n=ji.process(t);return"ipv6"===r.kind()&&"ipv6"===n.kind()?r.toNormalizedString()===n.toNormalizedString():r.toString()==n.toString()}var i=ji.parseCIDR(t);return r.match(i)}catch(e){return!1}}var Ni=Li,Bi=/^((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]?)$/,Fi=["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"],zi=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var Vi=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(Bi.test(e)){r.isValid=!0;for(var n=e.split("."),i=0;i<4;i++)t.push(parseInt(n[i],10));r.boiledIp=t.join("."),Ni(r.boiledIp,Fi)&&(r.isBogon=!0),Ni(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),Ni(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),Ni(r.boiledIp,zi)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},Ui=c(Vi),$i={exports:{}},Gi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qi=[],Hi=0;Hi<256;Hi++)qi[Hi]=(Hi+256).toString(16).substr(1);$i.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e,t){var r=t||0,n=qi;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!Gi.test(r))return!1;if(void 0===t)t=Ji(r);else if(Ji(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 Wi,Ki,Ji=$i.exports.version=function(e){return 0|e.charAt(14)},Qi=c($i.exports),Xi={},Yi={exports:{}};function Zi(){if(Ki)return Wi;Ki=1;var e=1e3,t=60*e,r=60*t,n=24*r,i=7*n,s=365.25*n;function o(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return Wi=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*i;case"days":case"day":case"d":return c*n;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(i){var s=Math.abs(i);if(s>=n)return o(i,s,n,"day");if(s>=r)return o(i,s,r,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=n)return Math.round(i/n)+"d";if(s>=r)return Math.round(i/r)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},Wi}var es=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,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,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),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:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}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.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Zi(),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 n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,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")}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=es(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Yi,Yi.exports);var ts=Yi.exports,rs={},ns={exports:{}};!function(e,t){!function(r,n){var i,s="",o="function",a="undefined",c="object",d="string",l="major",u="model",p="name",h="type",f="vendor",m="version",g="architecture",v="console",b="mobile",y="tablet",w="smarttv",_="wearable",S="xr",C="embedded",R="inapp",T="user-agent",k="brands",P="formFactors",E="fullVersionList",O="platform",I="platformVersion",D="bitness",x="sec-ch-ua",M=x+"-full-version-list",j=x+"-arch",L=x+"-"+D,A=x+"-form-factors",N=x+"-"+b,B=x+"-"+u,F=x+"-"+O,z=F+"-version",V=[k,E,b,u,O,I,g,P,D],U="browser",$="cpu",G="device",q="engine",H="os",W="result",K="Amazon",J="Apple",Q="ASUS",X="BlackBerry",Y="Google",Z="Huawei",ee="Lenovo",te="LG",re="Microsoft",ne="Motorola",ie="Samsung",se="Sharp",oe="Sony",ae="Xiaomi",ce="Zebra",de="Mobile ",le=" Browser",ue="Chrome",pe="Chromecast",he="Firefox",fe="Opera",me="Facebook",ge="Sogou",ve="Windows",be=typeof r!==a,ye=be&&r.navigator?r.navigator:n,we=ye&&ye.userAgentData?ye.userAgentData:n,_e=function(e){for(var t={},r=0;r<e.length;r++)t[e[r].toUpperCase()]=e[r];return t},Se=function(e,t){if(typeof e===c&&e.length>0){for(var r in e)if(ke(e[r])==ke(t))return!0;return!1}return!!Re(e)&&-1!==ke(t).indexOf(ke(e))},Ce=function(e,t){for(var r in e)return/^(browser|cpu|device|engine|os)$/.test(r)||!!t&&Ce(e[r])},Re=function(e){return typeof e===d},Te=function(e){if(!e)return n;for(var t=[],r=Oe(/\\?\"/g,e).split(","),i=0;i<r.length;i++)if(r[i].indexOf(";")>-1){var s=De(r[i]).split(";v=");t[i]={brand:s[0],version:s[1]}}else t[i]=De(r[i]);return t},ke=function(e){return Re(e)?e.toLowerCase():e},Pe=function(e){return Re(e)?Oe(/[^\d\.]/g,e).split(".")[0]:n},Ee=function(e){for(var t in e){var r=e[t];typeof r==c&&2==r.length?this[r[0]]=r[1]:this[r]=n}return this},Oe=function(e,t){return Re(t)?t.replace(e,s):t},Ie=function(e){return Oe(/\\?\"/g,e)},De=function(e,t){if(Re(e))return e=Oe(/^\s\s*/,e),typeof t===a?e:e.substring(0,500)},xe=function(e,t){if(e&&t)for(var r,i,s,a,d,l,u=0;u<t.length&&!d;){var p=t[u],h=t[u+1];for(r=i=0;r<p.length&&!d&&p[r];)if(d=p[r++].exec(e))for(s=0;s<h.length;s++)l=d[++i],typeof(a=h[s])===c&&a.length>0?2===a.length?typeof a[1]==o?this[a[0]]=a[1].call(this,l):this[a[0]]=a[1]:3===a.length?typeof a[1]!==o||a[1].exec&&a[1].test?this[a[0]]=l?l.replace(a[1],a[2]):n:this[a[0]]=l?a[1].call(this,l,a[2]):n:4===a.length&&(this[a[0]]=l?a[3].call(this,l.replace(a[1],a[2])):n):this[a]=l||n;u+=2}},Me=function(e,t){for(var r in t)if(typeof t[r]===c&&t[r].length>0){for(var i=0;i<t[r].length;i++)if(Se(t[r][i],e))return"?"===r?n:r}else if(Se(t[r],e))return"?"===r?n:r;return t.hasOwnProperty("*")?t["*"]:e},je={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"},Le={embedded:"Automotive",mobile:"Mobile",tablet:["Tablet","EInk"],smarttv:"TV",wearable:"Watch",xr:["VR","XR"],"?":["Desktop","Unknown"],"*":n},Ae={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[m,[p,de+"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[m,[p,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[p,m],[/opios[\/ ]+([\w\.]+)/i],[m,[p,fe+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[m,[p,fe+" GX"]],[/\bopr\/([\w\.]+)/i],[m,[p,fe]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[m,[p,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[m,[p,"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],[p,m],[/quark(?:pc)?\/([-\w\.]+)/i],[m,[p,"Quark"]],[/\bddg\/([\w\.]+)/i],[m,[p,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[m,[p,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[m,[p,"WeChat"]],[/konqueror\/([\w\.]+)/i],[m,[p,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[m,[p,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[m,[p,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[m,[p,"Smart "+ee+le]],[/(avast|avg)\/([\w\.]+)/i],[[p,/(.+)/,"$1 Secure"+le],m],[/\bfocus\/([\w\.]+)/i],[m,[p,he+" Focus"]],[/\bopt\/([\w\.]+)/i],[m,[p,fe+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[m,[p,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[m,[p,"Dolphin"]],[/coast\/([\w\.]+)/i],[m,[p,fe+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[m,[p,"MIUI"+le]],[/fxios\/([\w\.-]+)/i],[m,[p,de+he]],[/\bqihoobrowser\/?([\w\.]*)/i],[m,[p,"360"]],[/\b(qq)\/([\w\.]+)/i],[[p,/(.+)/,"$1Browser"],m],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[p,/(.+)/,"$1"+le],m],[/samsungbrowser\/([\w\.]+)/i],[m,[p,ie+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[m,[p,ge+" Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[p,ge+" Mobile"],m],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[p,m],[/(lbbrowser|rekonq)/i],[p],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[m,p],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[p,me],m,[h,R]],[/(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,/(instagram|snapchat)[\/ ]([-\w\.]+)/i],[p,m,[h,R]],[/\bgsa\/([\w\.]+) .*safari\//i],[m,[p,"GSA"],[h,R]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[m,[p,"TikTok"],[h,R]],[/\[(linkedin)app\]/i],[p,[h,R]],[/(chromium)[\/ ]([-\w\.]+)/i],[p,m],[/headlesschrome(?:\/([\w\.]+)| )/i],[m,[p,ue+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[p,ue+" WebView"],m],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[m,[p,"Android"+le]],[/chrome\/([\w\.]+) mobile/i],[m,[p,de+"Chrome"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[p,m],[/version\/([\w\.\,]+) .*mobile(?:\/\w+ | ?)safari/i],[m,[p,de+"Safari"]],[/iphone .*mobile(?:\/\w+ | ?)safari/i],[[p,de+"Safari"]],[/version\/([\w\.\,]+) .*(safari)/i],[m,p],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[p,[m,"1"]],[/(webkit|khtml)\/([\w\.]+)/i],[p,m],[/(?:mobile|tablet);.*(firefox)\/([\w\.-]+)/i],[[p,de+he],m],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[p,"Netscape"],m],[/(wolvic|librewolf)\/([\w\.]+)/i],[p,m],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[m,[p,he+" 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,/\b(links) \(([\w\.]+)/i],[p,[m,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[p,[m,/[^\d\.]+./,s]]],cpu:[[/\b(?:(amd|x|x86[-_]?|wow|win)64)\b/i],[[g,"amd64"]],[/(ia32(?=;))/i,/((?:i[346]|x)86)[;\)]/i],[[g,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[g,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[g,"armhf"]],[/windows (ce|mobile); ppc;/i],[[g,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[g,/ower/,s,ke]],[/(sun4\w)[;\)]/i],[[g,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[g,ke]]],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],[u,[f,ie],[h,y]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[u,[f,ie],[h,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[u,[f,J],[h,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[u,[f,J],[h,y]],[/(macintosh);/i],[u,[f,J]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[u,[f,se],[h,b]],[/(?:honor)([-\w ]+)[;\)]/i],[u,[f,"Honor"],[h,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[u,[f,Z],[h,y]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[u,[f,Z],[h,b]],[/\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],[[u,/_/g," "],[f,ae],[h,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[u,/_/g," "],[f,ae],[h,y]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[u,[f,"OPPO"],[h,b]],[/\b(opd2\d{3}a?) bui/i],[u,[f,"OPPO"],[h,y]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[u,[f,"Vivo"],[h,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[u,[f,"Realme"],[h,b]],[/\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],[u,[f,ne],[h,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[u,[f,ne],[h,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[u,[f,te],[h,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[u,[f,te],[h,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[u,[f,ee],[h,y]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[u,/_/g," "],[f,"Nokia"],[h,b]],[/(pixel c)\b/i],[u,[f,Y],[h,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[u,[f,Y],[h,b]],[/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],[u,[f,oe],[h,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[u,"Xperia Tablet"],[f,oe],[h,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[u,[f,"OnePlus"],[h,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[u,[f,K],[h,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[u,/(.+)/g,"Fire Phone $1"],[f,K],[h,b]],[/(playbook);[-\w\),; ]+(rim)/i],[u,f,[h,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[u,[f,X],[h,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[u,[f,Q],[h,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[u,[f,Q],[h,b]],[/(nexus 9)/i],[u,[f,"HTC"],[h,y]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[f,[u,/_/g," "],[h,b]],[/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],[u,[f,"TCL"],[h,y]],[/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],[u,[f,"TCL"],[h,b]],[/(itel) ((\w+))/i],[[f,ke],u,[h,Me,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[u,[f,"Acer"],[h,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[u,[f,"Meizu"],[h,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[u,[f,"Ulefone"],[h,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[u,[f,"Energizer"],[h,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[u,[f,"Cat"],[h,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[u,[f,"Smartfren"],[h,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[u,[f,"Nothing"],[h,b]],[/(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],[f,u,[h,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i],[f,u,[h,y]],[/(surface duo)/i],[u,[f,re],[h,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[u,[f,"Fairphone"],[h,b]],[/(shield[\w ]+) b/i],[u,[f,"Nvidia"],[h,y]],[/(sprint) (\w+)/i],[f,u,[h,b]],[/(kin\.[onetw]{3})/i],[[u,/\./g," "],[f,re],[h,b]],[/droid.+; ([c6]+|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[u,[f,ce],[h,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[u,[f,ce],[h,b]],[/smart-tv.+(samsung)/i],[f,[h,w]],[/hbbtv.+maple;(\d+)/i],[[u,/^/,"SmartTV"],[f,ie],[h,w]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[f,te],[h,w]],[/(apple) ?tv/i],[f,[u,J+" TV"],[h,w]],[/crkey.*devicetype\/chromecast/i],[[u,pe+" Third Generation"],[f,Y],[h,w]],[/crkey.*devicetype\/([^/]*)/i],[[u,/^/,"Chromecast "],[f,Y],[h,w]],[/fuchsia.*crkey/i],[[u,pe+" Nest Hub"],[f,Y],[h,w]],[/crkey/i],[[u,pe],[f,Y],[h,w]],[/droid.+aft(\w+)( bui|\))/i],[u,[f,K],[h,w]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[u,[f,se],[h,w]],[/(bravia[\w ]+)( bui|\))/i],[u,[f,oe],[h,w]],[/(mitv-\w{5}) bui/i],[u,[f,ae],[h,w]],[/Hbbtv.*(technisat) (.*);/i],[f,u,[h,w]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[f,De],[u,De],[h,w]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,w]],[/(ouya)/i,/(nintendo) (\w+)/i],[f,u,[h,v]],[/droid.+; (shield) bui/i],[u,[f,"Nvidia"],[h,v]],[/(playstation \w+)/i],[u,[f,oe],[h,v]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[u,[f,re],[h,v]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[u,[f,ie],[h,_]],[/((pebble))app/i],[f,u,[h,_]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[u,[f,J],[h,_]],[/droid.+; (wt63?0{2,3})\)/i],[u,[f,ce],[h,_]],[/droid.+; (glass) \d/i],[u,[f,Y],[h,S]],[/(pico) (4|neo3(?: link|pro)?)/i],[f,u,[h,S]],[/; (quest( \d| pro)?)/i],[u,[f,me],[h,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[f,[h,C]],[/(aeobc)\b/i],[u,[f,K],[h,C]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[u,[h,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[u,[h,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,y]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,b]],[/(android[-\w\. ]{0,9});.+buil/i],[u,[f,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[m,[p,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[p,m],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[m,[p,"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],[p,m],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[m,p]],os:[[/microsoft (windows) (vista|xp)/i],[p,m],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[p,[m,Me,je]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[m,Me,je],[p,ve]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[m,/_/g,"."],[p,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[p,"macOS"],[m,/_/g,"."]],[/android ([\d\.]+).*crkey/i],[m,[p,pe+" Android"]],[/fuchsia.*crkey\/([\d\.]+)/i],[m,[p,pe+" Fuchsia"]],[/crkey\/([\d\.]+).*devicetype\/smartspeaker/i],[m,[p,pe+" SmartSpeaker"]],[/linux.*crkey\/([\d\.]+)/i],[m,[p,pe+" Linux"]],[/crkey\/([\d\.]+)/i],[m,[p,pe]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[m,p],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[p,m],[/\(bb(10);/i],[m,[p,X]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[m,[p,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[m,[p,he+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[m,[p,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[m,[p,"watchOS"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[p,"Chrome OS"],m],[/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,/(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],[p,m],[/(sunos) ?([\w\.\d]*)/i],[[p,"Solaris"],m],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[p,m]]},Ne=(i={init:{},isIgnore:{},isIgnoreRgx:{},toString:{}},Ee.call(i.init,[[U,[p,m,l,h]],[$,[g]],[G,[h,u,f]],[q,[p,m]],[H,[p,m]]]),Ee.call(i.isIgnore,[[U,[m,l]],[q,[m]],[H,[m]]]),Ee.call(i.isIgnoreRgx,[[U,/ ?browser$/i],[H,/ ?os$/i]]),Ee.call(i.toString,[[U,[p,m]],[$,[g]],[G,[f,u]],[q,[p,m]],[H,[p,m]]]),i),Be=function(e,t){var r=Ne.init[t],n=Ne.isIgnore[t]||0,i=Ne.isIgnoreRgx[t]||0,o=Ne.toString[t]||0;function c(){Ee.call(this,r)}return c.prototype.getItem=function(){return e},c.prototype.withClientHints=function(){return we?we.getHighEntropyValues(V).then((function(t){return e.setCH(new Fe(t,!1)).parseCH().get()})):e.parseCH().get()},c.prototype.withFeatureCheck=function(){return e.detectFeature().get()},t!=W&&(c.prototype.is=function(e){var t=!1;for(var r in this)if(this.hasOwnProperty(r)&&!Se(n,r)&&ke(i?Oe(i,this[r]):this[r])==ke(i?Oe(i,e):e)){if(t=!0,e!=a)break}else if(e==a&&t){t=!t;break}return t},c.prototype.toString=function(){var e=s;for(var t in o)typeof this[o[t]]!==a&&(e+=(e?" ":s)+this[o[t]]);return e||a}),we||(c.prototype.then=function(e){var t=this,r=function(){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e])};r.prototype={is:c.prototype.is,toString:c.prototype.toString};var n=new r;return e(n),n}),new c};function Fe(e,t){if(e=e||{},Ee.call(this,V),t)Ee.call(this,[[k,Te(e[x])],[E,Te(e[M])],[b,/\?1/.test(e[N])],[u,Ie(e[B])],[O,Ie(e[F])],[I,Ie(e[z])],[g,Ie(e[j])],[P,Te(e[A])],[D,Ie(e[L])]]);else for(var r in e)this.hasOwnProperty(r)&&typeof e[r]!==a&&(this[r]=e[r])}function ze(e,t,r,i){return this.get=function(e){return e?this.data.hasOwnProperty(e)?this.data[e]:n: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(ye&&ye.userAgent==this.ua)switch(this.itemType){case U:ye.brave&&typeof ye.brave.isBrave==o&&this.set(p,"Brave");break;case G:!this.get(h)&&we&&we[b]&&this.set(h,b),"Macintosh"==this.get(u)&&ye&&typeof ye.standalone!==a&&ye.maxTouchPoints&&ye.maxTouchPoints>2&&this.set(u,"iPad").set(h,y);break;case H:!this.get(p)&&we&&we[O]&&this.set(p,we[O]);break;case W:var e=this.data,t=function(t){return e[t].getItem().detectFeature().get()};this.set(U,t(U)).set($,t($)).set(G,t(G)).set(q,t(q)).set(H,t(H))}return this},this.parseUA=function(){return this.itemType!=W&&xe.call(this.data,this.ua,this.rgxMap),this.itemType==U&&this.set(l,Pe(this.get(m))),this},this.parseCH=function(){var e=this.uaCH,t=this.rgxMap;switch(this.itemType){case U:var r,i=e[E]||e[k];if(i)for(var s in i){var o=Oe(/(Google|Microsoft) /,i[s].brand||i[s]),a=i[s].version;/not.a.brand/i.test(o)||r&&(!/chrom/i.test(r)||/chromi/i.test(o))||(this.set(p,o).set(m,a).set(l,Pe(a)),r=o)}break;case $:var c=e[g];c&&(c&&"64"==e[D]&&(c+="64"),xe.call(this.data,c+";",t));break;case G:if(e[b]&&this.set(h,b),e[u]&&this.set(u,e[u]),"Xbox"==e[u]&&this.set(h,v).set(f,re),e[P]){var d;if("string"!=typeof e[P])for(var y=0;!d&&y<e[P].length;)d=Me(e[P][y++],Le);else d=Me(e[P],Le);this.set(h,d)}break;case H:var w=e[O];if(w){var _=e[I];w==ve&&(_=parseInt(Pe(_),10)>=13?"11":"10"),this.set(p,w).set(m,_)}this.get(p)==ve&&"Xbox"==e[u]&&this.set(p,"Xbox").set(m,n);break;case W:var S=this.data,C=function(t){return S[t].getItem().setCH(e).parseCH().get()};this.set(U,C(U)).set($,C($)).set(G,C(G)).set(q,C(q)).set(H,C(H))}return this},Ee.call(this,[["itemType",e],["ua",t],["uaCH",i],["rgxMap",r],["data",Be(this,e)]]),this}function Ve(e,t,r){if(typeof e===c?(Ce(e,!0)?(typeof t===c&&(r=t),t=e):(r=e,t=n),e=n):typeof e!==d||Ce(t,!0)||(r=t,t=n),r&&typeof r.append===o){var i={};r.forEach((function(e,t){i[t]=e})),r=i}if(!(this instanceof Ve))return new Ve(e,t,r).getResult();var a=typeof e===d?e:r&&r[T]?r[T]:ye&&ye.userAgent?ye.userAgent:s,l=new Fe(r,!0),u=t?function(e,t){var r={},n=t;if(!Ce(t))for(var i in n={},t)for(var s in t[i])n[s]=t[i][s].concat(n[s]?n[s]:[]);for(var o in e)r[o]=n[o]&&n[o].length%2==0?n[o].concat(e[o]):e[o];return r}(Ae,t):Ae,p=function(e){return e==W?function(){return new ze(e,a,u,l).set("ua",a).set(U,this.getBrowser()).set($,this.getCPU()).set(G,this.getDevice()).set(q,this.getEngine()).set(H,this.getOS()).get()}:function(){return new ze(e,a,u[e],l).parseUA().get()}};return Ee.call(this,[["getBrowser",p(U)],["getCPU",p($)],["getDevice",p(G)],["getEngine",p(q)],["getOS",p(H)],["getResult",p(W)],["getUA",function(){return a}],["setUA",function(e){return Re(e)&&(a=e.length>500?De(e,500):e),this}]]).setUA(a),this}Ve.VERSION="2.0.0",Ve.BROWSER=_e([p,m,l,h]),Ve.CPU=_e([g]),Ve.DEVICE=_e([u,f,h,v,b,w,y,_,C]),Ve.ENGINE=Ve.OS=_e([p,m]),e.exports&&(t=e.exports=Ve),t.UAParser=Ve;var Ue=be&&(r.jQuery||r.Zepto);if(Ue&&!Ue.ua){var $e=new Ve;Ue.ua=$e.getResult(),Ue.ua.get=function(){return $e.getUA()},Ue.ua.set=function(e){$e.setUA(e);var t=$e.getResult();for(var r in t)Ue.ua[r]=t[r]}}}("object"==typeof window?window:a)}(ns,ns.exports);var is=ns.exports,ss={},os=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ss,"__esModule",{value:!0}),ss.Logger=void 0;const as=os(ts),cs="mediasoup-client";ss.Logger=class{constructor(e){e?(this._debug=(0,as.default)(`${cs}:${e}`),this._warn=(0,as.default)(`${cs}:WARN:${e}`),this._error=(0,as.default)(`${cs}:ERROR:${e}`)):(this._debug=(0,as.default)(cs),this._warn=(0,as.default)(`${cs}:WARN`),this._error=(0,as.default)(`${cs}: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 ds,ls={},us={exports:{}},ps="object"==typeof Reflect?Reflect:null,hs=ps&&"function"==typeof ps.apply?ps.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};ds=ps&&"function"==typeof ps.ownKeys?ps.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var fs=Number.isNaN||function(e){return e!=e};function ms(){ms.init.call(this)}us.exports=ms,us.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,s),n(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}Ts(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&Ts(e,"error",t,r)}(e,i,{once:!0})}))},ms.EventEmitter=ms,ms.prototype._events=void 0,ms.prototype._eventsCount=0,ms.prototype._maxListeners=void 0;var gs=10;function vs(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function bs(e){return void 0===e._maxListeners?ms.defaultMaxListeners:e._maxListeners}function ys(e,t,r,n){var i,s,o;if(vs(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]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),(i=bs(e))>0&&o.length>i&&!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 ws(){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 _s(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=ws.bind(n);return i.listener=r,n.wrapFn=i,i}function Ss(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]: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}(i):Rs(i,i.length)}function Cs(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 Rs(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function Ts(e,t,r,n){if("function"==typeof e.on)n.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 i(s){n.once&&e.removeEventListener(t,i),r(s)}))}}Object.defineProperty(ms,"defaultMaxListeners",{enumerable:!0,get:function(){return gs},set:function(e){if("number"!=typeof e||e<0||fs(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");gs=e}}),ms.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},ms.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||fs(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},ms.prototype.getMaxListeners=function(){return bs(this)},ms.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var n="error"===e,i=this._events;if(void 0!==i)n=n&&void 0===i.error;else if(!n)return!1;if(n){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=i[e];if(void 0===a)return!1;if("function"==typeof a)hs(a,this,t);else{var c=a.length,d=Rs(a,c);for(r=0;r<c;++r)hs(d[r],this,t)}return!0},ms.prototype.addListener=function(e,t){return ys(this,e,t,!1)},ms.prototype.on=ms.prototype.addListener,ms.prototype.prependListener=function(e,t){return ys(this,e,t,!0)},ms.prototype.once=function(e,t){return vs(t),this.on(e,_s(this,e,t)),this},ms.prototype.prependOnceListener=function(e,t){return vs(t),this.prependListener(e,_s(this,e,t)),this},ms.prototype.removeListener=function(e,t){var r,n,i,s,o;if(vs(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,o||t)}return this},ms.prototype.off=ms.prototype.removeListener,ms.prototype.removeAllListeners=function(e){var t,r,n;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 i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);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(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},ms.prototype.listeners=function(e){return Ss(this,e,!0)},ms.prototype.rawListeners=function(e){return Ss(this,e,!1)},ms.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Cs.call(e,t)},ms.prototype.listenerCount=Cs,ms.prototype.eventNames=function(){return this._eventsCount>0?ds(this._events):[]};var ks=us.exports;Object.defineProperty(ls,"__esModule",{value:!0}),ls.EnhancedEventEmitter=void 0;const Ps=ks,Es=new ss.Logger("EnhancedEventEmitter");class Os extends Ps.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){Es.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)}}ls.EnhancedEventEmitter=Os;var Is={};Object.defineProperty(Is,"__esModule",{value:!0}),Is.InvalidStateError=Is.UnsupportedError=void 0;class Ds extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ds):this.stack=new Error(e).stack}}Is.UnsupportedError=Ds;class xs extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,xs):this.stack=new Error(e).stack}}Is.InvalidStateError=xs;var Ms={};Object.defineProperty(Ms,"__esModule",{value:!0}),Ms.clone=function(e){return void 0===e?void 0:Number.isNaN(e)?NaN:"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))},Ms.generateRandomNumber=function(){return Math.round(1e7*Math.random())},Ms.deepFreeze=function e(t){const r=Reflect.ownKeys(t);for(const n of r){const r=t[n];(r&&"object"==typeof r||"function"==typeof r)&&e(r)}return Object.freeze(t)};var js,Ls,As={},Ns={},Bs={},Fs={exports:{}};function zs(){if(Ls)return js;Ls=1;var e=1e3,t=60*e,r=60*t,n=24*r,i=7*n,s=365.25*n;function o(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return js=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*i;case"days":case"day":case"d":return c*n;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(i){var s=Math.abs(i);if(s>=n)return o(i,s,n,"day");if(s>=r)return o(i,s,r,"hour");if(s>=t)return o(i,s,t,"minute");if(s>=e)return o(i,s,e,"second");return i+" ms"}(a):function(i){var s=Math.abs(i);if(s>=n)return Math.round(i/n)+"d";if(s>=r)return Math.round(i/r)+"h";if(s>=t)return Math.round(i/t)+"m";if(s>=e)return Math.round(i/e)+"s";return i+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))},js}var Vs=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,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,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),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:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}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.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=zs(),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 n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,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")}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;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&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$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=Vs(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Fs,Fs.exports);var Us=Fs.exports,$s=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Bs,"__esModule",{value:!0}),Bs.Logger=void 0;const Gs=$s(Us),qs="h264-profile-level-id";Bs.Logger=class{constructor(e){e?(this._debug=(0,Gs.default)(`${qs}:${e}`),this._warn=(0,Gs.default)(`${qs}:WARN:${e}`),this._error=(0,Gs.default)(`${qs}:ERROR:${e}`)):(this._debug=(0,Gs.default)(qs),this._warn=(0,Gs.default)(`${qs}:WARN`),this._error=(0,Gs.default)(`${qs}: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(Ns,"__esModule",{value:!0}),Ns.generateProfileLevelIdStringForAnswer=Ns.isSameProfile=Ns.parseSdpProfileLevelId=Ns.levelToString=Ns.profileToString=Ns.profileLevelIdToString=Ns.parseProfileLevelId=Ns.ProfileLevelId=Ns.Level=Ns.Profile=void 0;const Hs=new Bs.Logger;var Ws,Ks;!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"}(Ws||(Ns.Profile=Ws={})),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"}(Ks||(Ns.Level=Ks={}));class Js{constructor(e,t){this.profile=e,this.level=t}}Ns.ProfileLevelId=Js;const Qs=new Js(Ws.ConstrainedBaseline,Ks.L3_1);class Xs{constructor(e){this.mask=~no("x",e),this.masked_value=no("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}}class Ys{constructor(e,t,r){this.profile_idc=e,this.profile_iop=t,this.profile=r}}const Zs=[new Ys(66,new Xs("x1xx0000"),Ws.ConstrainedBaseline),new Ys(77,new Xs("1xxx0000"),Ws.ConstrainedBaseline),new Ys(88,new Xs("11xx0000"),Ws.ConstrainedBaseline),new Ys(66,new Xs("x0xx0000"),Ws.Baseline),new Ys(88,new Xs("10xx0000"),Ws.Baseline),new Ys(77,new Xs("0x0x0000"),Ws.Main),new Ys(100,new Xs("00000000"),Ws.High),new Ys(100,new Xs("00001100"),Ws.ConstrainedHigh),new Ys(244,new Xs("00000000"),Ws.PredictiveHigh444)];function eo(e){if("string"!=typeof e||6!==e.length)return;const t=parseInt(e,16);if(0===t)return;const r=255&t,n=t>>8&255,i=t>>16&255;let s;switch(r){case Ks.L1_1:s=0!=(16&n)?Ks.L1_b:Ks.L1_1;break;case Ks.L1:case Ks.L1_2:case Ks.L1_3:case Ks.L2:case Ks.L2_1:case Ks.L2_2:case Ks.L3:case Ks.L3_1:case Ks.L3_2:case Ks.L4:case Ks.L4_1:case Ks.L4_2:case Ks.L5:case Ks.L5_1:case Ks.L5_2:s=r;break;default:return void Hs.warn(`parseProfileLevelId() | unrecognized level_idc [str:${e}, level_idc:${r}]`)}for(const e of Zs)if(i===e.profile_idc&&e.profile_iop.isMatch(n))return new Js(e.profile,s);Hs.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${e}, profile_idc:${i}, profile_iop:${n}]`)}function to(e){if(e.level==Ks.L1_b)switch(e.profile){case Ws.ConstrainedBaseline:return"42f00b";case Ws.Baseline:return"42100b";case Ws.Main:return"4d100b";default:return void Hs.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${e.profile}`)}let t;switch(e.profile){case Ws.ConstrainedBaseline:t="42e0";break;case Ws.Baseline:t="4200";break;case Ws.Main:t="4d00";break;case Ws.ConstrainedHigh:t="640c";break;case Ws.High:t="6400";break;case Ws.PredictiveHigh444:t="f400";break;default:return void Hs.warn(`profileLevelIdToString() | unrecognized profile ${e.profile}`)}let r=e.level.toString(16);return 1===r.length&&(r=`0${r}`),`${t}${r}`}function ro(e={}){const t=e["profile-level-id"];return t?eo(t):Qs}function no(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)<<0}function io(e={}){const t=e["level-asymmetry-allowed"];return!0===t||1===t||"1"===t}Ns.parseProfileLevelId=eo,Ns.profileLevelIdToString=to,Ns.profileToString=function(e){switch(e){case Ws.ConstrainedBaseline:return"ConstrainedBaseline";case Ws.Baseline:return"Baseline";case Ws.Main:return"Main";case Ws.ConstrainedHigh:return"ConstrainedHigh";case Ws.High:return"High";case Ws.PredictiveHigh444:return"PredictiveHigh444";default:return void Hs.warn(`profileToString() | unrecognized profile ${e}`)}},Ns.levelToString=function(e){switch(e){case Ks.L1_b:return"1b";case Ks.L1:return"1";case Ks.L1_1:return"1.1";case Ks.L1_2:return"1.2";case Ks.L1_3:return"1.3";case Ks.L2:return"2";case Ks.L2_1:return"2.1";case Ks.L2_2:return"2.2";case Ks.L3:return"3";case Ks.L3_1:return"3.1";case Ks.L3_2:return"3.2";case Ks.L4:return"4";case Ks.L4_1:return"4.1";case Ks.L4_2:return"4.2";case Ks.L5:return"5";case Ks.L5_1:return"5.1";case Ks.L5_2:return"5.2";default:return void Hs.warn(`levelToString() | unrecognized level ${e}`)}},Ns.parseSdpProfileLevelId=ro,Ns.isSameProfile=function(e={},t={}){const r=ro(e),n=ro(t);return Boolean(r&&n&&r.profile===n.profile)},Ns.generateProfileLevelIdStringForAnswer=function(e={},t={}){if(!e["profile-level-id"]&&!t["profile-level-id"])return void Hs.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");const r=ro(e),n=ro(t);if(!r)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(r.profile!==n.profile)throw new TypeError("H264 Profile mismatch");const i=io(e)&&io(t),s=r.level,o=n.level,a=function(e,t){return e===Ks.L1_b?t!==Ks.L1&&t!==Ks.L1_b:t===Ks.L1_b?e!==Ks.L1:e<t}(c=s,d=o)?c:d;var c,d;const l=i?s:a;return Hs.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${r.profile}, level:${l}]`),to(new Js(r.profile,l))};var so,oo=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),ao=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),co=a&&a.__importStar||(so=function(e){return so=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},so(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=so(e),n=0;n<r.length;n++)"default"!==r[n]&&oo(t,e,r[n]);return ao(t,e),t});Object.defineProperty(As,"__esModule",{value:!0}),As.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)go(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)bo(t)},As.validateRtpParameters=mo,As.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")},As.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)},As.getExtendedRtpCapabilities=function(e,t){const r={codecs:[],headerExtensions:[]};for(const n of t.codecs??[]){if(So(n))continue;const t=(e.codecs??[]).find((e=>Co(e,n,{strict:!0,modify:!0})));if(!t)continue;const i={mimeType:t.mimeType,kind:t.kind,clockRate:t.clockRate,channels:t.channels,localPayloadType:t.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:n.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:t.parameters,remoteParameters:n.parameters,rtcpFeedback:To(t,n)};r.codecs.push(i)}for(const n of r.codecs){const r=e.codecs.find((e=>So(e)&&e.parameters.apt===n.localPayloadType)),i=t.codecs.find((e=>So(e)&&e.parameters.apt===n.remotePayloadType));r&&i&&(n.localRtxPayloadType=r.preferredPayloadType,n.remoteRtxPayloadType=i.preferredPayloadType)}for(const n of t.headerExtensions){const t=e.headerExtensions.find((e=>Ro(e,n)));if(!t)continue;const i={kind:n.kind,uri:n.uri,sendId:t.preferredId,recvId:n.preferredId,encrypt:t.preferredEncrypt,direction:"sendrecv"};switch(n.direction){case"sendrecv":i.direction="sendrecv";break;case"recvonly":i.direction="sendonly";break;case"sendonly":i.direction="recvonly";break;case"inactive":i.direction="inactive"}r.headerExtensions.push(i)}return r},As.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 n={mimeType:`${r.kind}/rtx`,kind:r.kind,preferredPayloadType:r.remoteRtxPayloadType,clockRate:r.clockRate,parameters:{apt:r.remotePayloadType},rtcpFeedback:[]};t.codecs.push(n)}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},As.getSendingRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};r.headerExtensions.push(t)}return r},As.getSendingRemoteRtpParameters=function(e,t){const r={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(const n of t.codecs){if(n.kind!==e)continue;const t={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(r.codecs.push(t),n.localRtxPayloadType){const e={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};r.codecs.push(e)}}for(const n of t.headerExtensions){if(n.kind&&n.kind!==e||"sendrecv"!==n.direction&&"sendonly"!==n.direction)continue;const t={uri:n.uri,id:n.sendId,encrypt:n.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},As.reduceCodecs=function(e,t){const r=[];if(t){for(let n=0;n<e.length;++n)if(Co(e[n],t,{strict:!0})){r.push(e[n]),So(e[n+1])&&r.push(e[n+1]);break}if(0===r.length)throw new TypeError("no matching codec found")}else r.push(e[0]),So(e[1])&&r.push(e[1]);return r},As.generateProbatorRtpParameters=function(e){mo(e=uo.clone(e));const t={mid:po,codecs:[],headerExtensions:[],encodings:[{ssrc:ho}],rtcp:{cname:"probator"}};return t.codecs.push(e.codecs[0]),t.codecs[0].payloadType=fo,t.headerExtensions=e.headerExtensions,t},As.canSend=function(e,t){return t.codecs.some((t=>t.kind===e))},As.canReceive=function(e,t){if(mo(e),0===e.codecs.length)return!1;const r=e.codecs[0];return t.codecs.some((e=>e.remotePayloadType===r.payloadType))};const lo=co(Ns),uo=co(Ms),po="probator",ho=1234,fo=127;function mo(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)yo(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)wo(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)_o(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 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(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)vo(t)}function vo(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 bo(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 yo(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)vo(t)}function wo(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 _o(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 So(e){return!!e&&/.+\/rtx$/i.test(e.mimeType)}function Co(e,t,{strict:r=!1,modify:n=!1}={}){const i=e.mimeType.toLowerCase();if(i!==t.mimeType.toLowerCase())return!1;if(e.clockRate!==t.clockRate)return!1;if(e.channels!==t.channels)return!1;switch(i){case"video/h264":if(r){if((e.parameters["packetization-mode"]||0)!==(t.parameters["packetization-mode"]||0))return!1;if(!lo.isSameProfile(e.parameters,t.parameters))return!1;let r;try{r=lo.generateProfileLevelIdStringForAnswer(e.parameters,t.parameters)}catch(e){return!1}n&&(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 Ro(e,t){return(!e.kind||!t.kind||e.kind===t.kind)&&e.uri===t.uri}function To(e,t){const r=[];for(const n of e.rtcpFeedback??[]){const e=(t.rtcpFeedback??[]).find((e=>e.type===n.type&&(e.parameter===n.parameter||!e.parameter&&!n.parameter)));e&&r.push(e)}return r}var ko={},Po={},Eo={};Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.Logger=void 0;const Oo=Us,Io="awaitqueue";Eo.Logger=class{constructor(e){e?(this._debug=(0,Oo.default)(`${Io}:${e}`),this._warn=(0,Oo.default)(`${Io}:WARN:${e}`),this._error=(0,Oo.default)(`${Io}:ERROR:${e}`)):(this._debug=(0,Oo.default)(Io),this._warn=(0,Oo.default)(`${Io}:WARN`),this._error=(0,Oo.default)(`${Io}: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(Po,"__esModule",{value:!0}),Po.AwaitQueue=Po.AwaitQueueRemovedTaskError=Po.AwaitQueueStoppedError=void 0;const Do=new Eo.Logger;class xo extends Error{constructor(e){super(e??"AwaitQueue stopped"),this.name="AwaitQueueStoppedError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,xo)}}Po.AwaitQueueStoppedError=xo;class Mo extends Error{constructor(e){super(e??"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Mo)}}Po.AwaitQueueRemovedTaskError=Mo;
|
|
2
2
|
/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
3
|
-
let as;es.AwaitQueue=class{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,is.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,n)=>{const i={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),is.debug(`resolving task [name:${i.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),is.debug(`rejecting task [name:${i.name}]: %s`,String(e)),n(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(i.id,i),1===this.pendingTasks.size&&this.execute(i)}))}stop(){is.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())is.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new ss);this.stopping=!1}remove(e){is.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new os):is.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(is.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)}}};var cs="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:a):e=>(as||(as=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),ds={};Object.defineProperty(ds,"__esModule",{value:!0}),ds.Producer=void 0;const ls=Bn,us=ii,ps=new Mn.Logger("Producer");class hs extends ls.EnhancedEventEmitter{constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:a,appData:c}){super(),this._closed=!1,this._observer=new ls.EnhancedEventEmitter,ps.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=r,this._track=n,this._kind=n.kind,this._rtpParameters=i,this._paused=!!o&&!n.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||(ps.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(ps.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new us.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){ps.debug("pause()"),this._closed?ps.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(){ps.debug("resume()"),this._closed?ps.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(ps.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch(e){}throw new us.InvalidStateError("closed")}if(e&&"ended"===e.readyState)throw new us.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()):ps.debug("replaceTrack() | same track, ignored")}async setMaxSpatialLayer(e){if(this._closed)throw new us.InvalidStateError("closed");if("video"!==this._kind)throw new us.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 us.InvalidStateError("closed");if("object"!=typeof e)throw new TypeError("invalid params");await new Promise(((t,r)=>{this.safeEmit("@setrtpencodingparameters",e,t,r)}))}onTrackEnded(){ps.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){}}}ds.Producer=hs;var fs={};Object.defineProperty(fs,"__esModule",{value:!0}),fs.Consumer=void 0;const ms=Bn,gs=ii,vs=new Mn.Logger("Consumer");class bs extends ms.EnhancedEventEmitter{constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,rtpParameters:s,appData:o}){super(),this._closed=!1,this._observer=new ms.EnhancedEventEmitter,vs.debug("constructor()"),this._id=e,this._localId=t,this._producerId=r,this._rtpReceiver=n,this._track=i,this._rtpParameters=s,this._paused=!i.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||(vs.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(vs.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new gs.InvalidStateError("closed");return new Promise(((e,t)=>{this.safeEmit("@getstats",e,t)}))}pause(){vs.debug("pause()"),this._closed?vs.error("pause() | Consumer closed"):this._paused?vs.debug("pause() | Consumer is already paused"):(this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause"))}resume(){vs.debug("resume()"),this._closed?vs.error("resume() | Consumer closed"):this._paused?(this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")):vs.debug("resume() | Consumer is already resumed")}onTrackEnded(){vs.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){}}}fs.Consumer=bs;var ys={};Object.defineProperty(ys,"__esModule",{value:!0}),ys.DataProducer=void 0;const ws=Bn,_s=ii,Ss=new Mn.Logger("DataProducer");class Cs extends ws.EnhancedEventEmitter{constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),this._closed=!1,this._observer=new ws.EnhancedEventEmitter,Ss.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},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||(Ss.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(Ss.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(Ss.debug("send()"),this._closed)throw new _s.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(Ss.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?Ss.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):Ss.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(Ss.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))})),this._dataChannel.addEventListener("message",(()=>{this._closed||Ss.warn('DataChannel "message" event in a DataProducer, message discarded')})),this._dataChannel.addEventListener("bufferedamountlow",(()=>{this._closed||this.safeEmit("bufferedamountlow")}))}}ys.DataProducer=Cs;var Rs={};Object.defineProperty(Rs,"__esModule",{value:!0}),Rs.DataConsumer=void 0;const Ts=Bn,ks=new Mn.Logger("DataConsumer");class Ps extends Ts.EnhancedEventEmitter{constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),this._closed=!1,this._observer=new Ts.EnhancedEventEmitter,ks.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,this._appData=i??{},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||(ks.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"))}transportClosed(){this._closed||(ks.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",(()=>{this._closed||(ks.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?ks.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",t.sctpCauseCode,t.message):ks.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)})),this._dataChannel.addEventListener("close",(()=>{this._closed||(ks.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)}))}}Rs.DataConsumer=Ps;var Es=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Os=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Is=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Es(r,t,n[i]);return Os(r,t),r}}(),Ds=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.Transport=void 0;const xs=es,Ms=Ds(cs),js=Mn,Ls=Bn,As=ii,Ns=Is(ai),Bs=Is(li),Fs=ds,zs=fs,Vs=ys,Us=Rs,$s=new js.Logger("Transport");class Gs{constructor(e){this.consumerOptions=e,this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}let qs=class extends Ls.EnhancedEventEmitter{constructor({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,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 xs.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 Ls.EnhancedEventEmitter,$s.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=Ns.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:n,dtlsParameters:i,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){$s.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 As.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if($s.debug("restartIce()"),this._closed)throw new As.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($s.debug("updateIceServers()"),this._closed)throw new As.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:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,onRtpSender:a,appData:c={}}={}){if($s.debug("produce() [track:%o]",e),this._closed)throw new As.InvalidStateError("closed");if(!e)throw new TypeError("missing track");if("send"!==this._direction)throw new As.UnsupportedError("not a sending Transport");if(!this._canProduceByKind[e.kind])throw new As.UnsupportedError(`cannot produce ${e.kind}`);if("ended"===e.readyState)throw new As.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:n,onRtpSender:a});try{Bs.validateRtpParameters(u);const{id:t}=await new Promise(((t,r)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:u,appData:c},t,r)})),r=new Fs.Producer({id:t,localId:l,rtpSender:p,track:e,rtpParameters:u,stopTracks:i,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(i)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,onRtpReceiver:s,appData:o={}}){if($s.debug("consume()"),this._closed)throw new As.InvalidStateError("closed");if("recv"!==this._direction)throw new As.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=Ns.clone(n);if(!Bs.canReceive(a,this._extendedRtpCapabilities))throw new As.UnsupportedError("cannot consume this Producer");const c=new Gs({id:e,producerId:t,kind:r,rtpParameters:a,streamId:i,onRtpReceiver:s,appData:o});return this._pendingConsumerTasks.push(c),(0,Ms.default)((()=>{this._closed||!1===this._consumerCreationInProgress&&this.createPendingConsumers()})),c.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:r,label:n="",protocol:i="",appData:s={}}={}){if($s.debug("produceData()"),this._closed)throw new As.InvalidStateError("closed");if("send"!==this._direction)throw new As.UnsupportedError("not a sending Transport");if(!this._maxSctpMessageSize)throw new As.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:n,protocol:i});Bs.validateSctpStreamParameters(a);const{id:c}=await new Promise(((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:n,protocol:i,appData:s},e,t)})),d=new Vs.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:n="",protocol:i="",appData:s={}}){if($s.debug("consumeData()"),this._closed)throw new As.InvalidStateError("closed");if("recv"!==this._direction)throw new As.UnsupportedError("not a receiving Transport");if(!this._maxSctpMessageSize)throw new As.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=Ns.clone(r);return Bs.validateSctpStreamParameters(o),this._awaitQueue.push((async()=>{const{dataChannel:r}=await this._handler.receiveDataChannel({sctpStreamParameters:o,label:n,protocol:i}),a=new Us.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 $s.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:n,rtpParameters:i,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o})}try{const n=await this._handler.receive(r);for(let r=0;r<n.length;++r){const i=e[r],s=n[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=i.consumerOptions,{localId:u,rtpReceiver:p,track:h}=s,f=new zs.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),i.resolve(f)}}catch(t){for(const r of e)r.reject(t)}if(t)try{const e=Bs.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:e}]),$s.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(e){$s.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 $s.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){$s.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 $s.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){$s.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 $s.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){$s.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 As.InvalidStateError("closed")):this.safeEmit("connect",{dtlsParameters:e},t,r)})),e.on("@icegatheringstatechange",(e=>{e!==this._iceGatheringState&&($s.debug("ICE gathering state changed to %s",e),this._iceGatheringState=e,this._closed||this.safeEmit("icegatheringstatechange",e))})),e.on("@connectionstatechange",(e=>{e!==this._connectionState&&($s.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=>$s.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,n)=>{this._awaitQueue.push((async()=>await this._handler.replaceTrack(e.localId,t)),"producer @replacetrack event").then(r).catch(n)})),e.on("@setmaxspatiallayer",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setMaxSpatialLayer(e.localId,t)),"producer @setmaxspatiallayer event").then(r).catch(n)})),e.on("@setrtpencodingparameters",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setRtpEncodingParameters(e.localId,t)),"producer @setrtpencodingparameters event").then(r).catch(n)})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new As.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,Ms.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,Ms.default)((()=>{this._closed||!1===this._consumerResumeInProgress&&this.resumePendingConsumers()}))})),e.on("@getstats",((t,r)=>{if(this._closed)return r(new As.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)}))}};Zi.Transport=qs;var Hs={},Ws={},Ks={},Js={exports:{}},Qs=Js.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(Qs).forEach((function(e){Qs[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Xs=Js.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=Xs,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[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=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+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,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(Ks);var Ys=Xs,Zs=/%[sdv%]/g,eo=function(e){var t=1,r=arguments,n=r.length;return e.replace(Zs,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},to=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return eo.apply(null,n)},ro=["v","o","s","i","u","e","p","c","b","t","r","z","a"],no=["i","c","b","a"],io=Ks,so=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||ro,n=t.innerOrder||no,i=[];return r.forEach((function(t){Ys[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(to(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(to(t,r,e))}))}))})),e.media.forEach((function(e){i.push(to("m",Ys.m[0],e)),n.forEach((function(t){Ys[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(to(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(to(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},oo=Xs;Ws.grammar=oo,Ws.write=so,Ws.parse=io.parse,Ws.parseParams=io.parseParams,Ws.parseFmtpConfig=io.parseFmtpConfig,Ws.parsePayloads=io.parsePayloads,Ws.parseRemoteCandidates=io.parseRemoteCandidates,Ws.parseImageAttributes=io.parseImageAttributes,Ws.parseSimulcastStreamList=io.parseSimulcastStreamList;var ao={},co=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),lo=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),uo=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&co(r,t,n[i]);return lo(r,t),r}}();Object.defineProperty(ao,"__esModule",{value:!0}),ao.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=[];let n=!1,i=!1;for(const s of e.media){const e=s.type;switch(e){case"audio":if(n)continue;n=!0;break;case"video":if(i)continue;i=!0;break;default:continue}for(const r of s.rtp){const n={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(n.preferredPayloadType,n)}for(const e of s.fmtp||[]){const r=po.parseParams(e.config),n=t.get(e.payload);n&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),n.parameters=r)}for(const r of s.rtcpFb||[]){const n={type:r.type,parameter:r.subtype};if(n.parameter||delete n.parameter,"*"!==r.payload){const e=t.get(r.payload);if(!e)continue;e.rtcpFeedback.push(n)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(n)}for(const t of s.ext||[]){if(t["encrypt-uri"])continue;const n={kind:e,uri:t.uri,preferredId:t.value};r.push(n)}}return{codecs:Array.from(t.values()),headerExtensions:r}},ao.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media||[]).find((e=>0!==e.port));t&&(r??(r=t.setup),n??(n=t.fingerprint))}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)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:n.type,value:n.hash}]}},ao.getCname=function({offerMediaObject:e}){const t=(e.ssrcs||[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},ao.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 n=t.fmtp.find((e=>e.payload===r.payloadType));n||(n={payload:r.payloadType,config:""},t.fmtp.push(n));const i=po.parseParams(n.config);switch(e){case"audio/opus":{const e=r.parameters["sprop-stereo"];void 0!==e&&(i.stereo=Number(e)?1:0);break}}n.config="";for(const e of Object.keys(i))n.config&&(n.config+=";"),n.config+=`${e}=${i[e]}`}};const po=uo(Ws);var ho={};Object.defineProperty(ho,"__esModule",{value:!0}),ho.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 n of e.ssrcGroups||[]){if("FID"!==n.semantics)continue;let[e,i]=n.ssrcs.split(/\s+/);e=Number(e),i=Number(i),t.has(e)&&(t.delete(e),t.delete(i),r.set(e,i))}for(const e of t)r.set(e,null);const n=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},ho.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[n,i]=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:`${n} ${i}`});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:`${n} ${i}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var fo={};Object.defineProperty(fo,"__esModule",{value:!0}),fo.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 mo={};Object.defineProperty(mo,"__esModule",{value:!0}),mo.HandlerInterface=void 0;const go=Bn;class vo extends go.EnhancedEventEmitter{constructor(){super()}}mo.HandlerInterface=vo;var bo={},yo={},wo=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),_o=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),So=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&wo(r,t,n[i]);return _o(r,t),r}}();Object.defineProperty(yo,"__esModule",{value:!0}),yo.OfferMediaSection=yo.AnswerMediaSection=yo.MediaSection=void 0;const Co=So(Ws),Ro=So(ai);class To{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:n=!1}){if(this._mediaObject={},this._planB=n,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}}yo.MediaSection=To;yo.AnswerMediaSection=class extends To{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,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,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.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:ko(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Ro.clone(e.parameters)??{};let n=Ro.clone(e.rtcpFeedback)??[];if(d){const{opusStereo:t,opusFec:i,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!==i&&(m.parameters.useinbandfec=i?1:0,r.useinbandfec=i?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)),n=n.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 i={payload:e.payloadType,config:""};for(const e of Object.keys(r))i.config&&(i.config+=";"),i.config+=`${e}=${r[e]}`;i.config&&this._mediaObject.fmtp.push(i);for(const t of n)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=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=n.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.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,n=Co.parseSimulcastStreamList(r);for(const e of n)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=n.map((e=>e.map((e=>`${e.paused?"~":""}${e.scid}`)).join(","))).join(";")}};function ko(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}yo.OfferMediaSection=class extends To{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,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,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=n?"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:ko(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=n.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize}):(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize)}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}planBReceive({offerRtpParameters:e,streamId:t,trackId:r}){const n=e.encodings[0],i=n.ssrc,s=n.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:ko(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:i,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:i,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:`${i} ${s}`}))}planBStopReceiving({offerRtpParameters:e}){const t=e.encodings[0],r=t.ssrc,n=t.rtx?.ssrc;this._mediaObject.ssrcs=this._mediaObject.ssrcs.filter((e=>e.id!==r&&e.id!==n)),n&&(this._mediaObject.ssrcGroups=this._mediaObject.ssrcGroups.filter((e=>e.ssrcs!==`${r} ${n}`)))}};var Po=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Eo=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Oo=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Po(r,t,n[i]);return Eo(r,t),r}}();Object.defineProperty(bo,"__esModule",{value:!0}),bo.RemoteSdp=void 0;const Io=Oo(Ws),Do=yo,xo=new Mn.Logger("RemoteSdp");bo.RemoteSdp=class{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,planB:s=!1}){if(this._mediaSections=[],this._midToIndex=new Map,this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,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:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){xo.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){xo.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:n,codecOptions:i,extmapAllowMixed:s=!1}){const o=new Do.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i,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:n,trackId:i}){const s=this._midToIndex.get(e);let o;if(void 0!==s&&(o=this._mediaSections[s]),o)o.planBReceive({offerRtpParameters:r,streamId:n,trackId:i}),this._replaceMediaSection(o);else{o=new Do.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i});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?(xo.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 Do.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 Do.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++,Io.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 n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.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 Mo={};Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.parse=function(e){const t=jo.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const jo=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var Lo=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Ao=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),No=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Lo(r,t,n[i]);return Ao(r,t),r}}();Object.defineProperty(Hs,"__esModule",{value:!0}),Hs.Chrome111=void 0;const Bo=No(Ws),Fo=Mn,zo=No(ai),Vo=No(li),Uo=No(ao),$o=No(ho),Go=No(fo),qo=ii,Ho=mo,Wo=bo,Ko=Mo,Jo=new Fo.Logger("Chrome111"),Qo={OS:1024,MIS:1024};class Xo extends Ho.HandlerInterface{static createFactory(){return()=>new Xo}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(Jo.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Jo.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=Bo.parse(t.sdp),n=Uo.extractRtpCapabilities({sdpObject:r});return Go.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Jo.debug("getNativeSctpCapabilities()"),{numStreams:Qo}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Jo.debug("run()"),this._direction=e,this._remoteSdp=new Wo.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Vo.getSendingRtpParameters("audio",d),video:Vo.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Vo.getSendingRemoteRtpParameters("audio",d),video:Vo.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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)})):(Jo.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(),Jo.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Jo.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Jo.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Jo.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Jo.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Jo.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:n,onRtpSender:i}){if(this.assertNotClosed(),this.assertSendDirection(),Jo.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,Ko.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const s=zo.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Vo.reduceCodecs(s.codecs,n);const o=zo.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Vo.reduceCodecs(o.codecs,n);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(c.sender);const d=await this._pc.createOffer();let l=Bo.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),Jo.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const u=c.mid;s.mid=u,l=Bo.parse(this._pc.localDescription.sdp);const p=l.media[a.idx];if(s.rtcp.cname=Uo.getCname({offerMediaObject:p}),t)if(1===t.length){const e=$o.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=$o.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 Jo.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(),Jo.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();Jo.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Jo.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Jo.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();Jo.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Jo.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Jo.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();Jo.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Jo.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Jo.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Jo.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(),Jo.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Jo.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Jo.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Jo.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Jo.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Jo.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Jo.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Qo.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Bo.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Jo.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Jo.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;Jo.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Jo.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Bo.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Uo.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Bo.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Jo.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Jo.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()};Jo.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Jo.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){Jo.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()};Jo.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Jo.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){Jo.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()};Jo.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Jo.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Jo.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()};Jo.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Bo.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Jo.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=Bo.parse(this._pc.localDescription.sdp));const r=Uo.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 qo.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')}}Hs.Chrome111=Xo;var Yo={},Zo=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),ea=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ta=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Zo(r,t,n[i]);return ea(r,t),r}}();Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.Chrome74=void 0;const ra=ta(Ws),na=Mn,ia=ta(ai),sa=ta(li),oa=ta(ao),aa=ta(ho),ca=ta(fo),da=ii,la=mo,ua=bo,pa=Mo,ha=new na.Logger("Chrome74"),fa={OS:1024,MIS:1024};class ma extends la.HandlerInterface{static createFactory(){return()=>new ma}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(ha.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){ha.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=ra.parse(t.sdp),n=oa.extractRtpCapabilities({sdpObject:r});return ca.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return ha.debug("getNativeSctpCapabilities()"),{numStreams:fa}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){ha.debug("run()"),this._direction=e,this._remoteSdp=new ua.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:sa.getSendingRtpParameters("audio",d),video:sa.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:sa.getSendingRemoteRtpParameters("audio",d),video:sa.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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)})):(ha.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(),ha.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),ha.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ha.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ha.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ha.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ha.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:n}){this.assertNotClosed(),this.assertSendDirection(),ha.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const i=ia.clone(this._sendingRtpParametersByKind[e.kind]);i.codecs=sa.reduceCodecs(i.codecs,n);const s=ia.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=sa.reduceCodecs(s.codecs,n);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=ra.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let u=!1;const p=(0,pa.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===i.codecs[0].mimeType.toLowerCase()&&(ha.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=ra.parse(d.sdp),c=l.media[o.idx],aa.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:ra.write(l)}),ha.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const h=a.mid;if(i.mid=h,l=ra.parse(this._pc.localDescription.sdp),c=l.media[o.idx],i.rtcp.cname=oa.getCname({offerMediaObject:c}),t)if(1===t.length){let e=aa.getRtpEncodings({offerMediaObject:c});Object.assign(e[0],t[0]),u&&(e=[e[0]]),i.encodings=e}else i.encodings=t;else i.encodings=aa.getRtpEncodings({offerMediaObject:c});if(i.encodings.length>1&&("video/vp8"===i.codecs[0].mimeType.toLowerCase()||"video/h264"===i.codecs[0].mimeType.toLowerCase()))for(const e of i.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:i,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return ha.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:i,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),ha.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();ha.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ha.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),ha.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();ha.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ha.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),ha.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();ha.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};ha.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?ha.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):ha.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(),ha.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();ha.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ha.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),ha.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();ha.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};ha.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};ha.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%fa.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=ra.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),ha.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};ha.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;ha.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};ha.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=ra.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));oa.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:ra.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),ha.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){ha.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()};ha.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ha.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){ha.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()};ha.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ha.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){ha.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()};ha.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ha.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};ha.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()};ha.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=ra.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}ha.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=ra.parse(this._pc.localDescription.sdp));const r=oa.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 da.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')}}Yo.Chrome74=ma;var ga={},va=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),ba=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ya=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&va(r,t,n[i]);return ba(r,t),r}}();Object.defineProperty(ga,"__esModule",{value:!0}),ga.Chrome70=void 0;const wa=ya(Ws),_a=Mn,Sa=ya(ai),Ca=ya(li),Ra=ya(ao),Ta=ya(ho),ka=mo,Pa=bo,Ea=Mo,Oa=new _a.Logger("Chrome70"),Ia={OS:1024,MIS:1024};class Da extends ka.HandlerInterface{static createFactory(){return()=>new Da}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(Oa.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Oa.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=wa.parse(t.sdp);return Ra.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Oa.debug("getNativeSctpCapabilities()"),{numStreams:Ia}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Oa.debug("run()"),this._direction=e,this._remoteSdp=new Pa.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Ca.getSendingRtpParameters("audio",d),video:Ca.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Ca.getSendingRemoteRtpParameters("audio",d),video:Ca.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(Oa.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){Oa.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Oa.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Oa.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Oa.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Oa.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Oa.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:n}){this.assertSendDirection(),Oa.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const i=Sa.clone(this._sendingRtpParametersByKind[e.kind]);i.codecs=Ca.reduceCodecs(i.codecs,n);const s=Sa.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=Ca.reduceCodecs(s.codecs,n);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let c,d=await this._pc.createOffer(),l=wa.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),t&&t.length>1&&(Oa.debug("send() | enabling legacy simulcast"),l=wa.parse(d.sdp),c=l.media[o.idx],Ta.addLegacySimulcast({offerMediaObject:c,numStreams:t.length}),d={type:"offer",sdp:wa.write(l)});let u=!1;const p=(0,Ea.parse)((t??[{}])[0].scalabilityMode);if(t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===i.codecs[0].mimeType.toLowerCase()&&(Oa.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=wa.parse(d.sdp),c=l.media[o.idx],Ta.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:wa.write(l)}),Oa.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d),t){Oa.debug("send() | applying given encodings");const e=a.sender.getParameters();for(let r=0;r<(e.encodings??[]).length;++r){const n=e.encodings[r],i=t[r];if(!i)break;e.encodings[r]=Object.assign(n,i)}await a.sender.setParameters(e)}const h=a.mid;if(i.mid=h,l=wa.parse(this._pc.localDescription.sdp),c=l.media[o.idx],i.rtcp.cname=Ra.getCname({offerMediaObject:c}),i.encodings=Ta.getRtpEncodings({offerMediaObject:c}),t)for(let e=0;e<i.encodings.length;++e)t[e]&&Object.assign(i.encodings[e],t[e]);if(u&&(i.encodings=[i.encodings[0]]),i.encodings.length>1&&("video/vp8"===i.codecs[0].mimeType.toLowerCase()||"video/h264"===i.codecs[0].mimeType.toLowerCase()))for(const e of i.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:i,answerRtpParameters:s,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Oa.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:i,rtpSender:a.sender}}async stopSending(e){this.assertSendDirection(),Oa.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();Oa.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Oa.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Oa.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Oa.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(),Oa.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Oa.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Oa.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Oa.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Oa.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Oa.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:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};Oa.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ia.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=wa.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Oa.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Oa.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;Oa.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Oa.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=wa.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Ra.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:wa.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Oa.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Oa.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()};Oa.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Oa.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Oa.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()};Oa.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=wa.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Oa.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=wa.parse(this._pc.localDescription.sdp));const r=Ra.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')}}ga.Chrome70=Da;var xa={},Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.getRtpEncodings=function({offerMediaObject:e,track:t}){const r=new Set;for(const n of e.ssrcs||[]){if("msid"!==n.attribute)continue;if(n.value.split(" ")[1]===t.id){const e=n.id;r.add(e)}}if(0===r.size)throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);const n=new Map;for(const t of e.ssrcGroups||[]){if("FID"!==t.semantics)continue;let[e,i]=t.ssrcs.split(/\s+/);e=Number(e),i=Number(i),r.has(e)&&(r.delete(e),r.delete(i),n.set(e,i))}for(const e of r)n.set(e,null);const i=[];for(const[e,t]of n){const r={ssrc:e};t&&(r.rtx={ssrc:t}),i.push(r)}return i},Ma.addLegacySimulcast=function({offerMediaObject:e,track:t,numStreams:r}){if(r<=1)throw new TypeError("numStreams must be greater than 1");let n,i,s;if(!(e.ssrcs||[]).find((e=>{if("msid"!==e.attribute)return!1;return e.value.split(" ")[1]===t.id&&(n=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])===n&&(i=Number(t[1]),!0)}));const o=e.ssrcs.find((e=>"cname"===e.attribute&&e.id===n));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(n+e),i&&d.push(i+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 n=c[r],i=d[r];e.ssrcs.push({id:i,attribute:"cname",value:a}),e.ssrcs.push({id:i,attribute:"msid",value:`${s} ${t.id}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${n} ${i}`})}};var ja=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),La=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Aa=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&ja(r,t,n[i]);return La(r,t),r}}();Object.defineProperty(xa,"__esModule",{value:!0}),xa.Chrome67=void 0;const Na=Aa(Ws),Ba=Mn,Fa=Aa(ai),za=Aa(li),Va=Aa(ao),Ua=Aa(Ma),$a=mo,Ga=bo,qa=new Ba.Logger("Chrome67"),Ha={OS:1024,MIS:1024};class Wa extends $a.HandlerInterface{static createFactory(){return()=>new Wa}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(qa.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){qa.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=Na.parse(t.sdp);return Va.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return qa.debug("getNativeSctpCapabilities()"),{numStreams:Ha}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){qa.debug("run()"),this._direction=e,this._remoteSdp=new Ga.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:za.getSendingRtpParameters("audio",d),video:za.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:za.getSendingRemoteRtpParameters("audio",d),video:za.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(qa.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){qa.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(qa.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});qa.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};qa.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};qa.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();qa.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:n}){this.assertSendDirection(),qa.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&qa.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let i,s=await this._pc.createOffer(),o=Na.parse(s.sdp);const a=Fa.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=za.reduceCodecs(a.codecs);const c=Fa.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=za.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(qa.debug("send() | enabling simulcast"),o=Na.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),Ua.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:Na.write(o)}),qa.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Na.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=Va.getCname({offerMediaObject:i}),a.encodings=Ua.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};qa.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(),qa.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();qa.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void qa.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};qa.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?qa.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):qa.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.track;await r.replaceTrack(t),n&&this._sendStream.removeTrack(n),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),qa.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(n)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),qa.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.setParameters(n)}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:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};qa.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ha.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Na.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),qa.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};qa.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,streamId:i}=t;qa.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:n,streamId:i??n.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};qa.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let n=await this._pc.createAnswer();const i=Na.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,s=i.media.find((e=>String(e.mid)===n));Va.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}n={type:"answer",sdp:Na.write(i)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:i}),qa.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const r of e){const{kind:e,trackId:n,rtpParameters:i}=r,s=n,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:i,rtpReceiver:a}),t.push({localId:s,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){qa.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()};qa.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();qa.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};qa.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()};qa.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Na.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}qa.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=Na.parse(this._pc.localDescription.sdp));const r=Va.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')}}xa.Chrome67=Wa;var Ka={},Ja=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Qa=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Xa=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Ja(r,t,n[i]);return Qa(r,t),r}}();Object.defineProperty(Ka,"__esModule",{value:!0}),Ka.Chrome55=void 0;const Ya=Xa(Ws),Za=Mn,ec=ii,tc=Xa(ai),rc=Xa(li),nc=Xa(ao),ic=Xa(Ma),sc=mo,oc=bo,ac=new Za.Logger("Chrome55"),cc={OS:1024,MIS:1024};class dc extends sc.HandlerInterface{static createFactory(){return()=>new dc}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(ac.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){ac.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=Ya.parse(t.sdp);return nc.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return ac.debug("getNativeSctpCapabilities()"),{numStreams:cc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){ac.debug("run()"),this._direction=e,this._remoteSdp=new oc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:rc.getSendingRtpParameters("audio",d),video:rc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:rc.getSendingRemoteRtpParameters("audio",d),video:rc.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(ac.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){ac.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(ac.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});ac.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};ac.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};ac.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();ac.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:n}){this.assertSendDirection(),ac.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&ac.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let i,s=await this._pc.createOffer(),o=Ya.parse(s.sdp);const a=tc.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=rc.reduceCodecs(a.codecs);const c=tc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=rc.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(ac.debug("send() | enabling simulcast"),o=Ya.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),ic.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:Ya.write(o)}),ac.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Ya.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=nc.getCname({offerMediaObject:i}),a.encodings=ic.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};ac.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(),ac.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();ac.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void ac.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};ac.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new ec.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new ec.UnsupportedError(" not implemented")}async setRtpEncodingParameters(e,t){throw new ec.UnsupportedError("not supported")}async getSenderStats(e){throw new ec.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};ac.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%cc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ya.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),ac.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};ac.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,streamId:i}=t;ac.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:n,streamId:i??n.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};ac.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let n=await this._pc.createAnswer();const i=Ya.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,s=i.media.find((e=>String(e.mid)===n));nc.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}n={type:"answer",sdp:Ya.write(i)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:i}),ac.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const r of e){const{kind:e,trackId:n,rtpParameters:i}=r,s=e,o=n,a=r.streamId??i.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:i}),t.push({localId:o,track:c})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){ac.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()};ac.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();ac.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new ec.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};ac.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()};ac.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ya.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}ac.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=Ya.parse(this._pc.localDescription.sdp));const r=nc.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')}}Ka.Chrome55=dc;var lc={},uc=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),pc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),hc=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&uc(r,t,n[i]);return pc(r,t),r}}();Object.defineProperty(lc,"__esModule",{value:!0}),lc.Firefox120=void 0;const fc=hc(Ws),mc=Mn,gc=ii,vc=hc(ai),bc=hc(li),yc=hc(ao),wc=hc(ho),_c=mo,Sc=bo,Cc=Mo,Rc=new mc.Logger("Firefox120"),Tc={OS:16,MIS:2048};class kc extends _c.HandlerInterface{static createFactory(){return()=>new kc}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(Rc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Rc.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 n=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const i=fc.parse(n.sdp);return yc.extractRtpCapabilities({sdpObject:i})}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw n}}async getNativeSctpCapabilities(){return Rc.debug("getNativeSctpCapabilities()"),{numStreams:Tc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Rc.debug("run()"),this._direction=e,this._remoteSdp=new Sc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:bc.getSendingRtpParameters("audio",d),video:bc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:bc.getSendingRemoteRtpParameters("audio",d),video:bc.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(Rc.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 gc.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Rc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Rc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Rc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Rc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Rc.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:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),Rc.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=vc.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=bc.reduceCodecs(s.codecs,n);const o=vc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=bc.reduceCodecs(o.codecs,n);const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(a.sender);const c=await this._pc.createOffer();let d=fc.parse(c.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});const l=(0,Cc.parse)((t??[{}])[0].scalabilityMode);Rc.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);const u=a.mid;s.mid=u,d=fc.parse(this._pc.localDescription.sdp);const p=d.media[d.media.length-1];if(s.rtcp.cname=yc.getCname({offerMediaObject:p}),t)if(1===t.length){const e=wc.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=wc.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 Rc.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(),Rc.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();Rc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Rc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Rc.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();Rc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Rc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Rc.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();Rc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Rc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Rc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Rc.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(),Rc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Rc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Rc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Rc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Rc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Rc.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Rc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Tc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=fc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Rc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Rc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;Rc.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Rc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=fc.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));yc.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:fc.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Rc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Rc.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()};Rc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Rc.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){Rc.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()};Rc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Rc.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){Rc.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()};Rc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Rc.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Rc.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()};Rc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=fc.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Rc.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=fc.parse(this._pc.localDescription.sdp));const r=yc.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 gc.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')}}lc.Firefox120=kc;var Pc={},Ec=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Oc=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Ec(r,t,n[i]);return Oc(r,t),r}}();Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.Firefox60=void 0;const Dc=Ic(Ws),xc=Mn,Mc=ii,jc=Ic(ai),Lc=Ic(li),Ac=Ic(ao),Nc=Ic(ho),Bc=mo,Fc=bo,zc=Mo,Vc=new xc.Logger("Firefox60"),Uc={OS:16,MIS:2048};class $c extends Bc.HandlerInterface{static createFactory(){return()=>new $c}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(Vc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Vc.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 n=e.addTransceiver(r,{direction:"sendrecv"}),i=n.sender.getParameters(),s=[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}];i.encodings=s,await n.sender.setParameters(i);const o=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const a=Dc.parse(o.sdp);return Ac.extractRtpCapabilities({sdpObject:a})}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw n}}async getNativeSctpCapabilities(){return Vc.debug("getNativeSctpCapabilities()"),{numStreams:Uc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Vc.debug("run()"),this._direction=e,this._remoteSdp=new Fc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Lc.getSendingRtpParameters("audio",d),video:Lc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Lc.getSendingRemoteRtpParameters("audio",d),video:Lc.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(Vc.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 Mc.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Vc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Vc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Vc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Vc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Vc.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:n}){this.assertNotClosed(),this.assertSendDirection(),Vc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&((t=jc.clone(t)).forEach(((e,t)=>{e.rid=`r${t}`})),t.reverse());const i=jc.clone(this._sendingRtpParametersByKind[e.kind]);i.codecs=Lc.reduceCodecs(i.codecs,n);const s=jc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=Lc.reduceCodecs(s.codecs,n);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=Dc.parse(a.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const d=(0,zc.parse)((t??[{}])[0].scalabilityMode);Vc.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const l=o.mid;i.mid=l,c=Dc.parse(this._pc.localDescription.sdp);const u=c.media[c.media.length-1];if(i.rtcp.cname=Ac.getCname({offerMediaObject:u}),t)if(1===t.length){const e=Nc.getRtpEncodings({offerMediaObject:u});Object.assign(e[0],t[0]),i.encodings=e}else i.encodings=t.reverse();else i.encodings=Nc.getRtpEncodings({offerMediaObject:u});if(i.encodings.length>1&&("video/vp8"===i.codecs[0].mimeType.toLowerCase()||"video/h264"===i.codecs[0].mimeType.toLowerCase()))for(const e of i.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${d.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:u,offerRtpParameters:i,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const p={type:"answer",sdp:this._remoteSdp.getSdp()};return Vc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",p),await this._pc.setRemoteDescription(p),this._mapMidTransceiver.set(l,o),{localId:l,rtpParameters:i,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),Vc.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();Vc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Vc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Vc.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();Vc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Vc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Vc.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();Vc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Vc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Vc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Vc.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(),Vc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();t=n.encodings.length-1-t,n.encodings.forEach(((e,r)=>{e.active=r>=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Vc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Vc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Vc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Vc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Vc.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Vc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Uc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Dc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Vc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Vc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;Vc.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Vc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=Dc.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));Ac.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:Dc.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Vc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Vc.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()};Vc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Vc.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){Vc.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()};Vc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Vc.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){Vc.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()};Vc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Vc.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Vc.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()};Vc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Dc.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Vc.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=Dc.parse(this._pc.localDescription.sdp));const r=Ac.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 Mc.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')}}Pc.Firefox60=$c;var Gc={},qc=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Hc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Wc=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&qc(r,t,n[i]);return Hc(r,t),r}}();Object.defineProperty(Gc,"__esModule",{value:!0});var Kc=Gc.Safari12=void 0;const Jc=Wc(Ws),Qc=Mn,Xc=Wc(ai),Yc=Wc(li),Zc=Wc(ao),ed=Wc(ho),td=Wc(fo),rd=ii,nd=mo,id=bo,sd=Mo,od=new Qc.Logger("Safari12"),ad={OS:1024,MIS:1024};class cd extends nd.HandlerInterface{static createFactory(){return()=>new cd}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(od.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){od.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=Jc.parse(t.sdp),n=Zc.extractRtpCapabilities({sdpObject:r});return td.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return od.debug("getNativeSctpCapabilities()"),{numStreams:ad}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),od.debug("run()"),this._direction=e,this._remoteSdp=new id.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Yc.getSendingRtpParameters("audio",d),video:Yc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Yc.getSendingRemoteRtpParameters("audio",d),video:Yc.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(od.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(),od.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),od.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});od.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};od.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};od.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();od.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:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),od.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=Xc.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Yc.reduceCodecs(s.codecs,n);const o=Xc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Yc.reduceCodecs(o.codecs,n);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});i&&i(c.sender);let d,l=await this._pc.createOffer(),u=Jc.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const p=(0,sd.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(od.debug("send() | enabling legacy simulcast"),u=Jc.parse(l.sdp),d=u.media[a.idx],ed.addLegacySimulcast({offerMediaObject:d,numStreams:t.length}),l={type:"offer",sdp:Jc.write(u)}),od.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);const h=c.mid;if(s.mid=h,u=Jc.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=Zc.getCname({offerMediaObject:d}),s.encodings=ed.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 od.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;od.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();od.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};od.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),od.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();od.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};od.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),od.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();od.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};od.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?od.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):od.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(),od.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();od.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};od.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),od.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();od.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};od.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};od.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ad.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Jc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),od.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};od.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;od.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};od.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=Jc.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Zc.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Jc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),od.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){od.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()};od.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();od.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){od.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()};od.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();od.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){od.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()};od.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();od.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};od.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()};od.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Jc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}od.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=Jc.parse(this._pc.localDescription.sdp));const r=Zc.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 rd.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')}}Kc=Gc.Safari12=cd;var dd={},ld=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),ud=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),pd=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&ld(r,t,n[i]);return ud(r,t),r}}();Object.defineProperty(dd,"__esModule",{value:!0}),dd.Safari11=void 0;const hd=pd(Ws),fd=Mn,md=pd(ai),gd=pd(li),vd=pd(ao),bd=pd(Ma),yd=mo,wd=bo,_d=new fd.Logger("Safari11"),Sd={OS:1024,MIS:1024};class Cd extends yd.HandlerInterface{static createFactory(){return()=>new Cd}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(_d.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){_d.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=hd.parse(t.sdp);return vd.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return _d.debug("getNativeSctpCapabilities()"),{numStreams:Sd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){_d.debug("run()"),this._direction=e,this._remoteSdp=new wd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:gd.getSendingRtpParameters("audio",d),video:gd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:gd.getSendingRemoteRtpParameters("audio",d),video:gd.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(_d.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){_d.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(_d.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});_d.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};_d.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};_d.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();_d.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:n}){this.assertSendDirection(),_d.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&_d.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let i,s=await this._pc.createOffer(),o=hd.parse(s.sdp);const a=md.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=gd.reduceCodecs(a.codecs);const c=md.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=gd.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(_d.debug("send() | enabling simulcast"),o=hd.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),bd.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:hd.write(o)}),_d.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=hd.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=vd.getCname({offerMediaObject:i}),a.encodings=bd.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};_d.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();_d.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void _d.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};_d.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?_d.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):_d.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.track;await r.replaceTrack(t),n&&this._sendStream.removeTrack(n),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),_d.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(n)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),_d.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.setParameters(n)}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:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};_d.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Sd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=hd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),_d.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};_d.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,streamId:i}=t;_d.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:n,streamId:i??n.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};_d.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let n=await this._pc.createAnswer();const i=hd.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,s=i.media.find((e=>String(e.mid)===n));vd.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}n={type:"answer",sdp:hd.write(i)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:i}),_d.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const r of e){const{kind:e,trackId:n,rtpParameters:i}=r,s=e,o=n,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:i,rtpReceiver:a}),t.push({localId:o,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){_d.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()};_d.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();_d.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};_d.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()};_d.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=hd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}_d.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=hd.parse(this._pc.localDescription.sdp));const r=vd.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')}}dd.Safari11=Cd;var Rd={},Td={},kd=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Pd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ed=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&kd(r,t,n[i]);return Pd(r,t),r}}();Object.defineProperty(Td,"__esModule",{value:!0}),Td.getCapabilities=function(){const e=RTCRtpReceiver.getCapabilities(),t=Od.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},Td.mangleRtpParameters=function(e){const t=Od.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 Od=Ed(ai);var Id=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Dd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),xd=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Id(r,t,n[i]);return Dd(r,t),r}}();Object.defineProperty(Rd,"__esModule",{value:!0}),Rd.Edge11=void 0;const Md=Mn,jd=ii,Ld=xd(ai),Ad=xd(li),Nd=xd(Td),Bd=mo,Fd=new Md.Logger("Edge11");class zd extends Bd.HandlerInterface{static createFactory(){return()=>new zd}constructor(){super(),this._rtpSenders=new Map,this._rtpReceivers=new Map,this._nextSendLocalId=0,this._transportReady=!1}get name(){return"Edge11"}close(){Fd.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 Fd.debug("getNativeRtpCapabilities()"),Nd.getCapabilities()}async getNativeSctpCapabilities(){return Fd.debug("getNativeSctpCapabilities()"),{numStreams:{OS:0,MIS:0}}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Fd.debug("run()"),this._sendingRtpParametersByKind={audio:Ad.getSendingRtpParameters("audio",d),video:Ad.getSendingRtpParameters("video",d)},this._remoteIceParameters=t,this._remoteIceCandidates=r,this._remoteDtlsParameters=n,this._cname=`CNAME-${Ld.generateRandomNumber()}`,this.setIceGatherer({iceServers:s,iceTransportPolicy:o}),this.setIceTransport(),this.setDtlsTransport()}async updateIceServers(e){throw new jd.UnsupportedError("not supported")}async restartIce(e){if(Fd.debug("restartIce()"),this._remoteIceParameters=e,this._transportReady){Fd.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:n}){Fd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),Fd.debug("send() | calling new RTCRtpSender()");const i=new RTCRtpSender(e,this._dtlsTransport),s=Ld.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Ad.reduceCodecs(s.codecs,n);const o=s.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));t||(t=[{}]);for(const e of t)e.ssrc=Ld.generateRandomNumber(),o&&(e.rtx={ssrc:Ld.generateRandomNumber()});s.encodings=t,s.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const a=Nd.mangleRtpParameters(s);Fd.debug("send() | calling rtpSender.send() [params:%o]",a),await i.send(a);const c=String(this._nextSendLocalId);return this._nextSendLocalId++,this._rtpSenders.set(c,i),{localId:c,rtpParameters:s,rtpSender:i}}async stopSending(e){Fd.debug("stopSending() [localId:%s]",e);const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");this._rtpSenders.delete(e);try{Fd.debug("stopSending() | calling rtpSender.stop()"),t.stop()}catch(e){throw Fd.warn("stopSending() | rtpSender.stop() failed:%o",e),e}}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){t?Fd.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Fd.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){Fd.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(n)}async setRtpEncodingParameters(e,t){Fd.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.setParameters(n)}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 jd.UnsupportedError("not implemented")}async receive(e){const t=[];for(const t of e){const{trackId:e,kind:r}=t;Fd.debug("receive() [trackId:%s, kind:%s]",e,r)}this._transportReady||await this.setupTransport({localDtlsRole:"server"});for(const r of e){const{trackId:e,kind:n,rtpParameters:i}=r;Fd.debug("receive() | calling new RTCRtpReceiver()");const s=new RTCRtpReceiver(this._dtlsTransport,n);s.addEventListener("error",(e=>{Fd.error('rtpReceiver "error" event [event:%o]',e)}));const o=Nd.mangleRtpParameters(i);Fd.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){Fd.debug("stopReceiving() [localId:%s]",t);const e=this._rtpReceivers.get(t);if(!e)throw new Error("RTCRtpReceiver not found");this._rtpReceivers.delete(t);try{Fd.debug("stopReceiving() | calling rtpReceiver.stop()"),e.stop()}catch(e){Fd.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 jd.UnsupportedError("not implemented")}setIceGatherer({iceServers:e,iceTransportPolicy:t}){const r=new RTCIceGatherer({iceServers:e??[],gatherPolicy:t??"all"});r.addEventListener("error",(e=>{Fd.error('iceGatherer "error" event [event:%o]',e)}));try{r.gather()}catch(e){Fd.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=>{Fd.debug('iceTransport "candidatepairchange" event [pair:%o]',e.pair)})),this._iceTransport=e}setDtlsTransport(){const e=new RTCDtlsTransport(this._iceTransport);e.addEventListener("statechange",(()=>{Fd.debug('dtlsTransport "statechange" event [state:%s]',e.state)})),e.addEventListener("dtlsstatechange",(()=>{Fd.debug('dtlsTransport "dtlsstatechange" event [state:%s]',e.state),"closed"===e.state&&this.emit("@connectionstatechange","closed")})),e.addEventListener("error",(e=>{Fd.error('dtlsTransport "error" event [event:%o]',e)})),this._dtlsTransport=e}async setupTransport({localDtlsRole:e}){Fd.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}}Rd.Edge11=zd;var Vd={},Ud=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),$d=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Gd=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Ud(r,t,n[i]);return $d(r,t),r}}();Object.defineProperty(Vd,"__esModule",{value:!0}),Vd.ReactNativeUnifiedPlan=void 0;const qd=Gd(Ws),Hd=Mn,Wd=Gd(ai),Kd=Gd(li),Jd=Gd(ao),Qd=Gd(ho),Xd=Gd(fo),Yd=ii,Zd=mo,el=bo,tl=Mo,rl=new Hd.Logger("ReactNativeUnifiedPlan"),nl={OS:1024,MIS:1024};class il extends Zd.HandlerInterface{static createFactory(){return()=>new il}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(rl.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(){rl.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=qd.parse(t.sdp),n=Jd.extractRtpCapabilities({sdpObject:r});return Xd.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return rl.debug("getNativeSctpCapabilities()"),{numStreams:nl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),rl.debug("run()"),this._direction=e,this._remoteSdp=new el.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Kd.getSendingRtpParameters("audio",d),video:Kd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Kd.getSendingRemoteRtpParameters("audio",d),video:Kd.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(rl.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(),rl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),rl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});rl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};rl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};rl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();rl.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:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),rl.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=Wd.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Kd.reduceCodecs(s.codecs,n);const o=Wd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Kd.reduceCodecs(o.codecs,n);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(c.sender);let d,l=await this._pc.createOffer(),u=qd.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let p=!1;const h=(0,tl.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===s.codecs[0].mimeType.toLowerCase()&&(rl.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,u=qd.parse(l.sdp),d=u.media[a.idx],Qd.addLegacySimulcast({offerMediaObject:d,numStreams:h.spatialLayers}),l={type:"offer",sdp:qd.write(u)}),rl.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);let f=c.mid??void 0;if(f||rl.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),s.mid=f,u=qd.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=Jd.getCname({offerMediaObject:d}),t)if(1===t.length){let e=Qd.getRtpEncodings({offerMediaObject:d});Object.assign(e[0],t[0]),p&&(e=[e[0]]),s.encodings=e}else s.encodings=t;else s.encodings=Qd.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 rl.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;rl.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();rl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};rl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),rl.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();rl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};rl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),rl.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();rl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};rl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?rl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):rl.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(),rl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();rl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};rl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),rl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();rl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};rl.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};rl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%nl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=qd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),rl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};rl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;rl.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};rl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=qd.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Jd.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:qd.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),rl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){rl.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()};rl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();rl.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){rl.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()};rl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();rl.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){rl.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()};rl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();rl.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};rl.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()};rl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=qd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}rl.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=qd.parse(this._pc.localDescription.sdp));const r=Jd.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 Yd.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')}}Vd.ReactNativeUnifiedPlan=il;var sl={},ol=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),al=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),cl=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&ol(r,t,n[i]);return al(r,t),r}}();Object.defineProperty(sl,"__esModule",{value:!0}),sl.ReactNative=void 0;const dl=cl(Ws),ll=Mn,ul=ii,pl=cl(ai),hl=cl(li),fl=cl(ao),ml=cl(Ma),gl=mo,vl=bo,bl=new ll.Logger("ReactNative"),yl={OS:1024,MIS:1024};class wl extends gl.HandlerInterface{static createFactory(){return()=>new wl}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(bl.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){bl.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=dl.parse(t.sdp);return fl.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return bl.debug("getNativeSctpCapabilities()"),{numStreams:yl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){bl.debug("run()"),this._direction=e,this._remoteSdp=new vl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:hl.getSendingRtpParameters("audio",d),video:hl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:hl.getSendingRemoteRtpParameters("audio",d),video:hl.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(bl.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){bl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(bl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});bl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};bl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};bl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();bl.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:n}){this.assertSendDirection(),bl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&bl.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let i,s=await this._pc.createOffer(),o=dl.parse(s.sdp);const a=pl.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=hl.reduceCodecs(a.codecs);const c=pl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=hl.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(bl.debug("send() | enabling simulcast"),o=dl.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),ml.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:dl.write(o)}),bl.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=dl.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=fl.getCname({offerMediaObject:i}),a.encodings=ml.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};bl.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(),bl.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();bl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void bl.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};bl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new ul.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new ul.UnsupportedError("not implemented")}async setRtpEncodingParameters(e,t){throw new ul.UnsupportedError("not implemented")}async getSenderStats(e){throw new ul.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};bl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%yl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=dl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),bl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};bl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i}=t;bl.debug("receive() [trackId:%s, kind:%s]",e,n);const s=n;let o=t.streamId??i.rtcp.cname;bl.debug("receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc"),o+=`-hack-${pl.generateRandomNumber()}`,r.set(e,o),this._remoteSdp.receive({mid:s,kind:n,offerRtpParameters:i,streamId:o,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};bl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=dl.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,i=s.media.find((e=>String(e.mid)===n));fl.applyCodecParameters({offerRtpParameters:r,answerMediaObject:i})}i={type:"answer",sdp:dl.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),bl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{kind:e,trackId:i,rtpParameters:s}=n,o=i,a=e,c=r.get(i),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){bl.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()};bl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();bl.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new ul.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};bl.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()};bl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=dl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}bl.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=dl.parse(this._pc.localDescription.sdp));const r=fl.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')}}sl.ReactNative=wl;var _l=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Sl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Cl=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&_l(r,t,n[i]);return Sl(r,t),r}}();Object.defineProperty(In,"__esModule",{value:!0}),In.Device=void 0,In.detectDevice=Gl;const Rl=xn,Tl=Mn,kl=Bn,Pl=ii,El=Cl(ai),Ol=Cl(li),Il=Zi,Dl=Hs,xl=Yo,Ml=ga,jl=xa,Ll=Ka,Al=lc,Nl=Pc,Bl=Gc,Fl=dd,zl=Rd,Vl=Vd,Ul=sl,$l=new Tl.Logger("Device");function Gl(e){if(!e&&"object"==typeof navigator&&"ReactNative"===navigator.product)return $l.debug("detectDevice() | React-Native detected"),"undefined"==typeof RTCPeerConnection?void $l.warn("detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?"):"undefined"!=typeof RTCRtpTransceiver?($l.debug("detectDevice() | ReactNative UnifiedPlan handler chosen"),"ReactNativeUnifiedPlan"):($l.debug("detectDevice() | ReactNative PlanB handler chosen"),"ReactNative");if(e||"object"==typeof navigator&&"string"==typeof navigator.userAgent){e??(e=navigator.userAgent);const t=new Rl.UAParser(e);$l.debug("detectDevice() | browser detected [userAgent:%s, parsed:%o]",e,t.getResult());const r=t.getBrowser(),n=r.name?.toLowerCase(),i=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=n&&["chrome","chromium","mobile chrome","chrome webview","chrome headless"].includes(n),f=n&&["firefox","mobile firefox","mobile focus"].includes(n),m=n&&["safari","mobile safari"].includes(n),g=n&&["edge"].includes(n);if((h||g)&&!p&&i>=111)return"Chrome111";if(h&&!p&&i>=74||g&&!p&&i>=88)return"Chrome74";if(h&&!p&&i>=70)return"Chrome70";if(h&&!p&&i>=67)return"Chrome67";if(h&&!p&&i>=55)return"Chrome55";if(f&&!p&&i>=120)return"Firefox120";if(f&&!p&&i>=60)return"Firefox60";if(f&&p&&d>=14.3)return"Safari12";if(m&&i>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(m&&i>=11)return"Safari11";if(g&&!p&&i>=11&&i<=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"}$l.warn("detectDevice() | browser not supported [name:%s, version:%s]",n,i)}else $l.warn("detectDevice() | unknown device")}In.Device=class{constructor({handlerName:e,handlerFactory:t}={}){if(this._loaded=!1,this._observer=new kl.EnhancedEventEmitter,$l.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)$l.debug("constructor() | handler given: %s",e);else{if(!(e=Gl()))throw new Pl.UnsupportedError("device not supported");$l.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=Dl.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=xl.Chrome74.createFactory();break;case"Chrome70":this._handlerFactory=Ml.Chrome70.createFactory();break;case"Chrome67":this._handlerFactory=jl.Chrome67.createFactory();break;case"Chrome55":this._handlerFactory=Ll.Chrome55.createFactory();break;case"Firefox120":this._handlerFactory=Al.Firefox120.createFactory();break;case"Firefox60":this._handlerFactory=Nl.Firefox60.createFactory();break;case"Safari12":this._handlerFactory=Bl.Safari12.createFactory();break;case"Safari11":this._handlerFactory=Fl.Safari11.createFactory();break;case"Edge11":this._handlerFactory=zl.Edge11.createFactory();break;case"ReactNativeUnifiedPlan":this._handlerFactory=Vl.ReactNativeUnifiedPlan.createFactory();break;case"ReactNative":this._handlerFactory=Ul.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 Pl.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Pl.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e}){let t;$l.debug("load() [routerRtpCapabilities:%o]",e);try{if(this._loaded)throw new Pl.InvalidStateError("already loaded");const r=El.clone(e);Ol.validateRtpCapabilities(r),t=this._handlerFactory();const n=await t.getNativeRtpCapabilities();$l.debug("load() | got native RTP capabilities:%o",n);const i=El.clone(n);Ol.validateRtpCapabilities(i),this._extendedRtpCapabilities=Ol.getExtendedRtpCapabilities(i,r),$l.debug("load() | got extended RTP capabilities:%o",this._extendedRtpCapabilities),this._canProduceByKind.audio=Ol.canSend("audio",this._extendedRtpCapabilities),this._canProduceByKind.video=Ol.canSend("video",this._extendedRtpCapabilities),this._recvRtpCapabilities=Ol.getRecvRtpCapabilities(this._extendedRtpCapabilities),Ol.validateRtpCapabilities(this._recvRtpCapabilities),$l.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._sctpCapabilities=await t.getNativeSctpCapabilities(),$l.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),Ol.validateSctpCapabilities(this._sctpCapabilities),$l.debug("load() succeeded"),this._loaded=!0,t.close()}catch(e){throw t&&t.close(),e}}canProduce(e){if(!this._loaded)throw new Pl.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:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return $l.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return $l.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l}){if(!this._loaded)throw new Pl.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(n))throw new TypeError("missing iceCandidates");if("object"!=typeof i)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 Il.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,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 ql={},Hl={};Object.defineProperty(Hl,"__esModule",{value:!0});var Wl={};function Kl(){}function Jl(){Jl.init.call(this)}function Ql(e){return void 0===e._maxListeners?Jl.defaultMaxListeners:e._maxListeners}function Xl(e,t,r,n){var i,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 Kl,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=Ql(e))&&i>0&&o.length>i){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 Yl(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Zl(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 eu(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Object.defineProperty(Wl,"__esModule",{value:!0}),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=a&&a.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(In,e),r(Zi,e),r(ds,e),r(fs,e),r(ys,e),r(Rs,e),r(Hl,e),r(Wl,e),r(mo,e),r(ii,e)}(ql),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=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}),n=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(n){if(n&&n.__esModule)return n;var i={};if(null!=n)for(var s=e(n),o=0;o<s.length;o++)"default"!==s[o]&&t(i,n,s[o]);return r(i,n),i}}(),i=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=i(On);e.debug=s.default;const o=In;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return o.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return o.detectDevice}});const c=n(ql);e.types=c,e.version="3.7.18";var d=Mo;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return d.parse}})}(Tn),Kl.prototype=Object.create(null),Jl.EventEmitter=Jl,Jl.usingDomains=!1,Jl.prototype.domain=void 0,Jl.prototype._events=void 0,Jl.prototype._maxListeners=void 0,Jl.defaultMaxListeners=10,Jl.init=function(){this.domain=null,Jl.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Kl,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Jl.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},Jl.prototype.getMaxListeners=function(){return Ql(this)},Jl.prototype.emit=function(e){var t,r,n,i,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(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=eu(e,n),s=0;s<n;++s)i[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=eu(e,i),o=0;o<i;++o)s[o].call(r,n)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=eu(e,s),a=0;a<s;++a)o[a].call(r,n,i)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=eu(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];!function(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=eu(e,i),o=0;o<i;++o)s[o].apply(r,n)}(r,l,this,i)}return!0},Jl.prototype.addListener=function(e,t){return Xl(this,e,t,!1)},Jl.prototype.on=Jl.prototype.addListener,Jl.prototype.prependListener=function(e,t){return Xl(this,e,t,!0)},Jl.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Yl(this,e,t)),this},Jl.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Yl(this,e,t)),this},Jl.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new Kl:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Kl,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},Jl.prototype.off=function(e,t){return this.removeListener(e,t)},Jl.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Kl,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new Kl:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new Kl,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},Jl.prototype.listeners=function(e){var t,r,n=this._events;return r=n&&(t=n[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},Jl.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Zl.call(e,t)},Jl.prototype.listenerCount=Zl,Jl.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const tu=Object.create(null);tu.open="0",tu.close="1",tu.ping="2",tu.pong="3",tu.message="4",tu.upgrade="5",tu.noop="6";const ru=Object.create(null);Object.keys(tu).forEach((e=>{ru[tu[e]]=e}));const nu={type:"error",data:"parser error"},iu="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),su="function"==typeof ArrayBuffer,ou=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,au=({type:e,data:t},r,n)=>iu&&t instanceof Blob?r?n(t):cu(t,n):su&&(t instanceof ArrayBuffer||ou(t))?r?n(t):cu(new Blob([t]),n):n(tu[e]+(t||"")),cu=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function du(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let lu;const uu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pu="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let sO=0;sO<64;sO++)pu[uu.charCodeAt(sO)]=sO;const hu="function"==typeof ArrayBuffer,fu=(e,t)=>{if("string"!=typeof e)return{type:"message",data:gu(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:mu(e.substring(1),t)};return ru[r]?e.length>1?{type:ru[r],data:e.substring(1)}:{type:ru[r]}:nu},mu=(e,t)=>{if(hu){const r=(e=>{let t,r,n,i,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=pu[e.charCodeAt(t)],n=pu[e.charCodeAt(t+1)],i=pu[e.charCodeAt(t+2)],s=pu[e.charCodeAt(t+3)],l[c++]=r<<2|n>>4,l[c++]=(15&n)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return d})(e);return gu(r,t)}return{base64:!0,data:e}},gu=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,vu=String.fromCharCode(30);function bu(){return new TransformStream({transform(e,t){!function(e,t){iu&&e.data instanceof Blob?e.data.arrayBuffer().then(du).then(t):su&&(e.data instanceof ArrayBuffer||ou(e.data))?t(du(e.data)):au(e,!1,(e=>{lu||(lu=new TextEncoder),t(lu.encode(e))}))}(e,(r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)}))}})}let yu;function wu(e){return e.reduce(((e,t)=>e+t.length),0)}function _u(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function Su(e){if(e)return function(e){for(var t in Su.prototype)e[t]=Su.prototype[t];return e}(e)}Su.prototype.on=Su.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Su.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Su.prototype.off=Su.prototype.removeListener=Su.prototype.removeAllListeners=Su.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},Su.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},Su.prototype.emitReserved=Su.prototype.emit,Su.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Su.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Cu="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Ru(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Tu=Cu.setTimeout,ku=Cu.clearTimeout;function Pu(e,t){t.useNativeTimers?(e.setTimeoutFn=Tu.bind(Cu),e.clearTimeoutFn=ku.bind(Cu)):(e.setTimeoutFn=Cu.setTimeout.bind(Cu),e.clearTimeoutFn=Cu.clearTimeout.bind(Cu))}class Eu extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class Ou extends Su{constructor(e){super(),this.writable=!1,Pu(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Eu(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=fu(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 Iu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Du=64,xu={};let Mu,ju=0,Lu=0;function Au(e){let t="";do{t=Iu[e%Du]+t,e=Math.floor(e/Du)}while(e>0);return t}function Nu(){const e=Au(+new Date);return e!==Mu?(ju=0,Mu=e):e+"."+Au(ju++)}for(;Lu<Du;Lu++)xu[Iu[Lu]]=Lu;let Bu=!1;try{Bu="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(oO){}const Fu=Bu;function zu(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Fu))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Cu[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function Vu(){}const Uu=null!=new zu({xdomain:!1}).responseType;class $u extends Su{constructor(e,t){super(),Pu(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 e;const t=Ru(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new zu(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=$u.requestsCount++,$u.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Vu,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete $u.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($u.requestsCount=0,$u.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",Gu);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Cu?"pagehide":"unload",Gu,!1)}function Gu(){for(let e in $u.requests)$u.requests.hasOwnProperty(e)&&$u.requests[e].abort()}const qu="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Hu=Cu.WebSocket||Cu.MozWebSocket,Wu="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const Ku={websocket:class extends Ou{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=Wu?{}:Ru(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=Wu?new Hu(e,t,r):t?new Hu(e,t):new Hu(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],n=t===e.length-1;au(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}n&&qu((()=>{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]=Nu()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!Hu}},webtransport:class extends Ou{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){yu||(yu=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(wu(r)<1)break;const e=_u(r,1);s=128==(128&e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(wu(r)<2)break;const e=_u(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(wu(r)<8)break;const e=_u(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(nu);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(wu(r)<i)break;const e=_u(r,i);a.enqueue(fu(s?e:yu.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(nu);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=bu();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),i())})).catch((e=>{}))};i();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],n=t===e.length-1;this.writer.write(r).then((()=>{n&&qu((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends Ou{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=Uu&&!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(vu),n=[];for(let e=0;e<r.length;e++){const i=fu(r[e],t);if(n.push(i),"error"===i.type)break}return n})(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,n=new Array(r);let i=0;e.forEach(((e,s)=>{au(e,!1,(e=>{n[s]=e,++i===r&&t(n.join(vu))}))}))})(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]=Nu()),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 $u(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}}},Ju=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Qu=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Xu(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=Ju.exec(e||""),s={},o=14;for(;o--;)s[Qu[o]]=i[o]||"";return-1!=r&&-1!=n&&(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,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,s.query),s}let Yu=class e extends Su{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Xu(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=Xu(t.host).host),Pu(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,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[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 Ku[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),n=!1;e.priorWebsocketSuccess=!1;const i=()=>{n||(r.send([{type:"ping",data:"probe"}]),r.once("packet",(t=>{if(!n)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((()=>{n||"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(){n||(n=!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",i),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",i),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((()=>{n||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 r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;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,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),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 n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};Yu.protocol=4;const Zu="function"==typeof ArrayBuffer,ep=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,tp=Object.prototype.toString,rp="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===tp.call(Blob),np="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===tp.call(File);function ip(e){return Zu&&(e instanceof ArrayBuffer||ep(e))||rp&&e instanceof Blob||np&&e instanceof File}function sp(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(sp(e[t]))return!0;return!1}if(ip(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return sp(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&sp(e[t]))return!0;return!1}function op(e){const t=[],r=e.data,n=e;return n.data=ap(r,t),n.attachments=t.length,{packet:n,buffers:t}}function ap(e,t){if(!e)return e;if(ip(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 n=0;n<e.length;n++)r[n]=ap(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=ap(e[n],t));return r}return e}function cp(e,t){return e.data=dp(e.data,t),delete e.attachments,e}function dp(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]=dp(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=dp(e[r],t));return e}const lp=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var up;!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"}(up||(up={}));function pp(e){return"[object Object]"===Object.prototype.toString.call(e)}class hp extends Su{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===up.BINARY_EVENT;r||t.type===up.BINARY_ACK?(t.type=r?up.EVENT:up.ACK,this.reconstructor=new fp(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!ip(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===up[r.type])throw new Error("unknown packet type "+r.type);if(r.type===up.BINARY_EVENT||r.type===up.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=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(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!hp.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case up.CONNECT:return pp(t);case up.DISCONNECT:return void 0===t;case up.CONNECT_ERROR:return"string"==typeof t||pp(t);case up.EVENT:case up.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===lp.indexOf(t[0]));case up.ACK:case up.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class fp{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=cp(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var mp=Object.freeze({__proto__:null,Decoder:hp,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==up.EVENT&&e.type!==up.ACK||!sp(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===up.EVENT?up.BINARY_EVENT:up.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==up.BINARY_EVENT&&e.type!==up.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=op(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},get PacketType(){return up},protocol:5});function gp(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const vp=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class bp extends Su{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=[gp(e,"open",this.onopen.bind(this)),gp(e,"packet",this.onpacket.bind(this)),gp(e,"error",this.onerror.bind(this)),gp(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(vp.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:up.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=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"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(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,...n)=>{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,...n)),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:up.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 up.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 up.EVENT:case up.BINARY_EVENT:this.onevent(e);break;case up.ACK:case up.BINARY_ACK:this.onack(e);break;case up.DISCONNECT:this.ondisconnect();break;case up.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(...n){r||(r=!0,t.packet({type:up.ACK,id:e,data:n}))}}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:up.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 yp(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}yp.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=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},yp.prototype.reset=function(){this.attempts=0},yp.prototype.setMin=function(e){this.ms=e},yp.prototype.setMax=function(e){this.max=e},yp.prototype.setJitter=function(e){this.jitter=e};class wp extends Su{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,Pu(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 yp({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||mp;this.encoder=new n.Encoder,this.decoder=new n.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 Yu(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=gp(t,"open",(function(){r.onopen(),e&&e()})),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=gp(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{n(),i(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(n),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(gp(e,"ping",this.onping.bind(this)),gp(e,"data",this.ondata.bind(this)),gp(e,"error",this.onerror.bind(this)),gp(e,"close",this.onclose.bind(this)),gp(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){qu((()=>{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 bp(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 _p={};function Sp(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=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),n=Xu(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=_p[i]&&s in _p[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new wp(n,t):(_p[i]||(_p[i]=new wp(n,t)),a=_p[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(Sp,{Manager:wp,Socket:bp,io:Sp,connect:Sp});var Cp={},Rp={exports:{}},Tp=Rp.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(Tp).forEach((function(e){Tp[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var kp=Rp.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=kp,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[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=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+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,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(Cp);var Pp=kp,Ep=/%[sdv%]/g,Op=function(e){var t=1,r=arguments,n=r.length;return e.replace(Ep,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},Ip=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return Op.apply(null,n)},Dp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],xp=["i","c","b","a"],Mp=Cp,jp=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||Dp,n=t.innerOrder||xp,i=[];return r.forEach((function(t){Pp[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Ip(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Ip(t,r,e))}))}))})),e.media.forEach((function(e){i.push(Ip("m",Pp.m[0],e)),n.forEach((function(t){Pp[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Ip(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Ip(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},Lp=jp,Ap=Mp.parse,Np={},Bp={},Fp={};Object.defineProperty(Fp,"__esModule",{value:!0}),Fp.isCorrect=Fp.isInSubnet=void 0,Fp.isInSubnet=function(e){return!(this.subnetMask<e.subnetMask)&&this.mask(e.subnetMask)===e.mask()},Fp.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}};var zp={};Object.defineProperty(zp,"__esModule",{value:!0}),zp.RE_SUBNET_STRING=zp.RE_ADDRESS=zp.GROUPS=zp.BITS=void 0,zp.BITS=32,zp.GROUPS=4,zp.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,zp.RE_SUBNET_STRING=/\/\d{1,2}$/;var Vp={};Object.defineProperty(Vp,"__esModule",{value:!0}),Vp.AddressError=void 0;class Up extends Error{constructor(e,t){super(e),this.name="AddressError",null!==t&&(this.parseMessage=t)}}Vp.AddressError=Up;var $p,Gp={exports:{}};$p=Gp,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 n="undefined"!=typeof navigator;n&&"Microsoft Internet Explorer"==navigator.appName?(t.prototype.am=function(e,t,r,n,i,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;i=((c=o*c+((32767&l)<<15)+r[n]+(1073741823&i))>>>30)+(l>>>15)+a*d+(i>>>30),r[n++]=1073741823&c}return i},e=30):n&&"Netscape"!=navigator.appName?(t.prototype.am=function(e,t,r,n,i,s){for(;--s>=0;){var o=t*this[e++]+r[n]+i;i=Math.floor(o/67108864),r[n++]=67108863&o}return i},e=26):(t.prototype.am=function(e,t,r,n,i,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;i=((c=o*c+((16383&l)<<14)+r[n]+i)>>28)+(l>>14)+a*d,r[n++]=268435455&c}return i},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 i,s,o="0123456789abcdefghijklmnopqrstuvwxyz",a=new Array;for(i="0".charCodeAt(0),s=0;s<=9;++s)a[i++]=s;for(i="a".charCodeAt(0),s=10;s<36;++s)a[i++]=s;for(i="A".charCodeAt(0),s=10;s<36;++s)a[i++]=s;function c(e){return o.charAt(e)}function d(e,t){var r=a[e.charCodeAt(t)];return null==r?-1:r}function l(e){var t=r();return t.fromInt(e),t}function u(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 p(e){this.m=e}function h(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 f(e,t){return e&t}function m(e,t){return e|t}function g(e,t){return e^t}function v(e,t){return e&~t}function b(e){if(0==e)return-1;var t=0;return 0==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function y(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function w(){}function _(e){return e}function S(e){this.r2=r(),this.q3=r(),t.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}p.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},p.prototype.revert=function(e){return e},p.prototype.reduce=function(e){e.divRemTo(this.m,null,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)},h.prototype.convert=function(e){var n=r();return e.abs().dlShiftTo(this.m.t,n),n.divRemTo(this.m,null,n),e.s<0&&n.compareTo(t.ZERO)>0&&this.m.subTo(n,n),n},h.prototype.revert=function(e){var t=r();return e.copyTo(t),this.reduce(t),t},h.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],n=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,n,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)},h.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},h.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 n;if(16==r)n=4;else if(8==r)n=3;else if(256==r)n=8;else if(2==r)n=1;else if(32==r)n=5;else{if(4!=r)return void this.fromRadix(e,r);n=2}this.t=0,this.s=0;for(var i=e.length,s=!1,o=0;--i>=0;){var a=8==n?255&e[i]:d(e,i);a<0?"-"==e.charAt(i)&&(s=!0):(s=!1,0==o?this[this.t++]=a:o+n>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+=n)>=this.DB&&(o-=this.DB))}8==n&&0!=(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,n=e%this.DB,i=this.DB-n,s=(1<<i)-1,o=Math.floor(e/this.DB),a=this.s<<n&this.DM;for(r=this.t-1;r>=0;--r)t[r+o+1]=this[r]>>i|a,a=(this[r]&s)<<n;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 n=e%this.DB,i=this.DB-n,s=(1<<n)-1;t[0]=this[r]>>n;for(var o=r+1;o<this.t;++o)t[o-r-1]|=(this[o]&s)<<i,t[o-r]=this[o]>>n;n>0&&(t[this.t-r-1]|=(this.s&s)<<i),t.t=this.t-r,t.clamp()}},t.prototype.subTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]-e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n-=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n-=e[r],t[r++]=n&this.DM,n>>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()},t.prototype.multiplyTo=function(e,r){var n=this.abs(),i=e.abs(),s=n.t;for(r.t=s+i.t;--s>=0;)r[s]=0;for(s=0;s<i.t;++s)r[s+n.t]=n.am(0,i[s],r,s,0,n.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 n=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,n,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,n,i){var s=e.abs();if(!(s.t<=0)){var o=this.abs();if(o.t<s.t)return null!=n&&n.fromInt(0),void(null!=i&&this.copyTo(i));null==i&&(i=r());var a=r(),c=this.s,d=e.s,l=this.DB-u(s[s.t-1]);l>0?(s.lShiftTo(l,a),o.lShiftTo(l,i)):(s.copyTo(a),o.copyTo(i));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=i.t,y=b-p,w=null==n?r():n;for(a.dlShiftTo(y,w),i.compareTo(w)>=0&&(i[i.t++]=1,i.subTo(w,i)),t.ONE.dlShiftTo(p,w),w.subTo(a,a);a.t<p;)a[a.t++]=0;for(;--y>=0;){var _=i[--b]==h?this.DM:Math.floor(i[b]*m+(i[b-1]+v)*g);if((i[b]+=a.am(0,_,i,y,0,p))<_)for(a.dlShiftTo(y,w),i.subTo(w,i);i[b]<--_;)i.subTo(w,i)}null!=n&&(i.drShiftTo(p,n),c!=d&&t.ZERO.subTo(n,n)),i.t=p,i.clamp(),l>0&&i.rShiftTo(l,i),c<0&&t.ZERO.subTo(i,i)}}},t.prototype.invDigit=function(){if(this.t<1)return 0;var e=this[0];if(0==(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,n){if(e>4294967295||e<1)return t.ONE;var i=r(),s=r(),o=n.convert(this),a=u(e)-1;for(o.copyTo(i);--a>=0;)if(n.sqrTo(i,s),(e&1<<a)>0)n.mulTo(s,o,i);else{var c=i;i=s,s=c}return n.revert(i)},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,n=(1<<t)-1,i=!1,s="",o=this.t,a=this.DB-o*this.DB%t;if(o-- >0)for(a<this.DB&&(r=this[o]>>a)>0&&(i=!0,s=c(r));o>=0;)a<t?(r=(this[o]&(1<<a)-1)<<t-a,r|=this[--o]>>(a+=this.DB-t)):(r=this[o]>>(a-=t)&n,a<=0&&(a+=this.DB,--o)),r>0&&(i=!0),i&&(s+=c(r));return i?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)+u(this[this.t-1]^this.s&this.DM)},t.prototype.mod=function(e){var n=r();return this.abs().divRemTo(e,null,n),this.s<0&&n.compareTo(t.ZERO)>0&&e.subTo(n,n),n},t.prototype.modPowInt=function(e,t){var r;return r=e<256||t.isEven()?new p(t):new h(t),this.exp(e,r)},t.ZERO=l(0),t.ONE=l(1),w.prototype.convert=_,w.prototype.revert=_,w.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r)},w.prototype.sqrTo=function(e,t){e.squareTo(t)},S.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},S.prototype.revert=function(e){return e},S.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)},S.prototype.mulTo=function(e,t,r){e.multiplyTo(t,r),this.reduce(r)},S.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var C,R,T,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],P=(1<<26)/k[k.length-1];function E(){var e;e=(new Date).getTime(),R[T++]^=255&e,R[T++]^=e>>8&255,R[T++]^=e>>16&255,R[T++]^=e>>24&255,T>=L&&(T-=L)}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),n=Math.pow(e,t),i=l(n),s=r(),o=r(),a="";for(this.divRemTo(i,s,o);s.signum()>0;)a=(n+o.intValue()).toString(e).substr(1)+a,s.divRemTo(i,s,o);return o.intValue().toString(e)+a},t.prototype.fromRadix=function(e,r){this.fromInt(0),null==r&&(r=10);for(var n=this.chunkSize(r),i=Math.pow(r,n),s=!1,o=0,a=0,c=0;c<e.length;++c){var l=d(e,c);l<0?"-"==e.charAt(c)&&0==this.signum()&&(s=!0):(a=r*a+l,++o>=n&&(this.dMultiply(i),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,n){if("number"==typeof r)if(e<2)this.fromInt(1);else for(this.fromNumber(e,n),this.testBit(e-1)||this.bitwiseTo(t.ONE.shiftLeft(e-1),m,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 i=new Array,s=7&e;i.length=1+(e>>3),r.nextBytes(i),s>0?i[0]&=(1<<s)-1:i[0]=0,this.fromString(i,256)}},t.prototype.bitwiseTo=function(e,t,r){var n,i,s=Math.min(e.t,this.t);for(n=0;n<s;++n)r[n]=t(this[n],e[n]);if(e.t<this.t){for(i=e.s&this.DM,n=s;n<this.t;++n)r[n]=t(this[n],i);r.t=this.t}else{for(i=this.s&this.DM,n=s;n<e.t;++n)r[n]=t(i,e[n]);r.t=e.t}r.s=t(this.s,e.s),r.clamp()},t.prototype.changeBit=function(e,r){var n=t.ONE.shiftLeft(e);return this.bitwiseTo(n,r,n),n},t.prototype.addTo=function(e,t){for(var r=0,n=0,i=Math.min(e.t,this.t);r<i;)n+=this[r]+e[r],t[r++]=n&this.DM,n>>=this.DB;if(e.t<this.t){for(n+=e.s;r<this.t;)n+=this[r],t[r++]=n&this.DM,n>>=this.DB;n+=this.s}else{for(n+=this.s;r<e.t;)n+=e[r],t[r++]=n&this.DM,n>>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),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 n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i<n;++i)r[i+this.t]=this.am(0,e[i],r,i,0,this.t);for(n=Math.min(e.t,t);i<n;++i)this.am(0,e[i],r,i,0,t-i);r.clamp()},t.prototype.multiplyUpperTo=function(e,t,r){--t;var n=r.t=this.t+e.t-t;for(r.s=0;--n>=0;)r[n]=0;for(n=Math.max(t-this.t,0);n<e.t;++n)r[this.t+n-t]=this.am(t-n,e[n],r,0,0,this.t+n-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 n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r},t.prototype.millerRabin=function(e){var n=this.subtract(t.ONE),i=n.getLowestSetBit();if(i<=0)return!1;var s=n.shiftRight(i);(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(n)){for(var d=1;d++<i&&0!=c.compareTo(n);)if(0==(c=c.modPowInt(2,this)).compareTo(t.ONE))return!1;if(0!=c.compareTo(n))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,n=this.DB-e*this.DB%8,i=0;if(e-- >0)for(n<this.DB&&(r=this[e]>>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<<this.DB-n);e>=0;)n<8?(r=(this[e]&(1<<n)-1)<<8-n,r|=this[--e]>>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=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,f,t),t},t.prototype.or=function(e){var t=r();return this.bitwiseTo(e,m,t),t},t.prototype.xor=function(e){var t=r();return this.bitwiseTo(e,g,t),t},t.prototype.andNot=function(e){var t=r();return this.bitwiseTo(e,v,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+b(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+=y(this[r]^t);return e},t.prototype.testBit=function(e){var t=Math.floor(e/this.DB);return t>=this.t?0!=this.s:0!=(this[t]&1<<e%this.DB)},t.prototype.setBit=function(e){return this.changeBit(e,m)},t.prototype.clearBit=function(e){return this.changeBit(e,v)},t.prototype.flipBit=function(e){return this.changeBit(e,g)},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(),n=r();return this.divRemTo(e,t,n),new Array(t,n)},t.prototype.modPow=function(e,t){var n,i,s=e.bitLength(),o=l(1);if(s<=0)return o;n=s<18?1:s<48?3:s<144?4:s<768?5:6,i=s<8?new p(t):t.isEven()?new S(t):new h(t);var a=new Array,c=3,d=n-1,f=(1<<n)-1;if(a[1]=i.convert(this),n>1){var m=r();for(i.sqrTo(a[1],m);c<=f;)a[c]=r(),i.mulTo(m,a[c-2],a[c]),c+=2}var g,v,b=e.t-1,y=!0,w=r();for(s=u(e[b])-1;b>=0;){for(s>=d?g=e[b]>>s-d&f:(g=(e[b]&(1<<s+1)-1)<<d-s,b>0&&(g|=e[b-1]>>this.DB+s-d)),c=n;0==(1&g);)g>>=1,--c;if((s-=c)<0&&(s+=this.DB,--b),y)a[g].copyTo(o),y=!1;else{for(;c>1;)i.sqrTo(o,w),i.sqrTo(w,o),c-=2;c>0?i.sqrTo(o,w):(v=o,o=w,w=v),i.mulTo(w,a[g],o)}for(;b>=0&&0==(e[b]&1<<s);)i.sqrTo(o,w),v=o,o=w,w=v,--s<0&&(s=this.DB-1,--b)}return i.revert(o)},t.prototype.modInverse=function(e){var r=e.isEven();if(this.isEven()&&r||0==e.signum())return t.ZERO;for(var n=e.clone(),i=this.clone(),s=l(1),o=l(0),a=l(0),c=l(1);0!=n.signum();){for(;n.isEven();)n.rShiftTo(1,n),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(;i.isEven();)i.rShiftTo(1,i),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);n.compareTo(i)>=0?(n.subTo(i,n),r&&s.subTo(a,s),o.subTo(c,o)):(i.subTo(n,i),r&&a.subTo(s,a),c.subTo(o,c))}return 0!=i.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 w)},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 n=t;t=r,r=n}var i=t.getLowestSetBit(),s=r.getLowestSetBit();if(s<0)return t;for(i<s&&(s=i),s>0&&(t.rShiftTo(s,t),r.rShiftTo(s,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,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 n=k[t],i=t+1;i<k.length&&n<P;)n*=k[i++];for(n=r.modInt(n);t<i;)if(n%k[t++]==0)return!1}return r.millerRabin(e)},t.prototype.square=function(){var e=r();return this.squareTo(e),e},t.prototype.Barrett=S,null==R){var O;if(R=new Array,T=0,"undefined"!=typeof window&&window.crypto)if(window.crypto.getRandomValues){var I=new Uint8Array(32);for(window.crypto.getRandomValues(I),O=0;O<32;++O)R[T++]=I[O]}else if("Netscape"==navigator.appName&&navigator.appVersion<"5"){var D=window.crypto.random(32);for(O=0;O<D.length;++O)R[T++]=255&D.charCodeAt(O)}for(;T<L;)O=Math.floor(65536*Math.random()),R[T++]=O>>>8,R[T++]=255&O;T=0,E()}function x(){if(null==C){for(E(),(C=new j).init(R),T=0;T<R.length;++T)R[T]=0;T=0}return C.next()}function M(){}function j(){this.i=0,this.j=0,this.S=new Array}M.prototype.nextBytes=function(e){var t;for(t=0;t<e.length;++t)e[t]=x()},j.prototype.init=function(e){var t,r,n;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,n=this.S[t],this.S[t]=this.S[r],this.S[r]=n;this.i=0,this.j=0},j.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 L=256;$p.exports={default:t,BigInteger:t,SecureRandom:M}}.call(a);var qp=Gp.exports,Hp={};!function(e){!function(){var t={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_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,n){var i,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(i=n[h],o=0;o<a.keys.length;o++){if(null==i)throw new Error(r('[sprintf] Cannot access property "%s" of undefined value "%s"',a.keys[o],a.keys[o-1]));i=i[a.keys[o]]}else i=a.param_no?n[a.param_no]:n[h++];if(t.not_type.test(a.type)&&t.not_primitive.test(a.type)&&i instanceof Function&&(i=i()),t.numeric_arg.test(a.type)&&"number"!=typeof i&&isNaN(i))throw new TypeError(r("[sprintf] expecting number but found %T",i));switch(t.number.test(a.type)&&(u=i>=0),a.type){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,a.width?parseInt(a.width):0);break;case"e":i=a.precision?parseFloat(i).toExponential(a.precision):parseFloat(i).toExponential();break;case"f":i=a.precision?parseFloat(i).toFixed(a.precision):parseFloat(i);break;case"g":i=a.precision?String(Number(i.toPrecision(a.precision))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=a.precision?i.substring(0,a.precision):i;break;case"t":i=String(!!i),i=a.precision?i.substring(0,a.precision):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=a.precision?i.substring(0,a.precision):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=a.precision?i.substring(0,a.precision):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(a.type)?m+=i:(!t.number.test(a.type)||u&&!a.sign?p="":(p=u?"+":"-",i=i.toString().replace(t.sign,"")),d=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+i).length,c=a.width&&l>0?d.repeat(l):"",m+=a.align?p+i+c:"0"===d?p+c+i:c+p+i)}return m}(function(e){if(i[e])return i[e];var r,n=e,s=[],o=0;for(;n;){if(null!==(r=t.text.exec(n)))s.push(r[0]);else if(null!==(r=t.modulo.exec(n)))s.push("%");else{if(null===(r=t.placeholder.exec(n)))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]})}n=n.substring(r[0].length)}return i[e]=s}(e),arguments)}function n(e,t){return r.apply(null,[e].concat(t||[]))}var i=Object.create(null);e.sprintf=r,e.vsprintf=n,"undefined"!=typeof window&&(window.sprintf=r,window.vsprintf=n)}()}(Hp);var Wp=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Kp=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Jp=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)&&Wp(t,e,r);return Kp(t,e),t};Object.defineProperty(Bp,"__esModule",{value:!0}),Bp.Address4=void 0;const Qp=Jp(Fp),Xp=Jp(zp),Yp=Vp,Zp=qp,eh=Hp;class th{constructor(e){this.groups=Xp.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=Qp.isCorrect(Xp.BITS),this.isInSubnet=Qp.isInSubnet,this.address=e;const t=Xp.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>Xp.BITS)throw new Yp.AddressError("Invalid subnet mask.");e=e.replace(Xp.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new th(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(Xp.RE_ADDRESS))throw new Yp.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 n;for(n=0;n<8;n+=2){const e=t.slice(n,n+2);r.push(parseInt(e,16))}return new th(r.join("."))}static fromInteger(e){return th.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new th(t)}toHex(){return this.parsedAddress.map((e=>(0,eh.sprintf)("%02x",parseInt(e,10)))).join(":")}toArray(){return this.parsedAddress.map((e=>parseInt(e,10)))}toGroup6(){const e=[];let t;for(t=0;t<Xp.GROUPS;t+=2){const r=(0,eh.sprintf)("%02x%02x",parseInt(this.parsedAddress[t],10),parseInt(this.parsedAddress[t+1],10));e.push((0,eh.sprintf)("%x",parseInt(r,16)))}return e.join(":")}bigInteger(){return new Zp.BigInteger(this.parsedAddress.map((e=>(0,eh.sprintf)("%02x",parseInt(e,10)))).join(""),16)}_startAddress(){return new Zp.BigInteger(this.mask()+"0".repeat(Xp.BITS-this.subnetMask),2)}startAddress(){return th.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new Zp.BigInteger("1");return th.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new Zp.BigInteger(this.mask()+"1".repeat(Xp.BITS-this.subnetMask),2)}endAddress(){return th.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new Zp.BigInteger("1");return th.fromBigInteger(this._endAddress().subtract(e))}static fromBigInteger(e){return th.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,eh.sprintf)("%s.in-addr.arpa.",t)}isMulticast(){return this.isInSubnet(new th("224.0.0.0/4"))}binaryZeroPad(){return this.bigInteger().toString(2).padStart(Xp.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(Xp.RE_ADDRESS,(0,eh.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(".")))}}Bp.Address4=th;var rh={},nh={};Object.defineProperty(nh,"__esModule",{value:!0}),nh.RE_URL_WITH_PORT=nh.RE_URL=nh.RE_ZONE_STRING=nh.RE_SUBNET_STRING=nh.RE_BAD_ADDRESS=nh.RE_BAD_CHARACTERS=nh.TYPES=nh.SCOPES=nh.GROUPS=nh.BITS=void 0,nh.BITS=128,nh.GROUPS=8,nh.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},nh.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"},nh.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,nh.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,nh.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,nh.RE_ZONE_STRING=/%.*$/,nh.RE_URL=new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/),nh.RE_URL_WITH_PORT=new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);var ih={};Object.defineProperty(ih,"__esModule",{value:!0}),ih.simpleGroup=ih.spanLeadingZeroes=ih.spanAll=ih.spanAllZeroes=void 0;const sh=Hp;function oh(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function ah(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}ih.spanAllZeroes=oh,ih.spanAll=function(e,t=0){return e.split("").map(((e,r)=>(0,sh.sprintf)('<span class="digit value-%s position-%d">%s</span>',e,r+t,oh(e)))).join("")},ih.spanLeadingZeroes=function(e){return e.split(":").map((e=>ah(e))).join(":")},ih.simpleGroup=function(e,t=0){return e.split(":").map(((e,r)=>/group-v4/.test(e)?e:(0,sh.sprintf)('<span class="hover-group group-%d">%s</span>',r+t,ah(e))))};var ch={},dh=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),lh=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),uh=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)&&dh(t,e,r);return lh(t,e),t};Object.defineProperty(ch,"__esModule",{value:!0}),ch.possibleElisions=ch.simpleRegularExpression=ch.ADDRESS_BOUNDARY=ch.padGroup=ch.groupPossibilities=void 0;const ph=uh(nh),hh=Hp;function fh(e){return(0,hh.sprintf)("(%s)",e.join("|"))}function mh(e){return e.length<4?(0,hh.sprintf)("0{0,%d}%s",4-e.length,e):e}ch.groupPossibilities=fh,ch.padGroup=mh,ch.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]",ch.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===ph.GROUPS-1?":":"";return fh([mh(e),t])}return mh(e)})).join(":")));return r.push(e.map(mh).join(":")),fh(r)},ch.possibleElisions=function(e,t,r){const n=t?"":":",i=r?"":":",s=[];t||r||s.push("::"),t&&r&&s.push(""),(r&&!t||!r&&t)&&s.push(":"),s.push((0,hh.sprintf)("%s(:0{1,4}){1,%d}",n,e-1)),s.push((0,hh.sprintf)("(0{1,4}:){1,%d}%s",e-1,i)),s.push((0,hh.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,hh.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}",r,e-r-t-1));return fh(s)};var gh=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),vh=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bh=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)&&gh(t,e,r);return vh(t,e),t};Object.defineProperty(rh,"__esModule",{value:!0}),rh.Address6=void 0;const yh=bh(Fp),wh=bh(zp),_h=bh(nh),Sh=bh(ih),Ch=Bp,Rh=ch,Th=Vp,kh=qp,Ph=Hp;function Eh(e){if(!e)throw new Error("Assertion failed.")}function Oh(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 Ih(e){return(0,Ph.sprintf)("%04x",parseInt(e,16))}function Dh(e){return 255&e}class xh{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=yh.isInSubnet,this.isCorrect=yh.isCorrect(_h.BITS),this.groups=void 0===t?_h.GROUPS:t,this.address=e;const r=_h.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>_h.BITS)throw new Th.AddressError("Invalid subnet mask.");e=e.replace(_h.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new Th.AddressError("Invalid subnet mask.");const n=_h.RE_ZONE_STRING.exec(e);n&&(this.zone=n[0],e=e.replace(_h.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new xh(e),!0}catch(e){return!1}}static fromBigInteger(e){const t=e.toString(16).padStart(32,"0"),r=[];let n;for(n=0;n<_h.GROUPS;n++)r.push(t.slice(4*n,4*(n+1)));return new xh(r.join(":"))}static fromURL(e){let t,r,n=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=_h.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],n=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=_h.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 n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new xh(t),port:n}}static fromAddress4(e){const t=new Ch.Address4(e),r=_h.BITS-(wh.BITS-t.subnetMask);return new xh(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new Th.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 xh(t)}microsoftTranscription(){return(0,Ph.sprintf)("%s.ipv6-literal.net",this.correctForm().replace(/:/g,"-"))}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=_h.BITS-this.subnetMask-Math.abs(e-_h.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 kh.BigInteger("2",10).pow(t).toString(10))}_startAddress(){return new kh.BigInteger(this.mask()+"0".repeat(_h.BITS-this.subnetMask),2)}startAddress(){return xh.fromBigInteger(this._startAddress())}startAddressExclusive(){const e=new kh.BigInteger("1");return xh.fromBigInteger(this._startAddress().add(e))}_endAddress(){return new kh.BigInteger(this.mask()+"1".repeat(_h.BITS-this.subnetMask),2)}endAddress(){return xh.fromBigInteger(this._endAddress())}endAddressExclusive(){const e=new kh.BigInteger("1");return xh.fromBigInteger(this._endAddress().subtract(e))}getScope(){let e=_h.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(_h.TYPES))if(this.isInSubnet(new xh(e)))return _h.TYPES[e];return"Global unicast"}getBits(e,t){return new kh.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,_h.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,Ph.sprintf)("%s.ip6.arpa.",r):e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const n=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&n.push([e-r,e-1]),r=0)}r>1&&n.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const i=n.map((e=>e[1]-e[0]+1));if(n.length>0){const e=i.indexOf(Math.max(...i));t=function(e,t){const r=[],n=[];let i;for(i=0;i<e.length;i++)i<t[0]?r.push(e[i]):i>t[1]&&n.push(e[i]);return r.concat(["compact"]).concat(n)}(this.parsedAddress,n[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(_h.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(wh.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new Ch.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new Th.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(wh.RE_ADDRESS,this.address4.parsedAddress.map(Oh).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(_h.RE_BAD_CHARACTERS);if(t)throw new Th.AddressError((0,Ph.sprintf)("Bad character%s detected in address: %s",t.length>1?"s":"",t.join("")),e.replace(_h.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(_h.RE_BAD_ADDRESS);if(r)throw new Th.AddressError((0,Ph.sprintf)("Address failed regex: %s",r.join("")),e.replace(_h.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let n=[];const i=e.split("::");if(2===i.length){let e=i[0].split(":"),t=i[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 Th.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,n=n.concat(e);for(let e=0;e<r;e++)n.push("0");n=n.concat(t)}else{if(1!==i.length)throw new Th.AddressError("Too many :: groups found");n=e.split(":"),this.elidedGroups=0}if(n=n.map((e=>(0,Ph.sprintf)("%x",parseInt(e,16)))),n.length!==this.groups)throw new Th.AddressError("Incorrect number of groups found");return n}canonicalForm(){return this.parsedAddress.map(Ih).join(":")}decimal(){return this.parsedAddress.map((e=>(0,Ph.sprintf)("%05d",parseInt(e,16)))).join(":")}bigInteger(){return new kh.BigInteger(this.parsedAddress.map(Ih).join(""),16)}to4(){const e=this.binaryZeroPad().split("");return Ch.Address4.fromHex(new kh.BigInteger(e.slice(96,128).join(""),2).toString(16))}to4in6(){const e=this.to4(),t=new xh(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 kh.BigInteger("ffff",16)).toString(),r=Ch.Address4.fromHex(this.getBitsBase16(32,64)),n=Ch.Address4.fromHex(this.getBits(96,128).xor(new kh.BigInteger("ffffffff",16)).toString(16)),i=this.getBits(64,80),s=this.getBitsBase2(64,80),o=i.testBit(15),a=i.testBit(14),c=i.testBit(8),d=i.testBit(9),l=new kh.BigInteger(s.slice(2,6)+s.slice(8,16),2).toString(10);return{prefix:(0,Ph.sprintf)("%s:%s",e.slice(0,4),e.slice(4,8)),server4:r.address,client4:n.address,flags:s,coneNat:o,microsoft:{reserved:a,universalLocal:d,groupIndividual:c,nonce:l},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=Ch.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:(0,Ph.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 xh(e)}toByteArray(){const e=this.bigInteger().toByteArray();return 17===e.length&&0===e[0]?e.slice(1):e}toUnsignedByteArray(){return this.toByteArray().map(Dh)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(Dh))}static fromUnsignedByteArray(e){const t=new kh.BigInteger("256",10);let r=new kh.BigInteger("0",10),n=new kh.BigInteger("1",10);for(let i=e.length-1;i>=0;i--)r=r.add(n.multiply(new kh.BigInteger(e[i].toString(10),10))),n=n.multiply(t);return xh.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 xh("2001::/32"))}is6to4(){return this.isInSubnet(new xh("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":(0,Ph.sprintf)(":%s",e),(0,Ph.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,Ph.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>',e.prefix,t.call(this),e.className):(0,Ph.sprintf)('<a href="%1$s%2$s">%2$s</a>',e.prefix,t.call(this))}group(){if(0===this.elidedGroups)return Sh.simpleGroup(this.address).join(":");Eh("number"==typeof this.elidedGroups),Eh("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...Sh.simpleGroup(t)):e.push("");const n=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)n.push((0,Ph.sprintf)("group-%d",e));return e.push((0,Ph.sprintf)('<span class="%s"></span>',n.join(" "))),r.length?e.push(...Sh.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Eh(this.address4 instanceof Ch.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new xh(this.correctForm());if(0===r.elidedGroups)t.push((0,Rh.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===_h.GROUPS)t.push((0,Rh.possibleElisions)(_h.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,Rh.simpleRegularExpression)(e[0].split(":"))),Eh("number"==typeof r.elidedGroups),t.push((0,Rh.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,Rh.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",Rh.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",Rh.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}rh.Address6=xh,function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=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}),n=a&&a.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(n,e,i);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;const i=Bp;Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});const s=rh;Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return s.Address6}});const o=Vp;Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}});const c=n(ih);e.v6={helpers:c}}(Np);var Mh={exports:{}};!function(e){(function(){var t,r,n,i,s,o,a,c;r={},null!==e&&e.exports?e.exports=r:this.ipaddr=r,a=function(e,t,r,n){var i,s;if(e.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;n>0;){if((s=r-n)<0&&(s=0),e[i]>>s!=t[i]>>s)return!1;n-=r,i+=1}return!0},r.subnetMatch=function(e,t,r){var n,i,s,o,a;for(s in null==r&&(r="unicast"),t)for(!(o=t[s])[0]||o[0]instanceof Array||(o=[o]),n=0,i=o.length;n<i;n++)if(a=o[n],e.kind()===a[0].kind()&&e.match.apply(e,a))return s;return r},r.IPv4=function(){function e(e){var t,r,n;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<=(n=e[t])&&n<=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,n,i,s,o;for(o={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},e=0,i=!1,t=r=3;r>=0;t=r+=-1){if(!((n=this.octets[t])in o))return null;if(s=o[n],i&&0!==s)return null;8!==s&&(i=!0),e+=s}return 32-e},e}(),n="(0?\\d+|0x[a-f0-9]+)",i={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},r.IPv4.parser=function(e){var t,r,n,s,o;if(r=function(e){return"0"===e[0]&&"x"!==e[1]?parseInt(e,8):parseInt(e)},t=e.match(i.fourOctet))return function(){var e,i,s,o;for(o=[],e=0,i=(s=t.slice(1,6)).length;e<i;e++)n=s[e],o.push(r(n));return o}();if(t=e.match(i.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,n,i,s,o,a;if(16===e.length)for(this.parts=[],r=n=0;n<=14;r=n+=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(i=0,s=(a=this.parts).length;i<s;i++)if(!(0<=(o=a[i])&&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,n,i;for(n=/((^|:)(0(:|$)){2,})/g,i=this.toNormalizedString(),e=0,t=-1;r=n.exec(i);)r[0].length>t&&(e=r.index,t=r[0].length);return t<0?i:i.substring(0,e)+"::"+i.substring(e+t)},e.prototype.toByteArray=function(){var e,t,r,n,i;for(e=[],t=0,r=(i=this.parts).length;t<r;t++)n=i[t],e.push(n>>8),e.push(255&n);return e},e.prototype.toNormalizedString=function(){var e,t,r;return e=function(){var e,r,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16));return i}.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,n,i;for(i=[],e=0,r=(n=this.parts).length;e<r;e++)t=n[e],i.push(t.toString(16).padStart(4,"0"));return i}.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,n;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=(n=this.parts.slice(-2))[0],t=n[1],new r.IPv4([e>>8,255&e,t>>8,255&t])},e.prototype.prefixLengthFromSubnetMask=function(){var e,t,r,n,i,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,i=!1,t=r=7;r>=0;t=r+=-1){if(!((n=this.parts[t])in o))return null;if(s=o[n],i&&0!==s)return null;16!==s&&(i=!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+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"("+c+")?$","i")},t=function(e,t){var r,n,i,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,n=-1;(n=e.indexOf(":",n+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,n,s;for(s=[],t=0,r=(n=e.split(":")).length;t<r;t++)i=n[t],s.push(parseInt(i,16));return s}(),zoneId:c}},r.IPv6.parser=function(e){var r,n,i,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(n=0,i=(c=[parseInt(s[2]),parseInt(s[3]),parseInt(s[4]),parseInt(s[5])]).length;n<i;n++)if(!(0<=(a=c[n])&&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,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=32)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},r.IPv4.subnetMaskFromPrefixLength=function(e){var t,r,n;if((e=parseInt(e))<0||e>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(n=[0,0,0,0],r=0,t=Math.floor(e/8);r<t;)n[r]=255,r++;return t<4&&(n[t]=Math.pow(2,e%8)-1<<8-e%8),new this(n)},r.IPv4.broadcastAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)|255^parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv4.networkAddressFromCIDR=function(e){var t,r,n,i,s;try{for(n=(t=this.parseCIDR(e))[0].toByteArray(),s=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],r=0;r<4;)i.push(parseInt(n[r],10)&parseInt(s[r],10)),r++;return new this(i)}catch(e){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},r.IPv6.parseCIDR=function(e){var t,r,n;if((r=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(r[2]))>=0&&t<=128)return n=[this.parse(r[1]),t],Object.defineProperty(n,"toString",{value:function(){return this.join("/")}}),n;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)}(Mh);var jh=Mh.exports,Lh=function(e,t){if("string"==typeof t)return Ah(e,t);if("object"==typeof t){for(var r=!1,n=0;n<t.length;n++)if(Ah(e,t[n])){r=!0;break}return r}};function Ah(e,t){try{var r=jh.process(e);if(-1===t.indexOf("/")){var n=jh.process(t);return"ipv6"===r.kind()&&"ipv6"===n.kind()?r.toNormalizedString()===n.toNormalizedString():r.toString()==n.toString()}var i=jh.parseCIDR(t);return r.match(i)}catch(e){return!1}}var Nh=Lh,Bh=/^((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]?)$/,Fh=["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"],zh=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"];for(var Vh=function(e){var t=[],r={originalIp:e,boiledIp:!1,isValid:!1,isBogon:!1,isApipa:!1,isMulticast:!1,isRfc1918:!1,isPublicIp:!1};if(Bh.test(e)){r.isValid=!0;for(var n=e.split("."),i=0;i<4;i++)t.push(parseInt(n[i],10));r.boiledIp=t.join("."),Nh(r.boiledIp,Fh)&&(r.isBogon=!0),Nh(r.boiledIp,"169.254.0.0/16")&&(r.isApipa=!0),Nh(r.boiledIp,"224.0.0.0/4")&&(r.isMulticast=!0),Nh(r.boiledIp,zh)?r.isRfc1918=!0:!1===r.isBogon&&(r.isPublicIp=!0)}return r},Uh=c(Vh),$h={exports:{}},Gh=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i,qh=[],Hh=0;Hh<256;Hh++)qh[Hh]=(Hh+256).toString(16).substr(1);$h.exports=function(e,t){var r;if(Buffer.isBuffer(e))r=function(e,t){var r=t||0,n=qh;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]}(e);else{if("[object String]"!==Object.prototype.toString.call(e))return!1;r=e}if(r=r.toLowerCase(),!Gh.test(r))return!1;if(void 0===t)t=Wh(r);else if(Wh(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 Wh=$h.exports.version=function(e){return 0|e.charAt(14)},Kh=c($h.exports);const Jh=new URLSearchParams(window.location.search).has("debug");class Qh{constructor(){this._isEnabled=!1,this._isEnabled=Jh}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 Xh(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,hn.default;const Yh={id:Sn(),connectionNumber:0},Zh=()=>{};let ef=Zh;const tf=function(e,t=console){const r=[];let n,i,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==n||n.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?i=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==n?void 0:n.readyState)===WebSocket.OPEN?(m=0,n.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==n?void 0:n.readyState)===WebSocket.CLOSED&&d&&setTimeout((()=>{n.readyState===WebSocket.CLOSED&&d&&b.connect()}),1e3*m)},close:()=>{d=!1,null==n||n.close()},connect:()=>{d=!0,m+=1,null==n||n.close(),b.connected=!0,n=new WebSocket(e+window.location.pathname,"1.0"),n.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},n.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),ef()},n.onopen=()=>{for(Yh.connectionNumber++,n.send(JSON.stringify(["clientInfo",null,Yh])),i&&n.send(JSON.stringify(i)),s&&n.send(JSON.stringify(s)),c&&n.send(JSON.stringify(c)),o&&n.send(JSON.stringify(o)),a&&n.send(JSON.stringify(a)),l&&n.send(JSON.stringify(l)),p&&n.send(JSON.stringify(p)),u&&n.send(JSON.stringify(u)),h&&n.send(JSON.stringify(h)),f&&n.send(JSON.stringify(f));r.length;)n.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),rf=gn(tf.trace,1e4,[""]);ef=(null==rf?void 0:rf.resetDelta)||Zh;const nf={sendEvent:(e,t)=>{tf.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{nf.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{nf.sendEvent("video_muted",{muted:e})},server:tf};let sf=[],of=0;const af=new WeakMap,cf=e=>{sf=sf.filter((t=>t!==e))};if(window.RTCPeerConnection){const aO=window.RTCPeerConnection;function cO(e){const t=new aO(e);sf.push(t),af.set(t,{index:of++});const r=()=>{"closed"===t.connectionState&&(cf(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}cO.prototype=aO.prototype,window.RTCPeerConnection=cO}const df=e=>{var t;return null===(t=af.get(e))||void 0===t?void 0:t.index},lf=new WeakMap;const uf=()=>Promise.all(sf.map((e=>Xh(void 0,void 0,void 0,(function*(){let t=lf.get(e);t||(t={ssrcToTrackId:{}},lf.set(e,t));try{const r=yield e.getStats();let n=null;if(r.forEach((e=>{if(!("inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||e.trackIdentifier||t.ssrcToTrackId[e.ssrc])){if(e.mediaSourceId){const n=r.get(e.mediaSourceId);n&&n.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=n.trackIdentifier)}if(!t.ssrcToTrackId[e.ssrc]&&e.trackId){const n=r.get(e.trackId);n&&n.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=n.trackIdentifier)}t.ssrcToTrackId[e.ssrc]||(n||(n=[]),n.push(e.ssrc))}})),n){const r=[...e.getSenders(),...e.getReceivers()];(yield Promise.all(r.map((e=>e.getStats())))).forEach(((e,n)=>{e.forEach((e=>{"inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||(t.ssrcToTrackId[e.ssrc]=r[n].track.id)}))})),n.forEach((e=>{t.ssrcToTrackId[e]||(t.ssrcToTrackId[e]="?"+e)}))}return[e,r,t]}catch(r){return nf.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]}}))))),pf=(e,t,r,n,i,s)=>{let o=e[n];o||(o={tracks:{},startTime:t,updated:t},e[n]=o),o.updated=t;let a=o.tracks[i];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[i]=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},hf=(e,t)=>{Object.entries(e).forEach((([r,n])=>{n.updated<t?delete e[r]:Object.entries(n.tracks).forEach((([e,r])=>{r.updated<t?delete n.tracks[e]:Object.entries(r.ssrcs).forEach((([e,n])=>{n.updated<t&&delete r.ssrcs[e]}))}))}))};function ff(e,{logger:t,interval:r},n){return Xh(this,void 0,void 0,(function*(){const i=ff.bind(null,e,{interval:r,logger:t});try{const t=e.getClients(),s=t.find((e=>e.isLocalClient&&!e.isPresentation))||{id:"unknown"};let o=e.statsByView[s.id];o||(o={tracks:{},candidatePairs:{},pressure:null},e.statsByView[s.id]=o),o.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return n?e.statsByView:(e.subscriptions.forEach((r=>{var n;return null===(n=r.onUpdatedStats)||void 0===n?void 0:n.call(r,e.statsByView,t)})),void(e.nextTimeout=setTimeout(i,r)));if(e.lastUpdateTime=Date.now(),(yield uf()).forEach((([n,i,a])=>{const c=df(n);"closed"===n.connectionState&&(i=new Map,cf(n)),a.previousSSRCs=a.currentSSRCs||{},a.currentSSRCs={},i.forEach((n=>{var d,l,u;if("candidate-pair"===n.type&&/inprogress|succeeded/.test(n.state)){const t=null===(d=a._oldReport)||void 0===d?void 0:d.get(n.id),s=t?n.timestamp-t.timestamp:r,l=c+":"+n.id;let u=o.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},o.candidatePairs[l]=u),function(e,t,r,n,i){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/n,e.bitrateOut=8e3*o/n,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=i.get(t.remoteCandidateId),c=i.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,n,t,s,i),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===n.type||"outbound-rtp"===n.type){const o=n.mediaType||n.kind,d=n.ssrc;let p=n.trackIdentifier||a.ssrcToTrackId[d],h=null===(l=a._oldReport)||void 0===l?void 0:l.get(n.id);if(h&&h.mediaSourceId!==n.mediaSourceId){const e=i.get(n.mediaSourceId);e&&e.trackIdentifier&&(p=e.trackIdentifier,a.ssrcToTrackId[d]=p)}const f=t.find((e=>{var t;return(null===(t=e[o].track)||void 0===t?void 0:t.id)===p}))||s;if(!n.trackIdentifier&&a.ssrcToTrackId[d]&&(null===(u=f[o].track)||void 0===u?void 0:u.id)&&f[o].track.id!==a.ssrcToTrackId[d]&&(p=f[o].track.id,a.ssrcToTrackId[d]=f[o].track.id),a.currentSSRCs[d]=f.id,h){const e=i.get(n.transportId),t=a._oldReport.get(h.transportId);(t&&(null==e?void 0:e.selectedCandidatePairId)!==t.selectedCandidatePairId||n.bytesReceived<h.bytesReceived||n.bytesSent<h.bytesSent)&&(h=null)}const m=h?n.timestamp-h.timestamp:r,g=pf(e.statsByView,e.lastUpdateTime,c,f.id,p,d);!function(e,t,r,n,i){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&&i.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,n,0,0,i),function(e,t,r,n,i){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/n,"in"===e.direction){const i=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+i,e.packetRate=1e3*i/n;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/n,e.lossRatio=s/(s+i)*1e3/n;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/n,e.mediaRatio=o/c,"audio"===t.kind){const n=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=n/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/n;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/n,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/n,t.remoteId){const r=i.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,n,h,m,i),"video"===o&&function(e,t,r,n,i){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/n;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/n,"in"===e.direction){const i=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+i,e.kfRate=1e3*i/n;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/n}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/n;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/n;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=i.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,n,h,m,i),"audio"===o&&function(e,t,r,n,i){const s=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+s,"in"===e.direction){const n=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),i=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(n/i);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,n,h)}})),a._oldReport=i,Object.keys(a.previousSSRCs).filter((e=>!a.currentSSRCs[e])).forEach((t=>{const r=a.previousSSRCs[t];if(r){const n=e.statsByView[r];n&&Object.values(n.tracks).forEach((e=>{e.ssrcs[t]&&delete e.ssrcs[t]}))}}))})),hf(e.statsByView,e.lastUpdateTime),Object.entries((null==o?void 0:o.candidatePairs)||{}).forEach((([t,r])=>{const n=r.lastRtcStatsTime===e.lastUpdateTime;r.active=n,n||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete o.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)})),n)return e.statsByView;e.subscriptions.forEach((r=>{var n;return null===(n=r.onUpdatedStats)||void 0===n?void 0:n.call(r,e.statsByView,t)}))}catch(r){t.warn(r),e.numFailedStatsReports++,nf.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}e.nextTimeout=setTimeout(i,r)}))}const mf={};function gf(e,t=mf,r=window.document){e.forEach((({hostnamePattern:e,token:n})=>{const i=`${e}-${n}`;if(!t[i]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=n,r.head.append(e),t[i]=!0}}))}const vf={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const bf={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},yf={interval:2e3,logger:new Qh},wf=()=>{var e;return null===(e=bf.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function _f(e,{interval:t,logger:r}){const n=ff.bind(null,e,{interval:t,logger:r});let i;try{i=function(e,{sampleRate:t,originTrials:r}=vf,n=globalThis.window){let i;if(gf(r),"PressureObserver"in n)return i=new n.PressureObserver(e,{sampleRate:t}),i.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{i.unobserve("cpu")}}}((t=>e.lastPressureObserverRecord=t.pop()))}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(n,t),{getUpdatedStats:()=>n(!0),stop:()=>{clearTimeout(e.nextTimeout),i&&i.stop()}}}class Sf 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 Cf(e){if(e.message instanceof Error)throw e.message;throw new Sf(e)}function Rf(...e){!function(e,t,r,n){if(!r){let i=!1;if(0===t)i=!0,n="No value argument passed to `assert.ok()`";else if(n instanceof Error)throw n;const s=new Sf({actual:r,expected:!0,message:n,operator:"==",stackStartFn:e});throw s.generatedMessage=i,s}}(Rf,e.length,...e)}const Tf={fail:e=>{Cf({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:Tf.fail})},ok:Rf,notEqual:function e(t,r,n){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&Cf({actual:t,expected:r,message:n,operator:"!=",stackStartFn:e})}};Tf.ok=Rf;const kf=()=>{let e=Tn.detectDevice()||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);return/iphone|ipad/i.test(navigator.userAgent)&&(e="Safari12"),e},Pf="[a-fA-F\\d:]",Ef=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${Pf})|(?<=${Pf})(?=\\s|$))`:"",Of="(?: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}",If="[a-fA-F\\d]{1,4}",Df=`\n(?:\n(?:${If}:){7}(?:${If}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${If}:){6}(?:${Of}|:${If}|:)| // 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(?:${If}:){5}(?::${Of}|(?::${If}){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(?:${If}:){4}(?:(?::${If}){0,1}:${Of}|(?::${If}){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(?:${If}:){3}(?:(?::${If}){0,2}:${Of}|(?::${If}){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(?:${If}:){2}(?:(?::${If}){0,3}:${Of}|(?::${If}){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(?:${If}:){1}(?:(?::${If}){0,4}:${Of}|(?::${If}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${If}){0,5}:${Of}|(?::${If}){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(),xf=new RegExp(`(?:^${Of}$)|(?:^${Df}$)`),Mf=new RegExp(`^${Of}$`),jf=new RegExp(`^${Df}$`),Lf=e=>e&&e.exact?xf:new RegExp(`(?:${Ef(e)}${Of}${Ef(e)})|(?:${Ef(e)}${Df}${Ef(e)})`,"g");Lf.v4=e=>e&&e.exact?Mf:new RegExp(`${Ef(e)}${Of}${Ef(e)}`,"g"),Lf.v6=e=>e&&e.exact?jf:new RegExp(`${Ef(e)}${Df}${Ef(e)}`,"g");const Af={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},Nf={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},Bf={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},Ff={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2_KEY"}]},zf={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2_KEY",maxBitrate:8e5}]},Vf={encodings:[{}]},Uf={encodings:[{maxBitrate:6e5,maxFramerate:2}]},$f={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},Gf={encodings:[{dtx:!0}]},qf=(e,t,r)=>{const{lowDataModeEnabled:n,simulcastScreenshareOn:i,vp9On:s,lowBandwidth:o}=r;return"audio"===e?Af:t?o&&!s?Uf:s?Gf:i?$f:Vf:o?s?zf:Bf:s?Ff:n?Bf:Nf},Hf=57600,Wf=2.6041666666666665,Kf=921600,Jf=1.0850694444444444;const Qf="fetch_mediaserver_config",Xf="start_screenshare",Yf="stop_screenshare",Zf="audio_enabled",em="client_left",tm="mediaserver_config",rm="new_client",nm="screenshare_started",im="screenshare_stopped",sm="room_joined",om="video_enabled",am="ice_candidate",cm="ice_endofcandidates",dm="ready_to_receive_offer",lm="sdp_answer",um="sdp_offer",pm="pending_client_left",hm="media_quality_changed",fm=new Qh;class mm extends Jl{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(sm,(e=>this._onRoomJoined(e))),e.on(rm,(e=>this._onNewClient(e))),e.on(em,(e=>this._onClientLeft(e))),e.on(pm,(e=>this._onPendingClientLeft(e))),e.on(Zf,(e=>this._onAudioEnabled(e))),e.on(om,(e=>this._onVideoEnabled(e))),e.on(nm,(e=>this._onScreenshareChanged(e,!0))),e.on(im,(e=>this._onScreenshareChanged(e,!1)))}_onRoomJoined(e){var t,r;return Xh(this,void 0,void 0,(function*(){if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),!(null===(t=e.room)||void 0===t?void 0:t.clients))return void this.emit(sm,e);if(!e.selfId)return void this.emit(sm,e);const n=null===(r=e.room.clients.find((t=>e.selfId===t.id)))||void 0===r?void 0:r.deviceId;if(!n)return void this.emit(sm,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter((e=>!(e.deviceId===n&&e.isPendingToLeave))),void this.emit(sm,e);const i=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>i)return this._resetClientState(e),this.emit(sm,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter((e=>!(e.deviceId===n&&e.isPendingToLeave)));const s=yield wf();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(s,t.id))return;t.mergeWithOldClientState=!0}catch(e){fm.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(sm,e)}))}_onClientLeft(e){var t;const{clientId:r}=e,n=this._clients[r];n&&(clearTimeout(n.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(em,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))):fm.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,n=this._clients[t];if(n&&n.isPendingToLeave)return clearTimeout(n.timeoutHandler),n.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach((e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(em,{clientId:e.clientId})})),this._addClientToState(e.client),this.emit(rm,e)}_abortIfNotActive(e){return Xh(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(em,e)))}))}_checkIsActive(e){return Xh(this,void 0,void 0,(function*(){const t=yield wf();return this._isClientMediaActive(t,e)}))}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let n=!1;return r&&Object.entries(r.tracks).forEach((([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach((e=>{(e.bitrate||0)>0&&(n=!0)}))})),n}_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:n}){const i=this._clients[e];if(!i)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==i.isVideoEnabled||(r!==i.isAudioEnabled||n!==i.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 gm;const vm=null!==(gm=hn.default)&&void 0!==gm?gm:hn;class bm{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=Sp(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"!==vm.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]})),r&&(this._reconnectManager=new mm(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=[sm,em,rm];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.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 ym=[{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 wm({host:e="whereby.com",protocol:t="https:"}={}){let r="",n=e,i=".";for(const{separator:t,pattern:s}of ym){const o=s.exec(e);if(o){r=o[1]||"",n=o[2],i=t;break}}const s=r?`${r}${i}${n}`:n;return{domain:n,domainWithSeparator:`${i}${n}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${n}`,subdomain:r}}wm(window&&window.location);const _m=new Qh,Sm={print:(...e)=>console.debug(e[0],...e.slice(1))};_m.withDebugLogger(Sm);const Cm=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 n=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let i=this.ssrcsHistory.get(e);if(!i)return i={id:e,hasActivePacketLoss:n,currPeriod:n?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,i);i.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(i,r),i.prevIntervalInMs&&i.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):n&&(i.hasActivePacketLoss=!0,i.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((()=>{_m.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)}),this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(_m.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(_m.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,_m.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}},Rm=[{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:n})=>{if(!n&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return!n}},{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:n})=>{if(0===n.length&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return 0===n.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let n=!1;if(r.forEach((e=>{n=n||((null==e?void 0:e.bitrate)||0)>0})),!n&&e.isLocalClient){const e=t.filter((e=>!e.isLocalClient));if(e.length>0)return!e.every((e=>e.isAudioOnlyModeEnabled))}return!n}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!n.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,kind:n})=>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:n})=>e&&r.isLocalClient&&"video"===n&&!!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:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.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:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.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:n})=>{if(!n.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 i=n[0];return!!i&&(0===i.bitrate||(i.lossRatio||0)>.03||(i.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==i?void 0:i.bitrate)&&i.bitrate<3e4||"in"===i.direction&&!!i.pliRate&&i.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)&&(Cm.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),Cm.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 Tm=[],km=null;const Pm=[{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:n})=>e&&"video"===n&&!!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:n,kind:i})=>e&&"video"===i&&!!r&&!!t&&!!n&&!!n.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:n})=>e&&"video"===n&&!!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:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+(t.qpf||0)),0)}];let Em,Om,Im;const Dm=()=>{Em={},Om={},Im={aggregated:{issues:Om,metrics:Em}}};function xm(e,t){Object.values(Em).forEach((e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0})),Object.values(Om).forEach((e=>{e.curTicks=0,e.curRegistered=0,e.active=!1})),t.find((e=>!e.isLocalClient))&&(t.forEach((r=>{const n=e[r.id];["video","audio","global"].forEach((e=>{var i,s;if(("global"!==e||r.isPresentation)&&!(null===(i=r[e])||void 0===i?void 0:i.enabled))return;if("global"===e&&!r.isLocalClient)return;let o=Im[r.id];o||(o={issues:{},metrics:{}},Im[r.id]=o);const a=null===(s=r[e])||void 0===s?void 0:s.track,c=!!a&&"ended"!==a.readyState,d=a&&n&&n.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:n,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}`;Pm.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 n=t.value(p);r||(r={ticks:0,sum:0,avg:0,min:n,max:n},o.metrics[e]=r),r.ticks++,r.sum+=n,r.min=Math.min(r.min,n),r.max=Math.max(r.max,n),r.avg=r.sum/r.ticks;let i=Em[e];i||(i={ticks:0,sum:0,min:n,max:n,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},Em[e]=i),i.ticks++,i.sum+=n,i.min=Math.min(i.min,n),i.max=Math.max(i.max,n),i.avg=i.sum/i.ticks,0===i.curTicks?(i.curMax=n,i.curMin=n,i.curSum=n):(i.curMax=Math.max(i.curMax,n),i.curMin=Math.min(i.curMin,n),i.curSum+=n),i.curTicks++}})),Rm.forEach((t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;const r=`${h}-${t.id}`,n=t.enabled(p);let i=o.issues[r],s=Om[r];if(n){i||(i={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},o.issues[r]=i),i.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},Om[r]=s),s.ticks++,s.curTicks++;t.check(p)?(i.registered++,i.current++,i.active||(i.active=!0,i.periods++),i.ticks===i.initial+1&&(i.initial++,s.initial++),i.current>i.longest&&(i.longest=i.current),s.active=!0,s.registered++,s.curRegistered++):(i.active=!1,i.current=0)}else i&&(i.active=!1,i.current=0)}))}))})),Object.values(Em).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(Om).forEach((e=>{e.curTicks})),Tm.forEach((r=>{var n;return null===(n=r.onUpdatedIssues)||void 0===n?void 0:n.call(r,Im,e,t)})))}function Mm(e){return Tm.push(e),km||(km=function(e,t=yf,r=bf){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=_f(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:xm}).stop),{stop(){Tm=Tm.filter((t=>t!==e)),Tm.length||(null==km||km(),km=null,Dm())}}}Dm();class jm{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?jm._handleRequest(t):t.response?jm._handleResponse(t):t.message?jm._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 Lm=new Qh;class Am extends Jl{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(){Lm.info("Connected"),this.emit("open")}_onMessage(e){const t=jm.parse(e.data);Lm.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){Lm.info("Disconnected"),this._tearDown()}_onError(e){Lm.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=jm.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const n=jm.createRequest(e,t);return this.send(n),new Promise(((e,t)=>{const i={id:n.id,method:n.method,resolve:t=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),e(t))},reject:e=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),t(e))},timer:setTimeout((()=>{this.sents.delete(n.id)&&t(new Error("request timeout"))}),r),close:()=>{clearTimeout(i.timer),t(new Error("transport closed"))}};this.sents.set(n.id,i)}))}}var Nm;const Bm=null!==(Nm=hn.default)&&void 0!==Nm?Nm:hn;const Fm=400;var zm;const Vm="safari"===(null!==(zm=hn.default)&&void 0!==zm?zm:hn).browserDetails.browser,Um=e=>e.split(/[^\d]/g).map((e=>parseInt(e,10)));function $m({devices:e,videoId:t,audioId:r,options:n,type:i="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=function({disableAEC:e,disableAGC:t,hd:r,lax:n,lowDataMode:i,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=n||Vm?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:i?p:u,frameRate:i&&!a?15:24})};if(n)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]=Um(o);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}(Object.assign({preferredDeviceIds:{audioId:a?null:{[i]:r},videoId:c?null:{[i]:t}}},n));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const Gm=new Qh,qm=/mobi/i.test(navigator.userAgent);class Hm extends Error{constructor(...e){super(...e),this.name="nodevices"}}function Wm(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch((t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw Gm.error(`getUserMedia ${r}`),t})):Promise.reject(new Hm("No provided devices"))}function Km(e,t,r,n){var i,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))):(n&&r&&(a.deviceId=null===(i=r.find((t=>t.deviceId===n&&t.kind===e)))||void 0===i?void 0:i.deviceId),a)}function Jm(e,t){t&&"audio"!==t||e.getAudioTracks().forEach((e=>e.stop())),t&&"video"!==t||e.getVideoTracks().forEach((e=>e.stop()))}function Qm(e,{replaceStream:t,fallback:r=!0}={}){var n;return Xh(this,void 0,void 0,(function*(){let i,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=qm||"video"!==c,l=$m(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!==i&&{error:String(i)}),e);d&&t&&Jm(t,c);try{a=yield Wm(l)}catch(s){if(i=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){if(l.audio&&l.video){try{a=yield Wm($m(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){if("NotFoundError"!==e.name)throw u(e,s)}try{a||(a=yield Wm($m(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){throw u(e,s)}}}else if("NotAllowedError"===s.name||"NotReadableError"===s.name||"AbortError"===s.name)if(t&&!d)Jm(t,c),o=e;else if("NotAllowedError"!==s.name){try{a=yield Wm($m(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){Gm.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(n=/(video|audio)/.exec(t))||void 0===n?void 0:n[0])||c||""];if(!a&&r)try{a=yield Wm($m(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){Gm.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 Wm($m(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){Gm.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=$m(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield Wm(s)}catch(e){throw u(e,i)}}if(!a)throw u(i);let p;return t&&(d||Jm(t,c),p=function(e,t,r){const n=[];return r&&"audio"!==r||(n.push(...e.getAudioTracks()),t.getAudioTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),r&&"video"!==r||(n.push(...e.getVideoTracks()),t.getVideoTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),n.forEach((t=>{t.replaced=!0,e.removeTrack(t)})),n}(t,a,c),a=t),{error:i&&u(i),stream:a,replacedTracks:p}}))}function Xm({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:n,currentSpeakerId:i}){const s=function(e,t){const[r,n]=[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})})),{}))),i={};return e.forEach((e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[e.kind]={added:{},removed:{},changed:{}}),n[e.kind]&&n[e.kind][e.deviceId]||(i[e.kind].removed[e.deviceId]=e))})),t.forEach((e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[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&&(i[e.kind].changed[e.deviceId]=e):i[e.kind].added[e.deviceId]=e)})),i}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",n],["audiooutput",i]].forEach((([e,r])=>{const n=s[e];if(n){if(r){if(n.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}}n.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(n.added).length>0){const[t]=Object.keys(n.added).slice(0,1),r=n.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(n.removed).length>0){const[t]=Object.keys(n.removed).slice(0,1);o[e]=n.removed[t]}}})),{addedDevices:c,changedDevices:a,removedDevices:o}}var Ym;const Zm=null!==(Ym=hn.default)&&void 0!==Ym?Ym:hn,eg=new Qh,tg=Zm.browserDetails.browser,rg=Zm.browserDetails.version;function ng(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),n=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+)/),n=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(n[e],"g"),r[e]);return t}function ig(e){return"firefox"!==tg?e:tn.splitLines(e.trim()).map((e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e)).join("\r\n")+"\r\n"}function sg(e){return function(e,t,r=!1,n=!1){var i,s;try{const o=Ap(e);if((null===(i=null==o?void 0:o.ext)||void 0===i?void 0:i.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 i;(r&&"audio"===e.type||n&&"video"===e.type)&&((null===(i=e.ext)||void 0===i?void 0:i.find((e=>e.uri===t)))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))})),Lp(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 og(e,t,r=console){const n=e.getSenders().find((e=>e.track&&"video"===e.track.kind));if(!n)return Promise.resolve();const i=n.getParameters();return i.encodings&&0===i.encodings.length?Promise.resolve():(i.encodings||(i.encodings=[{}]),0===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,n.setParameters(i).catch((e=>{r.error("setParameters err: ",e)})))}var ag;const cg=null!==(ag=hn.default)&&void 0!==ag?ag:hn,dg=new Qh;class lg{constructor({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:r,deprioritizeH264Encoding:n}){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=n}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:n}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=n,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 tn.splitSections(e).map((e=>{if("video"!==tn.getKind(e))return e;const t=tn.matchPrefix(e,"a=rtpmap:").map((e=>tn.parseRtpMap(e))).filter((e=>/h264/i.test(e.name))).map((e=>""+e.payloadType));if(!t.length)return e;const r=tn.matchPrefix(e,"m=video")[0],n=/(\s\d+)+$/i.exec(r),i=n?n[0]:"",s=[...i.split(" ").filter((e=>e&&!t.includes(e))),...t].join(" "),o=r.replace(i," "+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"!==tg&&("firefox"!==tg||rg&&rg>=63||60===rg)?e:tn.splitLines(e.trim()).filter((e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==tn.parseExtmap(e).uri)).join("\r\n")+"\r\n"}(t),t=ig(t);const r={type:e.type,sdp:t};let n;return this._setRemoteDescription(r).then((()=>this.pc.createAnswer())).then((e=>(n=e,this.pc.setLocalDescription(e)))).then((()=>og(this.pc,this.bandwidth))).then((()=>n))}handleAnswer(e){const t=ig(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then((()=>og(this.pc,this.bandwidth)),(e=>{dg.warn("Could not set remote description from remote answer: ",e)}))}addIceCandidate(e){this.srdComplete?this.srdComplete.then((()=>{"closed"!==this.pc.signalingState&&("safari"===cg.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch((t=>{dg.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){dg.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 n=r.getSenders();if(e||(e=(n.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<n.length;r++){const i=n[r].track;if((null==i?void 0:i.id)===t.id)return Promise.resolve(t);if((null==i?void 0:i.id)===e.id)return n[r].replaceTrack(t)}return null};let i=r();if(i)return i;let s=null,o=null;i=new Promise(((e,t)=>{s=e,o=t}));let a=0,c=setInterval((()=>Xh(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 i}const i=this.streams.find((e=>e.getTracks().find((e=>e.id===t.id))))||this.streams[0];return i?r.addTrack(t,i):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push((()=>{this.replaceTrack(e,t)}));this.isOperationPending=!0;const i=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout((()=>{r.onnegotiationneeded=i}),0),"offer"===r.localDescription.type?r.createOffer().then((e=>(e.sdp=ng(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))).then((()=>this._setRemoteDescription(r.remoteDescription))):this._setRemoteDescription(r.remoteDescription).then((()=>r.createAnswer())).then((e=>(e.sdp=ng(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((n=>{if("transport"===n.type&&n.selectedCandidatePairId){const i=e.get(n.selectedCandidatePairId);if(!i)return;return t=e.get(i.localCandidateId).candidateType,void(r=e.get(i.remoteCandidateId).candidateType)}"candidate-pair"===n.type&&n.selected&&(t=e.get(n.localCandidateId).candidateType,r=e.get(n.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&&og(this.pc,this.bandwidth)):this.pending.push((()=>this.changeBandwidth(e))))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter((e=>{var r,n,i,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(n=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===n?void 0:n.kind)&&!t.includes(null===(s=null===(i=null==e?void 0:e.receiver)||void 0===i?void 0:i.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 ug="client_connection_status_changed",pg="stream_added",hg="rtc_manager_created",fg="rtc_manager_destroyed",mg="local_stream_track_added",gg="local_stream_track_removed",vg="connecting",bg="connection_failed",yg="connection_successful",wg="connection_disconnected",_g="camera",Sg="screen_share";var Cg,Rg,Tg="connection_blocked_by_network",kg="ice_ipv6_seen",Pg="ice_mdns_seen",Eg="ice_no_public_ip_gathered",Og="ice_no_public_ip_gathered_3sec",Ig="ice_restart",Dg="microphone_not_working",xg="microphone_stopped_working",Mg="camera_stopped_working",jg="new_pc",Lg="sfu_connection_open",Ag="sfu_connection_closed",Ng="dominant_speaker",Bg="pc_sld_failure",Fg="pc_on_answer_failure",zg="pc_on_offer_failure";const Vg=null!==(Cg=hn.default)&&void 0!==Cg?Cg:hn,Ug=new Qh,$g=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=vg,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?_g:Sg}}.getCameraId(),Gg=Vg.browserDetails.browser,qg=Vg.browserDetails.version;"firefox"===Gg&&Vg.browserShim&&"shimGetDisplayMedia"in Vg.browserShim&&(null===(Rg=Vg.browserShim)||void 0===Rg||Rg.shimGetDisplayMedia(window,"screen"));let Hg=!1;"chrome"===Gg&&window.document.addEventListener("beforeunload",(()=>{Hg=!0}));class Wg{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s}){const{name:o,session:a,iceServers:c,sfuServer:d,mediaserverConfigTtlSeconds:l}=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=n,this._webrtcProvider=i,this._features=s||{},this._isAudioOnlyMode=!1,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{nf.sendEvent("audio_ended",{unloading:Hg}),this._emit(xg,{})},this._videoTrackOnEnded=()=>{nf.sendEvent("video_ended",{unloading:Hg}),this._emit(Mg,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:d,iceServers:c.iceServers||[],mediaserverConfigTtlSeconds:l}),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,n,i=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===$g){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=i.find((e=>"audio"===e.kind));t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=i.find((e=>"video"===e.kind));e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const n=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",n),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",n)})}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"!==Gg)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then((e=>{const n=e.getAudioTracks()[0];return n.enabled=r.enabled,t.removeTrack(r),t.addTrack(n),this.replaceTrack(r,n)})):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(tm,(e=>{e.error?Ug.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(dm,(e=>{this._connect(e.clientId)})),this._serverSocket.on(am,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):Ug.warn("No RTCPeerConnection on ICE_CANDIDATE",e)})),this._serverSocket.on(cm,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):Ug.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)})),this._serverSocket.on(um,(e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Ug.warn("No RTCPeerConnection on SDP_OFFER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=(t=n.handleOffer(i).then((t=>{this._emitServerEvent(lm,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})}))).catch)||void 0===r||r.call(t,(e=>{this._emit(zg,e)}))})),this._serverSocket.on(lm,(e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Ug.warn("No RTCPeerConnection on SDP_ANSWER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=null===(t=n.handleAnswer(i))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,(e=>{this._emit(Fg,e)}))})),this._serverSocket.on(sm,(({room:{sfuServer:e}})=>{if(e||!this._wasScreenSharing)return;const t=Object.keys(this.localStreams).find((e=>e!==$g));if(!t)return;const r=this.localStreams[t];if(!r)return void Ug.warn("screenshare stream %s not found",t);const n=r.getAudioTracks().length>0;this._emitServerEvent(Xf,{streamId:t,hasAudioTrack:n})}))]}sendAudioMutedStats(e){nf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nf.sendEvent(e,t)}rtcStatsDisconnect(){nf.server.close()}rtcStatsReconnect(){nf.server.connected||nf.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 n=e.connectionStatus;n!==t&&e.peerConnectionId!==this._selfId&&(n===wg&&t===vg||(e.connectionStatus=t,setTimeout((()=>{this._emit(ug,{streamIds:e.streamIds,clientId:r,status:t,previous:n})}),0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach((e=>{e.jitterBufferTarget=Fm,e.playoutDelayHint=.4}))}catch(e){Ug.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 n="safari"===Gg&&qg&&qg>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new lg({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:this._features.unlimitedBandwidthWhenUsingRelayP2POn?-1:1280,deprioritizeH264Encoding:n}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[$g]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter((e=>e!==$g))}_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:n,shouldAddLocalVideo:i}){if(!n)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(n,t),o={optional:[]};"chrome"===Gg&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:n}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._iceServers};if(this._features.turnServerOverrideHost){const e=this._features.turnServerOverrideHost,t=e.indexOf(":")>0?"":":443",r=":"+e+t;a.iceServers=a.iceServers.map((e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,r)),t.urls&&(t.urls=t.urls.map((e=>e.replace(/:[^?]*/,r)))),t}))}if(this._features.addGoogleStunServers&&(a.iceServers=[...a.iceServers,{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"}]),this._features.addCloudflareStunServers&&(a.iceServers=[...a.iceServers,{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"}]),this._features.useOnlyTURN){a.iceTransportPolicy="relay";const e={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[this._features.useOnlyTURN];e&&(a.iceServers=a.iceServers.filter((t=>t.url&&t.url.match(e))))}"chrome"===Gg&&(a.sdpSemantics="unified-plan");const c=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:i,clientId:e});setTimeout((()=>this._emit(jg)),0),c.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(pg,{clientId:e,stream:r}),s.connectionStatus===yg&&setTimeout((()=>{this._emit(ug,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:vg})}),0))},c.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(c.iceConnectionState){case"checking":t=vg;break;case"connected":case"completed":t=yg,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach((e=>{"function"==typeof e&&e()})),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(c.iceConnectionState.match(/connected|completed/)||"chrome"===Gg&&c.localDescription&&"answer"===c.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=wg,setTimeout((()=>{"disconnected"===c.iceConnectionState&&this._maybeRestartIce(e,s)}),2e3);break;case"failed":t=bg,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Tg);break;default:return}this._setConnectionStatus(s,t,e)},c.onconnectionstate=()=>{switch(c.connectionState){case"connected":setTimeout((()=>{(function(e){if("chrome"!==Bm.browserDetails.browser||Bm.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 n=!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&&(n="inbound"):0===e.bytesSent&&(n="outbound")})),n}))})(s.pc).then((t=>{!1!==t&&this._emit(Dg,{failureDirection:t,clientId:e})}))}),3e3),s.registerConnected();break;case"failed":const t=bg;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Tg),this._setConnectionStatus(s,t,e)}};const d=this.localStreams[$g];return i&&d&&s.addStream(d),i&&Object.keys(this.localStreams).forEach((e=>{if(e===$g)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then((()=>{this._emitServerEvent(Xf,{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]):Ug.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((n=>{if(!n.hasConnectedPeerConnection()){Ug.info("Session doesn't have a connected PeerConnection, adding pending action!");const i=this._pendingActionsForConnectedPeerConnections;if(!i)return void Ug.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise(((r,s)=>{i.push((()=>{const i=n.replaceTrack(e,t);if(!i)return Ug.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");i.then((e=>r(e))).catch((e=>s(e)))}))}));return void r.push(s)}const i=n.replaceTrack(e,t);i?r.push(i):Ug.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,sfuServer:t,mediaserverConfigTtlSeconds:r}){this._iceServers=e,this._sfuServer=t,this._mediaserverConfigTtlSeconds=r,this._clearMediaServersRefresh(),r&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitServerEvent(Qf)),1e3*r))}_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?(Ug.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(Ig),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e,t,r,n){try{const i=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)}));i.forEach((e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(n&&"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 s=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)}));s.forEach((e=>{if(void 0===RTCRtpSender.getCapabilities)return;const n=RTCRtpSender.getCapabilities("video");for(let e=0;e<n.codecs.length;e++){if(t&&"video/vp9"===n.codecs[e].mimeType.toLowerCase()){n.codecs.unshift(n.codecs.splice(e,1)[0]);break}if(r&&"video/av1"===n.codecs[e].mimeType.toLowerCase()){n.codecs.unshift(n.codecs.splice(e,1)[0]);break}}void 0!==e.setCodecPreferences&&e.setCodecPreferences(n.codecs)}))}catch(e){Ug.error("Error during setting setCodecPreferences:",e)}}_negotiatePeerConnection(e,t,r){if(!t)return void Ug.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const n=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push((()=>{this._negotiatePeerConnection(e,t,r)}));t.isOperationPending=!0;const{vp9On:i,av1On:s,redOn:o,rtpAbsCaptureTimeOn:a,cleanSdpOn:c}=this._features;(i||s||o)&&this._setCodecPreferences(n,i,s,o),n.createOffer(r||this.offerOptions).then((t=>{a&&(t.sdp=sg(t.sdp)),(i||o)&&"firefox"===Gg&&(t.sdp=function(e,t,r){var n,i;try{const s=Ap(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 i=0;i<t.length;i++)if(r&&"red"===t[i].codec){const r=null===(n=e.payloads)||void 0===n?void 0:n.split(" "),s=null==r?void 0:r.indexOf(""+t[i].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===(i=o.payloads)||void 0===i?void 0:i.split(" "),n=null==t?void 0:t.indexOf(""+e[r].payload);n&&-1!==n&&n>=0&&(null==t||t.unshift(t.splice(n,1)[0]),o.payloads=null==t?void 0:t.join(" "))}}}return Lp(s)}catch(e){eg.error("setCodecPreferenceSDP error:",e)}}(t.sdp,i,o)),c&&(t.sdp=function(e){try{const t=Ap(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 n={};e.fmtp&&(e.fmtp=e.fmtp.filter((e=>!e.payload||t[e.payload]&&!n[e.payload]&&(n[e.payload]=!0))));const i={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter((e=>!e.payload||t[e.payload]&&!i[e.payload+e.type]&&(i[e.payload+e.type]=!0))))})),Lp(t)}catch(e){}return e}(t.sdp)),n.setLocalDescription(t).catch((e=>{throw Ug.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(Bg,e),e})).then((()=>{this._emitServerEvent(um,{receiverId:e,message:this._transformOutgoingSdp(t)})}))})).catch((e=>{Ug.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,n=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout((()=>r.onnegotiationneeded=n),0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);let r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:this._features.lowBandwidth?768:0,2:this._features.highP2PBandwidth&&!this._features.lowBandwidth?768:384,3:this._features.highP2PBandwidth&&!this._features.lowBandwidth?512:256,4:192,5:128,6:128,7:64}[t];if(void 0===r)return 0;if(this._features.adjustBitratesFromResolution){const e=this._getLocalCameraStream();if(e){const t=e&&e.getVideoTracks()[0];if(t){const{width:e,height:n,frameRate:i}=t.getSettings();if(e&&n&&i){const t=Math.round(function(e,t,r){let n=e*t;n<Hf&&(n=Hf),n>Kf&&(n=Kf);let i=Wf;n>Kf?i=Jf:n>Hf&&(i+=-17582143775720163e-22*(n-Hf));let s=e*t*i;return r<=15?s*=.7:r<=24&&(s*=.9),s}(e,n,i)/1e3);r=Math.min(t,r||t)}}}}return this._features.higherP2PBitrates&&!this._features.lowBandwidth&&(r*=1.5),this._forEachPeerConnection((e=>{e.changeBandwidth(r)})),r}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:n=!1}){const i=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:n}),s=i.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[$g];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((()=>{i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(Og)}),3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,n;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(n=null==t?void 0:t.candidate)||void 0===n?void 0:n.address;try{if(Lf.v4({exact:!0}).test(e)){Uh(e).isPublicIp&&(i.publicHostCandidateSeen=!0)}else if(Lf.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new Np.Address6(e.replace(/^\[(.*)\]/,"$1"));i.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(i.publicHostCandidateSeen=!0),t.isTeredo()&&(i.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(i.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&Kh(t,4)&&(i.mdnsHostCandidateSeen=!0)}}catch(e){Ug.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":i.serverReflexiveCandidateSeen||(i.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":i.relayCandidateSeen||(i.relayCandidateSeen=!0)}this._emitServerEvent(am,{receiverId:e,message:t.candidate})}else this._emitServerEvent(cm,{receiverId:e}),i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(Eg),i.ipv6HostCandidateSeen&&this._emit(kg,{teredoSeen:i.ipv6HostCandidateTeredoSeen,sixtofourSeen:i.ipv6HostCandidate6to4Seen}),i.mdnsHostCandidateSeen&&this._emit(Pg)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&i.connectionStatus&&this._negotiatePeerConnection(e,i)},i}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let n=this._getSession(t);if(n&&e!==t)return n;let i=n&&n.bandwidth||0;return n?(Ug.warn("Replacing peer session",t),this._cleanup(t)):i=this._changeBandwidthForAllClients(!0),n=this._createP2pSession({clientId:t,initialBandwidth:i,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(dm,{receiverId:t}),n}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(Gg))if(!1===t){const n="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(gg,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),n)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emit(mg,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})}))}}_shareScreen(e,t){this._emitServerEvent(Xf,{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(Yf,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}var Kg=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:n=1,C:i=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=i,this.B=n,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),n=this.uncertainty(),i=n*this.C*(1/(this.C*n*this.C+this.Q));this.x=r+i*(e-this.C*r),this.cov=n-i*this.C*n}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 n=>{const i=n.reduce(((e,t)=>e+t),0)/n.length;if(e=e<0?i:.95*e+.05*i,++r<2)return t=i,0;const s=(i-e)*(t-e);return t=i,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 Jg={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"},Qg=new Qh;const Xg=new Qh,Yg=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class Zg extends Jl{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:Yg.ok,trend:[]},video:{currentQuality:Yg.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 n=t.reduce(((e,t)=>e+t.score),0)/t.length,i=this._evaluateScore(n);this._updateTrend(i,this._clients[e][r])&&this.emit(hm,{clientId:e,kind:r,quality:i})}_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]={}):Xg.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]={}):Xg.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,n){Array.isArray(n)&&0!==n.length&&!n.some((e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score)))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.map((e=>e.score)))}:Xg.warn("Unexpected producer score format")}addConsumerScore(e,t,r,n){n&&n.hasOwnProperty("producerScores")&&Array.isArray(n.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.producerScores)}:Xg.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?Yg.warning:e<=7&&e>0?Yg.critical:Yg.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 Xg.error(e),0}}}var ev;const tv=null!==(ev=hn.default)&&void 0!==ev?ev:hn,rv=new Qh,nv=tv.browserDetails.browser;let iv=!1;const sv=Sn(),ov=Sn();"chrome"===nv&&window.document.addEventListener("beforeunload",(()=>iv=!0));class av{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s,eventClaim:o,deviceHandlerFactory:a}){const{session:c,iceServers:d,sfuServer:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._room=t,this._roomSessionId=null==c?void 0:c.id,this._emitter=r,this._serverSocket=n,this._webrtcProvider=i,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDevice=a?new Tn.Device({handlerFactory:a}):new Tn.Device({handlerName:kf()}),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=()=>{nf.sendEvent("audio_ended",{unloading:iv}),this._emitToPWA(xg,{})},this._videoTrackOnEnded=()=>{nf.sendEvent("video_ended",{unloading:iv}),this._emitToPWA(Mg,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,iceServers:d.iceServers||[],mediaserverConfigTtlSeconds:u}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._hasVegaConnection=!1,this._qualityMonitor=new Zg,this._qualityMonitor.on(hm,(e=>{this._emitToPWA(hm,e)}))}_updateAndScheduleMediaServersRefresh({iceServers:e,sfuServer:t,mediaserverConfigTtlSeconds:r}){var n,i;this._iceServers=e,this._sfuServer=t,this._mediaserverConfigTtlSeconds=r,null===(n=this._sendTransport)||void 0===n||n.updateIceServers({iceServers:this._iceServers}),null===(i=this._receiveTransport)||void 0===i||i.updateIceServers({iceServers:this._iceServers}),this._clearMediaServersRefresh(),r&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitToSignal(Qf)),1e3*r))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}setupSocketListeners(){this._socketListenerDeregisterFunctions.push((()=>this._clearMediaServersRefresh()),this._serverSocket.on(tm,(e=>{e.error?rv.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(sm,(()=>{this._screenVideoTrack&&this._emitScreenshareStarted(),this._features.sfuReconnectV2On&&!this._hasVegaConnection&&this._reconnect&&this._connect()}))),this._connect()}_emitScreenshareStarted(){this._emitToSignal(Xf,{streamId:ov,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(this._features.sfuReconnectV2On){if(this._hasVegaConnection)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)}const e=this._features.sfuServerOverrideHost||[this._sfuServer.url],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]})),{}))),r=`wss://${e}?${t.toString()}`;this._vegaConnection=new Am(r),this._hasVegaConnection=!0,this._vegaConnection.on("open",(()=>this._join())),this._vegaConnection.on("close",(()=>this._onClose())),this._vegaConnection.on("message",(e=>this._onMessage(e)))}_onClose(){var e,t;rv.info("_onClose()"),this._hasVegaConnection=!1,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(Ag)}_join(){return Xh(this,void 0,void 0,(function*(){rv.info("join()"),this._emitToPWA(Lg);try{const{routerRtpCapabilities:e}=yield this._vegaConnection.request("getCapabilities");this._routerRtpCapabilities||(((e,t)=>{const{vp9On:r,h264On:n}=t;if(r){const{preferredPayloadType:t}=e.codecs.find((e=>"video/vp9"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}else if(n){const{preferredPayloadType:t}=e.codecs.find((e=>"video/h264"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}})(e,this._features),this._routerRtpCapabilities=e,yield this._mediasoupDevice.load({routerRtpCapabilities:e})),this._vegaConnection.message("setCapabilities",{rtpCapabilities:this._mediasoupDevice.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const t=[];!this._micTrack||this._micProducer||this._micProducerPromise||t.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||t.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||t.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||t.push(this._internalSendScreenAudio()),yield Promise.all(t)}catch(e){rv.error("_join() [error:%o]",e)}}))}_createTransport(e){return Xh(this,void 0,void 0,(function*(){const t=e?"createSendTransport":"createRecvTransport",r=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}});r.iceServers=this._iceServers,((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))))})(r,this._features);const n=this._mediasoupDevice[t](r),i=t=>Xh(this,void 0,void 0,(function*(){if(rv.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}))}}));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",i),n.observer.once("close",(()=>{n.removeListener(i)})),e?(n.on("produce",(({kind:e,rtpParameters:t,appData:r},i,s)=>Xh(this,void 0,void 0,(function*(){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)}})))),n.on("producedata",(({appData:e,sctpStreamParameters:t},r,i)=>Xh(this,void 0,void 0,(function*(){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,t=0){return Xh(this,void 0,void 0,(function*(){if(!e||!("closed"in e)||!("connectionState"in e))return void rv.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void rv.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void rv.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,n=Date.now();if(Number.isFinite(r)&&n-r<3500)return;if(e.appData.iceRestartStarted=n,5<=t)return void rv.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void rv.info("_restartIce: Connection is undefined");const{iceParameters:i}=yield this._vegaConnection.request("restartIce",{transportId:e.id});rv.info("_restartIce: ICE restart iceParameters received from SFU: ",i);const s=yield e.restartIce({iceParameters:i}).then((()=>null)).catch((e=>e));if(s)switch(rv.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 Xh(this,void 0,void 0,(function*(){rv.info("_internalSendMic()"),this._micProducerPromise=(()=>Xh(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},qf("audio",!1,this._features)),{appData:{streamId:sv,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;rv.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){rv.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}})))()}))}_internalSetupMicScore(){return Xh(this,void 0,void 0,(function*(){rv.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>Xh(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;rv.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){rv.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}})))()}))}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){var e;return Xh(this,void 0,void 0,(function*(){rv.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;rv.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 Xh(this,void 0,void 0,(function*(){return rv.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){rv.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_internalSendWebcam(){var e;return Xh(this,void 0,void 0,(function*(){rv.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>Xh(this,void 0,void 0,(function*(){var e,t;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},qf("video",!1,this._features)),{appData:{streamId:sv,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;rv.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){rv.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null),this._features.lowBandwidth&&this._screenVideoTrack&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(0))}})))())}))}_replaceWebcamTrack(){return Xh(this,void 0,void 0,(function*(){rv.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;rv.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 Xh(this,void 0,void 0,(function*(){return rv.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 Xh(this,void 0,void 0,(function*(){rv.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>Xh(this,void 0,void 0,(function*(){var e,t;try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1},qf("video",!0,this._features)),{appData:{streamId:ov,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",(()=>{var e;rv.info('screenVideoProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)})),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack()),this._features.lowBandwidth&&(null===(e=this._webcamProducer)||void 0===e||e.setMaxSpatialLayer(0))}catch(e){rv.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._features.lowBandwidth&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(Number.MAX_VALUE)))}})))()}))}_replaceScreenVideoTrack(){return Xh(this,void 0,void 0,(function*(){rv.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 Xh(this,void 0,void 0,(function*(){return rv.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 Xh(this,void 0,void 0,(function*(){rv.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>Xh(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},qf("audio",!0,this._features)),{appData:{streamId:ov,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;rv.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){rv.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}})))()}))}_replaceScreenAudioTrack(){return Xh(this,void 0,void 0,(function*(){rv.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 Xh(this,void 0,void 0,(function*(){return rv.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){rv.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}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(),nf.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 n;if(rv.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r),this._clientStates.has(e)){const t=this._clientStates.get(e);t.hasAcceptedWebcamStream=!1,t.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)}r&&(this._eventClaim=r,null===(n=this._vegaConnection)||void 0===n||n.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){var n;rv.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(Yf,{streamId:ov,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null,this._features.lowBandwidth&&(null===(n=this._webcamProducer)||void 0===n||n.setMaxSpatialLayer(Number.MAX_VALUE))}_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,n,i=[]){if("0"===e){this._micPaused=r,this._webcamPaused=n;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=i.find((e=>"video"===e.kind));t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=i.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 n=new AudioContext;let i=null,s=null,o=null,a=!1;const c=e=>Xh(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){Qg.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=n.createMediaStreamSource(t),s.connect(i)}}));let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},Jg),e),!i||i.fftSize!==2*t.bins){let e=null;i&&(e=o,c(null)),i=n.createAnalyser(),i.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(i.frequencyBinCount),a=[];i.minDecibels=t.minDecibels,i.maxDecibels=t.maxDecibels,i.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(Kg,c,o);d=setInterval((()=>{i.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,Kg),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),n=a.reduce(((e,t)=>e+t),0)/a.length,i=h(e,n,t,a);r({bins:s,score:e,max:t,avg:n,out:i})}}),1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),n.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){rv.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(rv.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(nv))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emitToPWA(mg,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})}))}}else{clearTimeout(this._stopCameraTimeout);const n="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(gg,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),n)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){rv.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:n}){var i,s;rv.info("updateStreamResolution()",{streamId:e,width:r,height:n});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:n});const c=function(e){let t=0;return e.forEach((e=>{var r,n;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(n=e._appData)||void 0===n?void 0:n.source)||t++})),t}(this._consumers),d=function(e){var t,r,n;return/T3/.test((null===(n=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===n?void 0:n.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:n,uncappedSingleRemoteVideoOn:i}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=n-1;return s<100&&(a=Math.max(n-2,0)),r>8&&0===o&&(a=Math.max(n-2,0)),r<4&&s>300&&0===o&&(o=1),i&&1===r&&(o=2,a=n-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:n},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(i=this._features)||void 0===i?void 0:i.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,n;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===(n=this._receiveTransport)||void 0===n||n.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDevice=null}sendAudioMutedStats(e){nf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nf.sendEvent(e,t)}rtcStatsDisconnect(){nf.server.close()}rtcStatsReconnect(){nf.server.connected||nf.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 Xh(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 rv.info(`unknown message method "${t}"`)}})).catch((e=>{rv.error('"message" failed [error:%o]',e)}))}))}_onConsumerReady(e){return Xh(this,void 0,void 0,(function*(){rv.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=Fm,t.rtpReceiver.playoutDelayHint=.4}catch(e){rv.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:n,streamId:i}=t.appData,s=this._getOrCreateClientState(r);n?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=i):(s.hasEmittedWebcamStream=!1,s.camStreamId=i);let o=n?s.screenStream:s.webcamStream;o&&o.inboundId===i||(o=new MediaStream,o.inboundId=i,n?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({consumerId:e,reason:t}){var r;return Xh(this,void 0,void 0,(function*(){rv.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()}))}_onConsumerPaused({consumerId:e}){rv.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){rv.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}){rv.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:n}}=this._consumers.get(e)||{appData:{}};n&&this._qualityMonitor.addConsumerScore(n,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){rv.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach((n=>{(null==n?void 0:n.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)}))}_onDataConsumerReady(e){return Xh(this,void 0,void 0,(function*(){rv.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:n}=JSON.parse(e);n&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,n))})),this._syncIncomingStreamsWithPWA(r)}))}_onDataConsumerClosed({dataConsumerId:e,reason:t}){return Xh(this,void 0,void 0,(function*(){rv.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(Ng,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,n=this._getOrCreateClientState(t),i=r?n.screenStream:n.webcamStream;i&&(i.removeTrack(e.track),0===i.getTracks().length&&(this._streamIdToVideoConsumerId.delete(i.id),this._streamIdToVideoResolution.delete(i.id),r?(n.screenStream=null,n.hasEmittedScreenStream=!1,n.screenShareStreamId=null):(n.hasEmittedWebcamStream=!1,n.camStreamId=null)))}_syncIncomingStreamsWithPWA(e){var t,r;const n=this._getOrCreateClientState(e),{webcamStream:i,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=n,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})),i&&!o&&c&&(this._emitToPWA(pg,{clientId:e,stream:i,streamId:u,streamType:"webcam"}),n.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(pg,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),n.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1,webcamStream:null,screenStream:null,screenShareStreamId:null,camStreamId:null},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 cv{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:n}){this.emitter=e,this.currentManager=null,t.on(sm,(({room:i,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:i,emitter:e,serverSocket:t,webrtcProvider:r,features:n,eventClaim:a,deviceHandlerFactory:null==n?void 0:n.deviceHandlerFactory},d=!!i.sfuServer;if(this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:i.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(fg)}let l=null;l=d?new av(c):new Wg(c),l.rtcStatsReconnect(),l.setupSocketListeners(),e.emit(hg,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)}))}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(fg))}}var dv;!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(dv||(dv={}));var lv={exports:{}};lv.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var uv=c(lv.exports);function pv(e,t){return function(){return e.apply(t,arguments)}}const{toString:hv}=Object.prototype,{getPrototypeOf:fv}=Object,mv=(e=>t=>{const r=hv.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),gv=e=>(e=e.toLowerCase(),t=>mv(t)===e),vv=e=>t=>typeof t===e,{isArray:bv}=Array,yv=vv("undefined");const wv=gv("ArrayBuffer");const _v=vv("string"),Sv=vv("function"),Cv=vv("number"),Rv=e=>null!==e&&"object"==typeof e,Tv=e=>{if("object"!==mv(e))return!1;const t=fv(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},kv=gv("Date"),Pv=gv("File"),Ev=gv("Blob"),Ov=gv("FileList"),Iv=gv("URLSearchParams");function Dv(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),bv(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function xv(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const Mv="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,jv=e=>!yv(e)&&e!==Mv;const Lv=(Av="undefined"!=typeof Uint8Array&&fv(Uint8Array),e=>Av&&e instanceof Av);var Av;const Nv=gv("HTMLFormElement"),Bv=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Fv=gv("RegExp"),zv=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};Dv(r,((r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)})),Object.defineProperties(e,n)},Vv="abcdefghijklmnopqrstuvwxyz",Uv="0123456789",$v={DIGIT:Uv,ALPHA:Vv,ALPHA_DIGIT:Vv+Vv.toUpperCase()+Uv};const Gv=gv("AsyncFunction");var qv={isArray:bv,isArrayBuffer:wv,isBuffer:function(e){return null!==e&&!yv(e)&&null!==e.constructor&&!yv(e.constructor)&&Sv(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Sv(e.append)&&("formdata"===(t=mv(e))||"object"===t&&Sv(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&wv(e.buffer),t},isString:_v,isNumber:Cv,isBoolean:e=>!0===e||!1===e,isObject:Rv,isPlainObject:Tv,isUndefined:yv,isDate:kv,isFile:Pv,isBlob:Ev,isRegExp:Fv,isFunction:Sv,isStream:e=>Rv(e)&&Sv(e.pipe),isURLSearchParams:Iv,isTypedArray:Lv,isFileList:Ov,forEach:Dv,merge:function e(){const{caseless:t}=jv(this)&&this||{},r={},n=(n,i)=>{const s=t&&xv(r,i)||i;Tv(r[s])&&Tv(n)?r[s]=e(r[s],n):Tv(n)?r[s]=e({},n):bv(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&Dv(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(Dv(t,((t,n)=>{r&&Sv(t)?e[n]=pv(t,r):e[n]=t}),{allOwnKeys:n}),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,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&fv(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:mv,kindOfTest:gv,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(bv(e))return e;let t=e.length;if(!Cv(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:Nv,hasOwnProperty:Bv,hasOwnProp:Bv,reduceDescriptors:zv,freezeMethods:e=>{zv(e,((t,r)=>{if(Sv(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Sv(n)&&(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={},n=e=>{e.forEach((e=>{r[e]=!0}))};return bv(e)?n(e):n(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)=>(e=+e,Number.isFinite(e)?e:t),findKey:xv,global:Mv,isContextDefined:jv,ALPHABET:$v,generateString:(e=16,t=$v.ALPHA_DIGIT)=>{let r="";const{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r},isSpecCompliantForm:function(e){return!!(e&&Sv(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(Rv(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const i=bv(e)?[]:{};return Dv(e,((e,t)=>{const s=r(e,n+1);!yv(s)&&(i[t]=s)})),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:Gv,isThenable:e=>e&&(Rv(e)||Sv(e))&&Sv(e.then)&&Sv(e.catch)};function Hv(e,t,r,n,i){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),n&&(this.request=n),i&&(this.response=i)}qv.inherits(Hv,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:qv.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const Wv=Hv.prototype,Kv={};["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=>{Kv[e]={value:e}})),Object.defineProperties(Hv,Kv),Object.defineProperty(Wv,"isAxiosError",{value:!0}),Hv.from=(e,t,r,n,i,s)=>{const o=Object.create(Wv);return qv.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),Hv.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Jv(e){return qv.isPlainObject(e)||qv.isArray(e)}function Qv(e){return qv.endsWith(e,"[]")?e.slice(0,-2):e}function Xv(e,t,r){return e?e.concat(t).map((function(e,t){return e=Qv(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const Yv=qv.toFlatObject(qv,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Zv(e,t,r){if(!qv.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=qv.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!qv.isUndefined(t[e])}))).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&qv.isSpecCompliantForm(t);if(!qv.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(qv.isDate(e))return e.toISOString();if(!a&&qv.isBlob(e))throw new Hv("Blob is not supported. Use a Buffer instead.");return qv.isArrayBuffer(e)||qv.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(qv.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(qv.isArray(e)&&function(e){return qv.isArray(e)&&!e.some(Jv)}(e)||(qv.isFileList(e)||qv.endsWith(r,"[]"))&&(a=qv.toArray(e)))return r=Qv(r),a.forEach((function(e,n){!qv.isUndefined(e)&&null!==e&&t.append(!0===o?Xv([r],n,s):null===o?r:r+"[]",c(e))})),!1;return!!Jv(e)||(t.append(Xv(i,r,s),c(e)),!1)}const l=[],u=Object.assign(Yv,{defaultVisitor:d,convertValue:c,isVisitable:Jv});if(!qv.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!qv.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),qv.forEach(r,(function(r,s){!0===(!(qv.isUndefined(r)||null===r)&&i.call(t,r,qv.isString(s)?s.trim():s,n,u))&&e(r,n?n.concat(s):[s])})),l.pop()}}(e),t}function eb(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function tb(e,t){this._pairs=[],e&&Zv(e,this,t)}const rb=tb.prototype;function nb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ib(e,t,r){if(!t)return e;const n=r&&r.encode||nb,i=r&&r.serialize;let s;if(s=i?i(t,r):qv.isURLSearchParams(t)?t.toString():new tb(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}rb.append=function(e,t){this._pairs.push([e,t])},rb.toString=function(e){const t=e?function(t){return e.call(this,t,eb)}:eb;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class sb{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){qv.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var ob={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ab={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:tb,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,db=(lb="undefined"!=typeof navigator&&navigator.product,cb&&["ReactNative","NativeScript","NS"].indexOf(lb)<0);var lb;const ub="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var pb={...Object.freeze({__proto__:null,hasBrowserEnv:cb,hasStandardBrowserEnv:db,hasStandardBrowserWebWorkerEnv:ub}),...ab};function hb(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&qv.isArray(n)?n.length:s,a)return qv.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&qv.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&qv.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(qv.isFormData(e)&&qv.isFunction(e.entries)){const r={};return qv.forEachEntry(e,((e,n)=>{t(function(e){return qv.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const fb={transitional:ob,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=qv.isObject(e);i&&qv.isHTMLForm(e)&&(e=new FormData(e));if(qv.isFormData(e))return n?JSON.stringify(hb(e)):e;if(qv.isArrayBuffer(e)||qv.isBuffer(e)||qv.isStream(e)||qv.isFile(e)||qv.isBlob(e))return e;if(qv.isArrayBufferView(e))return e.buffer;if(qv.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Zv(e,new pb.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return pb.isNode&&qv.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=qv.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Zv(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(qv.isString(e))try{return(t||JSON.parse)(e),qv.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||fb.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&qv.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw Hv.from(e,Hv.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:pb.classes.FormData,Blob:pb.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};qv.forEach(["delete","get","head","post","put","patch"],(e=>{fb.headers[e]={}}));var mb=fb;const gb=qv.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 vb=Symbol("internals");function bb(e){return e&&String(e).trim().toLowerCase()}function yb(e){return!1===e||null==e?e:qv.isArray(e)?e.map(yb):String(e)}function wb(e,t,r,n,i){return qv.isFunction(n)?n.call(this,t,r):(i&&(t=r),qv.isString(t)?qv.isString(n)?-1!==t.indexOf(n):qv.isRegExp(n)?n.test(t):void 0:void 0)}class _b{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=bb(t);if(!i)throw new Error("header name must be a non-empty string");const s=qv.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=yb(e))}const s=(e,t)=>qv.forEach(e,((e,r)=>i(e,r,t)));return qv.isPlainObject(e)||e instanceof this.constructor?s(e,t):qv.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach((function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&gb[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t):null!=e&&i(t,e,r),this}get(e,t){if(e=bb(e)){const r=qv.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 n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(qv.isFunction(t))return t.call(this,e,r);if(qv.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=bb(e)){const r=qv.findKey(this,e);return!(!r||void 0===this[r]||t&&!wb(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=bb(e)){const i=qv.findKey(r,e);!i||t&&!wb(0,r[i],i,t)||(delete r[i],n=!0)}}return qv.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!wb(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return qv.forEach(this,((n,i)=>{const s=qv.findKey(r,i);if(s)return t[s]=yb(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(i):String(i).trim();o!==i&&delete t[i],t[o]=yb(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return qv.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&qv.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")}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[vb]=this[vb]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=bb(e);t[n]||(!function(e,t){const r=qv.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})}))}(r,e),t[n]=!0)}return qv.isArray(e)?e.forEach(n):n(e),this}}_b.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),qv.reduceDescriptors(_b.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),qv.freezeMethods(_b);var Sb=_b;function Cb(e,t){const r=this||mb,n=t||r,i=Sb.from(n.headers);let s=n.data;return qv.forEach(e,(function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)})),i.normalize(),s}function Rb(e){return!(!e||!e.__CANCEL__)}function Tb(e,t,r){Hv.call(this,null==e?"canceled":e,Hv.ERR_CANCELED,t,r),this.name="CanceledError"}qv.inherits(Tb,Hv,{__CANCEL__:!0});var kb=pb.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];qv.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),qv.isString(n)&&o.push("path="+n),qv.isString(i)&&o.push("domain="+i),!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 Pb(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var Eb=pb.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function n(r){let n=r;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return r=n(window.location.href),function(e){const t=qv.isString(e)?n(e):e;return t.protocol===r.protocol&&t.host===r.host}}():function(){return!0};function Ob(e,t){let r=0;const n=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[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-i<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return i=>{const s=i.loaded,o=i.lengthComputable?i.total:void 0,a=s-r,c=n(a);r=s;const d={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:i};d[t?"download":"upload"]=!0,e(d)}}var Ib="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){let n=e.data;const i=Sb.from(e.headers).normalize();let s,o,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener("abort",s)}if(qv.isFormData(n))if(pb.hasStandardBrowserEnv||pb.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if(!1!==(o=i.getContentType())){const[e,...t]=o?o.split(";").map((e=>e.trim())).filter(Boolean):[];i.setContentType([e||"multipart/form-data",...t].join("; "))}let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",r=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(t+":"+r))}const u=Pb(e.baseURL,e.url);function p(){if(!l)return;const n=Sb.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new Hv("Request failed with status code "+r.status,[Hv.ERR_BAD_REQUEST,Hv.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}((function(e){t(e),d()}),(function(e){r(e),d()}),{data:a&&"text"!==a&&"json"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),ib(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=p:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(p)},l.onabort=function(){l&&(r(new Hv("Request aborted",Hv.ECONNABORTED,e,l)),l=null)},l.onerror=function(){r(new Hv("Network Error",Hv.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||ob;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(new Hv(t,n.clarifyTimeoutError?Hv.ETIMEDOUT:Hv.ECONNABORTED,e,l)),l=null},pb.hasStandardBrowserEnv&&(c&&qv.isFunction(c)&&(c=c(e)),c||!1!==c&&Eb(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&kb.read(e.xsrfCookieName);t&&i.set(e.xsrfHeaderName,t)}void 0===n&&i.setContentType(null),"setRequestHeader"in l&&qv.forEach(i.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),qv.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&"json"!==a&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",Ob(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",Ob(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{l&&(r(!t||t.type?new Tb(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener("abort",s)));const h=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);h&&-1===pb.protocols.indexOf(h)?r(new Hv("Unsupported protocol "+h+":",Hv.ERR_BAD_REQUEST,e)):l.send(n||null)}))};const Db={http:null,xhr:Ib};qv.forEach(Db,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const xb=e=>`- ${e}`,Mb=e=>qv.isFunction(e)||null===e||!1===e;var jb=e=>{e=qv.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!Mb(r)&&(n=Db[(t=String(r)).toLowerCase()],void 0===n))throw new Hv(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new Hv("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(xb).join("\n"):" "+xb(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Lb(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Tb(null,e)}function Ab(e){Lb(e),e.headers=Sb.from(e.headers),e.data=Cb.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return jb(e.adapter||mb.adapter)(e).then((function(t){return Lb(e),t.data=Cb.call(e,e.transformResponse,t),t.headers=Sb.from(t.headers),t}),(function(t){return Rb(t)||(Lb(e),t&&t.response&&(t.response.data=Cb.call(e,e.transformResponse,t.response),t.response.headers=Sb.from(t.response.headers))),Promise.reject(t)}))}const Nb=e=>e instanceof Sb?e.toJSON():e;function Bb(e,t){t=t||{};const r={};function n(e,t,r){return qv.isPlainObject(e)&&qv.isPlainObject(t)?qv.merge.call({caseless:r},e,t):qv.isPlainObject(t)?qv.merge({},t):qv.isArray(t)?t.slice():t}function i(e,t,r){return qv.isUndefined(t)?qv.isUndefined(e)?void 0:n(void 0,e,r):n(e,t,r)}function s(e,t){if(!qv.isUndefined(t))return n(void 0,t)}function o(e,t){return qv.isUndefined(t)?qv.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(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)=>i(Nb(e),Nb(t),!0)};return qv.forEach(Object.keys(Object.assign({},e,t)),(function(n){const s=c[n]||i,o=s(e[n],t[n],n);qv.isUndefined(o)&&s!==a||(r[n]=o)})),r}const Fb="1.6.7",zb={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{zb[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Vb={};zb.transitional=function(e,t,r){function n(e,t){return"[Axios v1.6.7] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new Hv(n(i," has been removed"+(t?" in "+t:"")),Hv.ERR_DEPRECATED);return t&&!Vb[i]&&(Vb[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}};var Ub={assertOptions:function(e,t,r){if("object"!=typeof e)throw new Hv("options must be an object",Hv.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new Hv("option "+s+" must be "+r,Hv.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new Hv("Unknown option "+s,Hv.ERR_BAD_OPTION)}},validators:zb};const $b=Ub.validators;class Gb{constructor(e){this.defaults=e,this.interceptors={request:new sb,response:new sb}}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/,""):"";e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Bb(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Ub.assertOptions(r,{silentJSONParsing:$b.transitional($b.boolean),forcedJSONParsing:$b.transitional($b.boolean),clarifyTimeoutError:$b.transitional($b.boolean)},!1),null!=n&&(qv.isFunction(n)?t.paramsSerializer={serialize:n}:Ub.assertOptions(n,{encode:$b.function,serialize:$b.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&qv.merge(i.common,i[t.method]);i&&qv.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete i[e]})),t.headers=Sb.concat(s,i);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=[Ab.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=Ab.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 ib(Pb((e=Bb(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}qv.forEach(["delete","get","head","options"],(function(e){Gb.prototype[e]=function(t,r){return this.request(Bb(r||{},{method:e,url:t,data:(r||{}).data}))}})),qv.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,i){return this.request(Bb(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Gb.prototype[e]=t(),Gb.prototype[e+"Form"]=t(!0)}));var qb=Gb;class Hb{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 n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,i){r.reason||(r.reason=new Tb(e,n,i),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)}static source(){let e;return{token:new Hb((function(t){e=t})),cancel:e}}}var Wb=Hb;const Kb={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(Kb).forEach((([e,t])=>{Kb[t]=e}));var Jb=Kb;const Qb=function e(t){const r=new qb(t),n=pv(qb.prototype.request,r);return qv.extend(n,qb.prototype,r,{allOwnKeys:!0}),qv.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(Bb(t,r))},n}(mb);function Xb(e,t){return Rt(e,t)}function Yb(e,t){return r=>(n,i,s)=>e(i())?t(r)(n,i,s):(console.warn("Not authorized to perform this action"),!1)}function Zb(e){return t=>(r,n,i)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,n,i)}function ey(e,t){return Xb(e,((e,r)=>{const{getState:n}=r;return"connected"!==n().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 ty(e,t){return r=>(n,i,s)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):Yb(e,t)(r)(n,i,s)}Qb.Axios=qb,Qb.CanceledError=Tb,Qb.CancelToken=Wb,Qb.isCancel=Rb,Qb.VERSION=Fb,Qb.toFormData=Zv,Qb.AxiosError=Hv,Qb.Cancel=Qb.CanceledError,Qb.all=function(e){return Promise.all(e)},Qb.spread=function(e){return function(t){return e.apply(null,t)}},Qb.isAxiosError=function(e){return qv.isObject(e)&&!0===e.isAxiosError},Qb.mergeConfig=Bb,Qb.AxiosHeaders=Sb,Qb.formToJSON=e=>hb(qv.isHTMLForm(e)?new FormData(e):e),Qb.getAdapter=jb,Qb.HttpStatusCode=Jb,Qb.default=Qb;const ry=((e={})=>{const t=new Map,{extra:r,onError:n=ar}=e;zt(n,"onError");const i=e=>{let r=et(Array.from(t.values()),(t=>t.effect===e.effect));return r||(r=tr(e)),(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&rr(e)}))(r)};Object.assign(i,{withTypes:()=>i});const s=e=>{const{type:r,effect:n,predicate:i}=er(e),s=et(Array.from(t.values()),(e=>("string"==typeof r?e.type===r:e.predicate===i)&&e.effect===n));return s&&(s.unsubscribe(),e.cancelActive&&rr(s)),!!s};Object.assign(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=Zt(i,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,Jt({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Kt(c.signal),pause:Wt(c.signal),extra:r,signal:c.signal,fork:Yt(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach(((e,t,r)=>{e!==c&&(Gt(e,Nt),r.delete(e))}))},cancel:()=>{Gt(c,Nt),e.pending.delete(c)},throwIfCancelled:()=>{qt(c.signal)}})))}catch(e){e instanceof Ft||nr(n,e,{raisedBy:"effect"})}finally{await Promise.all(l),Gt(c,Bt),e.pending.delete(c)}},a=(e=>()=>{e.forEach(rr),e.clear()})(t);return{middleware:e=>r=>c=>{if(!z(c))return r(c);if(ir.match(c))return i(c.payload);if(sr.match(c))return void a();if(or.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===Qt)throw new Error(`${Xt}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),i=Array.from(t.values());for(const t of i){let i=!1;try{i=t.predicate(c,r,d)}catch(e){i=!1,nr(n,e,{raisedBy:"predicate"})}i&&o(t,c,e,l)}}}finally{d=Qt}return u},startListening:i,stopListening:s,clearListeners:a}})(),ny=ry.startListening,iy=(e,t)=>ny({predicate:(t,r,n)=>{const i=e.map((e=>e(n))),s=e.map((e=>e(r)));return i.some(((e,t)=>e!==s[t]))},effect:(r,{dispatch:n,getState:i,extra:s})=>{const o=e.map((e=>e(i())));t({dispatch:n,getState:i,extra:s},...o)}}),sy=It({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,roomName:null,roomUrl:null,displayName:null,userAgent:"core:0.30.2",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:oy,doAppStart:ay}=sy.actions,cy=e=>e.app.isActive,dy=e=>e.app.isDialIn,ly=e=>e.app.roomName,uy=e=>e.app.displayName,py=e=>e.app.userAgent,hy=e=>e.app.externalId;function fy(e){return Xe(`signalConnection/event/${e}`)}const my={audioEnabled:fy("audioEnabled"),audioEnableRequested:fy("audioEnableRequested"),breakoutGroupJoined:fy("breakoutGroupJoined"),chatMessage:fy("chatMessage"),clientLeft:fy("clientLeft"),clientKicked:fy("clientKicked"),clientMetadataReceived:fy("clientMetadataReceived"),clientUnableToJoin:fy("clientUnableToJoin"),cloudRecordingStarted:fy("cloudRecordingStarted"),cloudRecordingStopped:fy("cloudRecordingStopped"),disconnect:fy("disconnect"),knockerLeft:fy("knockerLeft"),knockHandled:fy("knockHandled"),newClient:fy("newClient"),roomJoined:fy("roomJoined"),roomKnocked:fy("roomKnocked"),roomLeft:fy("roomLeft"),roomLocked:fy("roomLocked"),roomSessionEnded:fy("roomSessionEnded"),screenshareStarted:fy("screenshareStarted"),screenshareStopped:fy("screenshareStopped"),spotlightAdded:fy("spotlightAdded"),spotlightRemoved:fy("spotlightRemoved"),streamingStopped:fy("streamingStopped"),videoEnabled:fy("videoEnabled"),videoEnableRequested:fy("videoEnableRequested"),liveTranscriptionStarted:fy("liveTranscriptionStarted"),liveTranscriptionStopped:fy("liveTranscriptionStopped")},gy={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},vy=It({name:"authorization",initialState:{roomKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(ay,((e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey}))),e.addCase(my.roomJoined,((e,t)=>{var r,n;const i=null===(n=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===n?void 0:n.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{roleName:(null==i?void 0:i.role.roleName)||"none"})}))}}),{setRoomKey:by}=vy.actions,yy=e=>e.authorization.roomKey,wy=e=>e.authorization.roleName,_y=Ge(wy,(e=>gy.canLockRoom.includes(e))),Sy=Ge(wy,(e=>gy.canRequestAudioEnable.includes(e))),Cy=Ge(wy,(e=>gy.canRequestVideoEnable.includes(e))),Ry=Ge(wy,(e=>gy.canKickClient.includes(e))),Ty=Ge(wy,(e=>gy.canEndMeeting.includes(e))),ky=Ge(wy,(e=>gy.canAskToSpeak.includes(e))),Py=Ge(wy,(e=>gy.canSpotlight.includes(e)));function Ey(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function Oy(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const Iy=It({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(Dy.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(Dy.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}))),e.addCase(Dy.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!0})))}}),Dy=Xb("deviceCredentials/doGetDeviceCredentials",((e,{extra:t})=>Oy(void 0,void 0,void 0,(function*(){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})))),xy=e=>e.deviceCredentials;iy([Ge(cy,xy,((e,t)=>!(!e||t.isFetching||t.data)))],(({dispatch:e},t)=>{t&&e(Dy())}));const My=It({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(my.disconnect,(e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"})))}}),{deviceIdentifying:jy,deviceIdentified:Ly,socketConnected:Ay,socketConnecting:Ny,socketDisconnected:By,socketReconnecting:Fy}=My.actions,zy=()=>(e,t)=>{if(Hy(t()))return;e(Ny());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new bm(e,{autoConnect:!1})}();r.on("connect",(()=>e(Ay(r)))),r.on("device_identified",(()=>e(Ly()))),r.getManager().on("reconnect",(()=>e(Fy()))),function(e,t){e.on("room_joined",(e=>t(my.roomJoined(e)))),e.on("new_client",(e=>t(my.newClient(e)))),e.on("client_left",(e=>t(my.clientLeft(e)))),e.on("client_kicked",(e=>t(my.clientKicked(e)))),e.on("client_unable_to_join",(e=>t(my.clientUnableToJoin(e)))),e.on("audio_enabled",(e=>t(my.audioEnabled(e)))),e.on("video_enabled",(e=>t(my.videoEnabled(e)))),e.on("audio_enable_requested",(e=>t(my.audioEnableRequested(e)))),e.on("client_metadata_received",(e=>t(my.clientMetadataReceived(e)))),e.on("chat_message",(e=>t(my.chatMessage(e)))),e.on("disconnect",(()=>t(my.disconnect()))),e.on("room_knocked",(e=>t(my.roomKnocked(e)))),e.on("room_left",(()=>t(my.roomLeft()))),e.on("room_locked",(e=>t(my.roomLocked(e)))),e.on("room_session_ended",(e=>t(my.roomSessionEnded(e)))),e.on("knocker_left",(e=>t(my.knockerLeft(e)))),e.on("knock_handled",(e=>t(my.knockHandled(e)))),e.on("screenshare_started",(e=>t(my.screenshareStarted(e)))),e.on("screenshare_stopped",(e=>t(my.screenshareStopped(e)))),e.on("cloud_recording_started",(e=>t(my.cloudRecordingStarted(e)))),e.on("cloud_recording_stopped",(()=>t(my.cloudRecordingStopped()))),e.on("streaming_stopped",(()=>t(my.streamingStopped()))),e.on("spotlight_added",(e=>t(my.spotlightAdded(e)))),e.on("spotlight_removed",(e=>t(my.spotlightRemoved(e)))),e.on("live_transcription_started",(e=>t(my.liveTranscriptionStarted(e)))),e.on("live_transcription_stopped",(e=>t(my.liveTranscriptionStopped(e)))),e.on("video_enable_requested",(e=>t(my.videoEnableRequested(e)))),e.on("breakout_group_joined",(e=>t(my.breakoutGroupJoined(e))))}(r,e),r.connect()},Vy=({deviceCredentials:e})=>(t,r)=>{const n=r(),i=Hy(n),s=Gy(n);i&&(s||(i.emit("identify_device",{deviceCredentials:e}),t(jy())))},Uy=()=>(e,t)=>{const r=t();if("connected"===qy(r)){const t=$y(r).socket;null==t||t.disconnect(),e(By())}},$y=e=>e.signalConnection,Gy=e=>e.signalConnection.deviceIdentified,qy=e=>e.signalConnection.status,Hy=e=>e.signalConnection.socket;iy([Ge(cy,qy,((e,t)=>!(!e||!["ready","reconnecting"].includes(t))))],(({dispatch:e},t)=>{t&&e(zy())}));const Wy=Ge(xy,qy,Gy,(e=>e.signalConnection.isIdentifyingDevice),((e,t,r,n)=>!(!e.data||"connected"!==t||r||n)));iy([Wy,xy],(({dispatch:e},t,r)=>{t&&r.data&&e(Vy({deviceCredentials:r.data}))})),ny({actionCreator:my.roomLeft,effect:(e,{dispatch:t})=>{t(Uy())}}),ny({actionCreator:my.clientKicked,effect:(e,{dispatch:t})=>{t(Uy())}});const Ky=It({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(my.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]})}))}}),Jy=Zb((e=>(t,r)=>{const n=r(),i=$y(n).socket;null==i||i.emit("chat_message",{text:e.text})})),Qy=It({name:"cloudRecording",initialState:{isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{status:"requested"})},extraReducers:e=>{e.addCase(my.cloudRecordingStopped,(e=>Object.assign(Object.assign({},e),{isRecording:!1,status:void 0}))),e.addCase(my.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(my.newClient,((e,{payload:t})=>{var r;const{client:n}=t;return"recorder"===(null===(r=n.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:n.startedCloudRecordingAt?new Date(n.startedCloudRecordingAt).getTime():(new Date).getTime()}):e}))}}),{recordingRequestStarted:Xy}=Qy.actions,Yy=Zb((()=>(e,t)=>{const r=t(),n=$y(r).socket,i=ew(r);i&&["recording","requested"].includes(i)||(null==n||n.emit("start_recording",{recording:"cloud"}),e(Xy()))})),Zy=Zb((()=>(e,t)=>{const r=t(),n=$y(r).socket;null==n||n.emit("stop_recording")})),ew=e=>e.cloudRecording.status,tw=It({initialState:{data:null,isFetching:!1,error:null},name:"organization",reducers:{},extraReducers:e=>{e.addCase(rw.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(rw.fulfilled,((e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(rw.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0})))}}),rw=Xb("organization/doOrganizationFetch",((e,{extra:t,getState:r})=>Oy(void 0,void 0,void 0,(function*(){try{const e=r().app.roomUrl,n=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!n)throw new Error("Invalid room url");return n}catch(e){console.error(e)}})))),nw=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};function iw(e,{delay:t=500,edges:r}={}){let n,i=0;return(...s)=>{i+=1,r&&1===i&&e(...s),clearTimeout(n),n=setTimeout((()=>{(!r||i>1)&&e(...s),n=void 0,i=0}),t)}}iy([Ge(cy,(e=>e.organization),xy,((e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching)))],(({dispatch:e},t)=>{t&&e(rw())}));const sw=It({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:n}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:n.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter((e=>e!==r.deviceId&&e!==n.deviceId))})}},extraReducers:e=>{e.addCase(ay,((e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions}))),e.addCase(ww.pending,((e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:n,isSettingMicrophoneDevice:r})})),e.addCase(ww.fulfilled,((e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})})),e.addCase(ww.rejected,((e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:n?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})})),e.addCase(vw.pending,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0}))),e.addCase(vw.fulfilled,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1}))),e.addCase(_w.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}))),e.addCase(Cw.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(Cw.fulfilled,((e,{payload:{stream:t,onDeviceChange:r}})=>{let n,i,s=!1,o=!1;const a=t.getAudioTracks()[0],c=t.getVideoTracks()[0];return a&&(i=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,n=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:n,currentMicrophoneDeviceId:i,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})})),e.addCase(Cw.rejected,((e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error}))),e.addCase(Sw.pending,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0}))),e.addCase(Sw.fulfilled,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))),e.addCase(Sw.rejected,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})))}}),{deviceBusy:ow,setCurrentCameraDeviceId:aw,setCurrentMicrophoneDeviceId:cw,setCurrentSpeakerDeviceId:dw,toggleCameraEnabled:lw,toggleMicrophoneEnabled:uw,toggleLowDataModeEnabled:pw,setLocalMediaOptions:hw,setLocalMediaStream:fw,localMediaStopped:mw,localStreamMetadataUpdated:gw}=sw.actions,vw=Xb("localMedia/doToggleCamera",((e,{getState:t,rejectWithValue:r})=>Oy(void 0,void 0,void 0,(function*(){const e=t(),n=Aw(e);if(!n)return;let i=n.getVideoTracks()[0];const s=Ow(e);try{if(s)if(i)i.enabled=!0;else{const t=Bw(e),r=kw(e);yield Qm(Object.assign(Object.assign({},t),{audioId:!1,videoId:r,type:"exact"}),{replaceStream:n}),i=n.getVideoTracks()[0]}else{if(!i)return;i.enabled=!1,i.stop(),n.removeTrack(i)}n.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:i,enable:s}}))}catch(e){return r(e)}})))),bw=Xb("localMedia/doToggleMicrophone",((e,{getState:t})=>{var r;const n=t(),i=Aw(n);if(!i)return;const s=Iw(n),o=null===(r=i.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)})),yw=()=>(e,t)=>{const r=t();if(!Aw(r))return;const n=kw(r),i=Pw(r);e(Sw({audioId:i,videoId:n}))},ww=Xb("localMedia/reactSetDevice",(({audio:e,video:t},{getState:r,rejectWithValue:n})=>Oy(void 0,void 0,void 0,(function*(){try{const n=r(),i=Aw(n);if(!i)throw new Error("No stream");const s=!!e&&Pw(n),o=!!t&&kw(n),a=Bw(n),{replacedTracks:c}=yield Qm(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:i}),d=Iw(n);i.getAudioTracks().forEach((e=>e.enabled=d));const l=Ow(n);return i.getVideoTracks().forEach((e=>e.enabled=l)),{replacedTracks:c}}catch(e){return n(e)}})))),_w=Xb("localMedia/doUpdateDeviceList",((e,{getState:t,dispatch:r,rejectWithValue:n})=>Oy(void 0,void 0,void 0,(function*(){var e,i,s,o;const a=t();let c=[],d=[];const l=Aw(a);try{c=yield navigator.mediaDevices.enumerateDevices(),d=xw(a);if(!(l&&!Nw(a)&&c&&d&&d.find((e=>e.deviceId))))return{devices:c};const{changedDevices:t,addedDevices:n}=Xm({oldDevices:d,newDevices:c});let u=null===(e=t.audioinput)||void 0===e?void 0:e.deviceId,p=null===(i=t.videoinput)||void 0===i?void 0:i.deviceId;return void 0===u&&(u=null===(s=n.audioinput)||void 0===s?void 0:s.deviceId),void 0===p&&(p=null===(o=n.videoinput)||void 0===o?void 0:o.deviceId),void 0===u&&void 0===p||r(Sw({audioId:u,videoId:p})),{devices:c}}catch(e){return n(e)}})))),Sw=Xb("localMedia/doSwitchLocalStream",(({audioId:e,videoId:t},{dispatch:r,getState:n,rejectWithValue:i})=>Oy(void 0,void 0,void 0,(function*(){const s=n(),o=Aw(s),a=Bw(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:n}=yield Qm(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),i=e||t;return c&&i&&r(ow({deviceId:i})),{replacedTracks:n}}catch(n){console.error(n);const s=e||t;return c&&s&&r(ow({deviceId:s})),i(n)}})))),Cw=Xb("localMedia/doStartLocalMedia",((e,{getState:t,dispatch:r,rejectWithValue:n})=>Oy(void 0,void 0,void 0,(function*(){const i=iw((()=>{r(_w())}),{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",i),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:i});if(!e.audio&&!e.video)return{stream:new MediaStream,onDeviceChange:i};r(hw({options:e}));try{yield r(_w());const n=t(),s=Bw(n),{stream:o}=yield Qm(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:i}}catch(e){return n(e)}})))),Rw=()=>(e,t)=>{const r=Aw(t()),n=jw(t()).onDeviceChange;null==r||r.getTracks().forEach((e=>{e.stop()})),navigator.mediaDevices&&n&&navigator.mediaDevices.removeEventListener("devicechange",n),e(mw())},Tw=e=>e.localMedia.busyDeviceIds,kw=e=>e.localMedia.currentCameraDeviceId,Pw=e=>e.localMedia.currentMicrophoneDeviceId,Ew=e=>e.localMedia.currentSpeakerDeviceId,Ow=e=>e.localMedia.cameraEnabled,Iw=e=>e.localMedia.microphoneEnabled,Dw=e=>e.localMedia.lowDataMode,xw=e=>e.localMedia.devices,Mw=e=>e.localMedia.options;Ge(Mw,(e=>!!e));const jw=e=>e.localMedia,Lw=e=>e.localMedia.status,Aw=e=>e.localMedia.stream,Nw=e=>e.localMedia.isSwitchingStream,Bw=Ge(xw,kw,Pw,Dw,((e,t,r,n)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:n,simulcast:!0,widescreen:!0}}))),Fw=Ge(Lw,(e=>"starting"===e)),zw=Ge(xw,Tw,((e,t)=>e.filter((e=>"videoinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),Vw=Ge(xw,Tw,((e,t)=>e.filter((e=>"audioinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),Uw=Ge(xw,(e=>e.filter((e=>"audiooutput"===e.kind))));iy([Ge(cy,Lw,Mw,((e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r}))],(({dispatch:e},t)=>{t&&e(Cw(t))}));iy([Ge(cy,Lw,Mw,((e,t,r)=>!e&&"inactive"!==t&&!!r))],(({dispatch:e},t)=>{t&&e(Rw())})),ny({predicate:(e,t,r)=>{const n=Iw(r),i=Iw(t);return"started"===Lw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(bw())}}),ny({predicate:(e,t,r)=>{const n=Dw(r),i=Dw(t);return"started"===Lw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(yw())}}),ny({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const n=Ow(r),i=Ow(t);return"started"===Lw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(vw())}}),ny({predicate:(e,t,r)=>{const n=kw(r),i=kw(t);return"started"===Lw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(ww({audio:!1,video:!0}))}}),ny({predicate:(e,t,r)=>{const n=Pw(r),i=Pw(t);return"started"===Lw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(ww({audio:!0,video:!1}))}}),ny({matcher:yt(Cw.fulfilled,_w.fulfilled,Sw.fulfilled,Sw.rejected),effect:(e,{dispatch:t,getState:r})=>{const n=r(),i=Aw(n),s=xw(n);if(!i)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:n,lastAudioId:i,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||n,e=o(e),{video:Km("videoinput",t,r,s),audio:Km("audioinput",e,r,i)}}({audioTrack:i.getAudioTracks()[0],videoTrack:i.getVideoTracks()[0],devices:s});t(gw(o))}}),ny({actionCreator:my.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(uw({enabled:!1}))}}),ny({actionCreator:my.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(lw({enabled:!1}))}});const $w=["recorder","streamer"],Gw=It({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,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})},extraReducers:e=>{e.addCase(ay,((e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}))),e.addCase(Ww.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload}))),e.addCase(Kw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload}))),e.addCase(Jw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload}))),e.addCase(my.roomJoined,((e,t)=>{var r,n;const i=null===(n=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===n?void 0:n.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{id:t.payload.selfId,roleName:(null==i?void 0:i.role.roleName)||"none",clientClaim:t.payload.clientClaim,breakoutGroup:(null==i?void 0:i.breakoutGroup)||null})})),e.addCase(my.breakoutGroupJoined,((e,t)=>{var r,n;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(n=t.payload)||void 0===n?void 0:n.group})}))}}),{setDisplayName:qw}=Gw.actions,Hw=Zb((e=>(t,r)=>{const n=r(),i=$y(n).socket;null==i||i.emit("send_client_metadata",{type:"UserData",payload:{displayName:e.displayName}}),t(qw({displayName:e.displayName}))})),Ww=ey("localParticipant/doEnableAudio",((e,{dispatch:t,getState:r})=>Oy(void 0,void 0,void 0,(function*(){const n=r(),i=$y(n).socket;return null==i||i.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(Jw({enabled:!1})),e.enabled})))),Kw=ey("localParticipant/doEnableVideo",((e,{getState:t})=>Oy(void 0,void 0,void 0,(function*(){const r=t(),n=$y(r).socket;return null==n||n.emit("enable_video",{enabled:e.enabled}),e.enabled})))),Jw=ey("localParticipant/doSetLocalStickyReaction",((e,{getState:t,rejectWithValue:r})=>Oy(void 0,void 0,void 0,(function*(){var n;const i=t(),s=e_(i),o=Boolean(s),a=null!==(n=e.enabled)&&void 0!==n?n:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})))),Qw=Zb((()=>(e,t)=>{const r=t(),n=$y(r).socket,i={displayName:Zw(r),stickyReaction:e_(r)};null==n||n.emit("send_client_metadata",{type:"UserData",payload:i})})),Xw=e=>e.localParticipant,Yw=e=>e.localParticipant.id,Zw=e=>e.localParticipant.displayName,e_=e=>e.localParticipant.stickyReaction,t_=Ge(Xw,Aw,((e,t)=>{const r={id:e.id,clientId:e.id,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return $w.includes(e.roleName)?null:r}));ny({actionCreator:lw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isVideoEnabled:i}=Xw(r());t(Kw({enabled:n||!i}))}}),ny({actionCreator:uw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isAudioEnabled:i}=Xw(r());t(Ww({enabled:n||!i}))}}),iy([Zw,e_],(({dispatch:e})=>{e(Qw())}));const r_=It({initialState:{session:null,status:"ready",error:null},name:"roomConnection",reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(my.roomJoined,((e,t)=>{var r,n;const{error:i,isLocked:s}=t.payload;return"room_locked"===i&&s?Object.assign(Object.assign({},e),{status:"room_locked"}):i?Object.assign(Object.assign({},e),{status:"disconnected",error:i}):Object.assign(Object.assign({},e),{status:"connected",session:null!==(n=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==n?n:null})})),e.addCase(my.disconnect,(e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"}))),e.addCase(my.newClient,((e,t)=>{var r,n;return Object.assign(Object.assign({},e),{session:null!==(n=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==n?n:null})})),e.addCase(my.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(my.clientKicked,(e=>Object.assign(Object.assign({},e),{status:"kicked"}))),e.addCase(my.roomLeft,(e=>Object.assign(Object.assign({},e),{status:"left"}))),e.addCase(Fy,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"})))}}),{connectionStatusChanged:n_}=r_.actions,i_=()=>(e,t)=>{const r=t(),n=$y(r).socket,i=ly(r),s=yy(r),o=uy(r),a=dy(r),c=py(r),d=hy(r),l=nw(r);"room_locked"===o_(r)?(null==n||n.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:i,userAgent:c,externalId:d}),e(n_("knocking"))):console.warn("Room is not locked, knock aborted")},s_=()=>(e,t)=>{const r=t(),n=$y(r).socket,i=ly(r),s=yy(r),o=uy(r),a=py(r),c=hy(r),d=dy(r),l=nw(r),u=Ow(t()),p=Iw(t()),h=(e=>e.localParticipant.clientClaim)(t());null==n||n.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:i,userAgent:a,externalId:c},h&&{clientClaim:h})),e(n_("connecting"))},o_=e=>e.roomConnection.status;function a_(e){return Xe(`rtcConnection/event/${e}`)}iy([Ge([cy,nw,o_,Gy,Lw,e=>e.roomConnection.error],((e,t,r,n,i,s)=>!(!(e&&"started"===i&&n&&t&&["ready","reconnecting","disconnected"].includes(r))||s)))],(({dispatch:e},t)=>{t&&e(s_())})),ny({actionCreator:my.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:n,resolution:i}=e,s=r();n===Yw(s)&&("accepted"===i?(t(by(e.metadata.roomKey)),t(s_())):"rejected"===i&&t(n_("knock_rejected")))}}),ny({actionCreator:oy,effect:(e,{dispatch:t,getState:r})=>{const n=r();if("connected"===o_(n)){const e=$y(n).socket;null==e||e.emit("leave_room"),t(n_("leaving"))}else Uy()}});const c_={rtcManagerCreated:a_("rtcManagerCreated"),rtcManagerDestroyed:a_("rtcManagerDestroyed"),streamAdded:a_("streamAdded")};function d_(e,t=!1){const{streams:r,role:n,breakoutGroup:i}=e,s=Ey(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==n?void 0:n.roleName)||"none",presentationStream:null,breakoutGroup:i||null,newJoiner:t})}function l_(e,t){const r=e.remoteParticipants.findIndex((e=>e.id===t));return{index:r,participant:e.remoteParticipants[r]}}function u_(e,t,r){const{participant:n,index:i}=l_(e,t);return n?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,i),Object.assign(Object.assign({},n),r),...e.remoteParticipants.slice(i+1)]}):(console.error(`Did not find client for update ${t}`),e)}function p_(e,t,r,n){const{participant:i}=l_(e,t);if(!i)return console.error(`No client ${t} found to update stream ${r} ${n}`),e;const s=i.streams.findIndex((e=>e.id===r)),o=[...i.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:n}),u_(e,t,{streams:o})}function h_(e,t,r){const{participant:n}=l_(e,t);return!n||n.streams.find((e=>e.id===r))?(console.warn(`No participant ${t} or stream ${r} already exists`),e):u_(e,t,{streams:[...n.streams,{id:r,state:"to_accept"}]})}const f_=It({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:n,state:i}of t.payload)r=p_(r,e,n,i);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:n}=t.payload;return u_(e,r,{stream:n})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:n}=t.payload;return h_(e,r,n)}},extraReducers:e=>{e.addCase(my.roomJoined,((e,t)=>{var r;if(!(null===(r=t.payload)||void 0===r?void 0:r.room))return e;const n=t.payload.selfId,{clients:i}=t.payload.room;return Object.assign(Object.assign({},e),{remoteParticipants:i.filter((e=>e.id!==n)).map((e=>d_(e)))})})),e.addCase(c_.streamAdded,((e,t)=>function(e,t){const{clientId:r,stream:n,streamType:i}=t;let{streamId:s}=t;const{participant:o}=l_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=n.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"===i||!c.stream&&!i&&!d?u_(e,r,{stream:n}):u_(e,r,{presentationStream:n})}(e,t.payload))),e.addCase(my.newClient,((e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=l_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,d_(r,!0))})),e.addCase(my.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(my.audioEnabled,((e,t)=>{const{clientId:r,isAudioEnabled:n}=t.payload;return u_(e,r,{isAudioEnabled:n})})),e.addCase(my.videoEnabled,((e,t)=>{const{clientId:r,isVideoEnabled:n}=t.payload;return u_(e,r,{isVideoEnabled:n})})),e.addCase(my.clientMetadataReceived,((e,t)=>{const{error:r,payload:n}=t.payload;if(r||!n)return console.warn(r||"Client metadata error received"),e;const{clientId:i,displayName:s,stickyReaction:o}=n;return u_(e,i,{displayName:s,stickyReaction:o})})),e.addCase(my.breakoutGroupJoined,((e,t)=>{const{clientId:r,group:n}=t.payload;return u_(e,r,{breakoutGroup:n||null})})),e.addCase(my.screenshareStarted,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return h_(e,r,n)})),e.addCase(my.screenshareStopped,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return function(e,t,r){var n,i;const{participant:s}=l_(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===(n=s.presentationStream)||void 0===n?void 0:n.inboundId)||(null===(i=s.presentationStream)||void 0===i?void 0:i.id),c=s.streams.findIndex((e=>e.id===r));return u_(e,t,Object.assign(Object.assign({streams:s.streams.filter(((e,t)=>t!==c))},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,n)}))}}),{participantStreamAdded:m_,participantStreamIdAdded:g_,streamStatusUpdated:v_}=f_.actions,b_=ty((e=>Sy(e)),(e=>(t,r)=>{const n=r(),i=ky(n);if(e.enable&&!i)return void console.warn("Not authorized to perform this action");const s=$y(n).socket;null==s||s.emit("request_audio_enable",e)})),y_=ty((e=>Cy(e)),(e=>(t,r)=>{const n=r(),i=$y(n).socket;null==i||i.emit("request_video_enable",e)})),w_=e=>e.remoteParticipants.remoteParticipants,__=Ge(w_,(e=>e.filter((e=>!$w.includes(e.roleName)))));Ge(w_,(e=>e.length+1));const S_=Ge(__,Xw,((e,t)=>$w.includes(t.roleName)?e.length:e.length+1)),C_=It({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(T_.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(T_.fulfilled,((e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t}))),e.addCase(T_.rejected,((e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null})))}}),{stopScreenshare:R_}=C_.actions,T_=ey("localScreenshare/doStartScreenshare",((e,{dispatch:t,getState:r,rejectWithValue:n})=>Oy(void 0,void 0,void 0,(function*(){var e;try{const n=r(),i=P_(n);if(i)return{stream:i};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t(k_())};return"oninactive"in s?s.addEventListener("inactive",o):null===(e=s.getVideoTracks()[0])||void 0===e||e.addEventListener("ended",o),{stream:s}}catch(e){return n(e)}})))),k_=Zb((()=>(e,t)=>{const r=t(),n=P_(r);n&&(n.getTracks().forEach((e=>e.stop())),e(R_({stream:n})))})),P_=e=>e.localScreenshare.stream;ny({actionCreator:mw,effect:(e,{getState:t})=>{const r=t(),n=P_(r);n&&(null==n||n.getTracks().forEach((e=>{e.stop()})))}});const E_=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(U_(r)):"stream_added"===t?e(c_.streamAdded(r)):"rtc_manager_destroyed"===t&&e(L_())}}),O_={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},I_=It({name:"rtcConnection",initialState:O_,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:n,height:i}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:n,height:i}})})},rtcDisconnected:()=>Object.assign({},O_),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})},extraReducers:e=>{e.addCase(Fy,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))),e.addCase(my.roomJoined,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status})))}}),{resolutionReported:D_,rtcDispatcherCreated:x_,rtcDisconnected:M_,rtcManagerCreated:j_,rtcManagerDestroyed:L_,rtcManagerInitialized:A_,isAcceptingStreams:N_}=I_.actions,B_=()=>(e,t)=>{const r=t(),n=$y(r).socket,i=G_(r).rtcManagerDispatcher,s=Ow(r),o=Iw(r),a=(e=>e.app.isNodeSdk)(r);if(i||!n)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable:e=>!e},d=new cv({emitter:E_(e),serverSocket:n,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,vp9On:!1,h264On:!1,simulcastScreenshareOn:!1,deviceHandlerFactory:a?Kc.createFactory():void 0}});e(x_(d))},F_=()=>(e,t)=>{const{rtcManager:r}=G_(t());r&&r.disconnectAll(),e(M_())},z_=e=>(t,r)=>{var n;t(N_(!0));const i=r(),s=G_(i).rtcManager,o=w_(i);if(!s)throw new Error("No rtc manager");const a=null===(n=s.shouldAcceptStreamsFromBothSides)||void 0===n?void 0:n.call(s),c=[];for(const{clientId:t,streamId:r,state:n}of e){if(o.find((e=>e.id===t))){if("to_accept"===n||"new_accept"===n&&a||"old_accept"===n&&!a)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:false});else if("new_accept"===n||"old_accept"===n);else if("to_unaccept"===n)null==s||s.disconnect("0"===r?t:r,false);else if("done_accept"!==n)continue;c.push({clientId:t,streamId:r,state:n.replace(/to_|new_|old_/,"done_")})}}t(v_(c)),t(N_(!1))},V_=({streamId:e,width:t,height:r})=>(n,i)=>{const{reportedStreamResolutions:s,rtcManager:o}=G_(i()),a=Aw(i());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}),n(D_({streamId:e,width:t,height:r}))},U_=e=>t=>{const{rtcManager:r}=e;t(j_(r))},$_=()=>(e,t)=>{const r=Aw(t()),n=G_(t()).rtcManager,i=Ow(t()),s=Iw(t());r&&n&&n.addNewStream("0",r,!s,!i),e(A_())},G_=e=>e.rtcConnection,q_=e=>e.rtcConnection.rtcManagerInitialized,H_=e=>e.rtcConnection.rtcManager,W_=e=>e.rtcConnection.status;ny({actionCreator:ww.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:n}=G_(t()),i=Aw(t());null==r||r.forEach((e=>{((e,t)=>{const r=null==i?void 0:i.getTracks().find((t=>t.kind===e));r&&(null==n||n.replaceTrack(t,r))})(e.kind,e)}))}}),ny({actionCreator:T_.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=G_(t());null==n||n.addNewStream(r.id,r,!1,!0)}}),ny({actionCreator:oy,effect:(e,{getState:t})=>{const r=H_(t());null==r||r.rtcStatsDisconnect()}}),ny({actionCreator:R_,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=G_(t());null==n||n.removeStream(r.id,r,null)}}),ny({actionCreator:Sw.fulfilled,effect:({payload:e},{getState:t})=>{var r;const n=Aw(t()),{rtcManager:i}=G_(t());if(n&&i){const t=(e,t)=>{const r=n.getTracks().find((t=>t.kind===e));return r&&i.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach((e=>{t(e.kind,e)}))}}});iy([Ge(W_,cy,(e=>e.rtcConnection.dispatcherCreated),(e=>e.rtcConnection.isCreatingDispatcher),Hy,((e,t,r,n,i)=>!(!t||"inactive"!==e||r||n||!i)))],(({dispatch:e},t)=>{t&&e(B_())}));const K_=Ge(H_,q_,Lw,((e,t,r)=>!("started"!==r||!e||t)));iy([K_],(({dispatch:e},t)=>{t&&e($_())}));iy([Ge(W_,cy,((e,t)=>!t&&!["inactive","disconnected"].includes(e)))],(({dispatch:e},t)=>{t&&e(F_())}));const J_=Ge(W_,w_,((e,t)=>{if("ready"!==e)return[];const r=[];for(const e of t){const{streams:t,id:n,newJoiner:i}=e;for(let e=0;e<t.length;e++){let s=t[e].id,o=t[e].state;(null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===e?(s=t[1].id,o=t[1].state):1===e&&(s=t[0].id,o=t[0].state)),"done_accept"!==o&&r.push({clientId:n,streamId:s,state:(i&&"0"===s?"new":"to")+"_accept"})}}return r}));function Q_(e){return"recorder"===e.roleName}iy([J_,e=>e.rtcConnection.isAcceptingStreams],(({dispatch:e},t,r)=>{0<t.length&&!r&&e(z_(t))}));const X_=It({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(my.roomJoined,((e,t)=>{const{error:r,isLocked:n}=t.payload;return r?e:Object.assign(Object.assign({},e),{isLocked:Boolean(n)})})),e.addCase(my.roomLocked,((e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})}))}}),Y_=Yb((e=>_y(e)),(e=>(t,r)=>{const n=r(),{socket:i}=$y(n);null==i||i.emit("set_lock",{locked:e.locked})})),Z_=Yb((e=>Ry(e)),(e=>(t,r)=>{const n=r(),{socket:i}=$y(n);null==i||i.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})})),eS=Yb((e=>Ty(e)),(e=>(t,r)=>{const n=r(),i=w_(n).map((e=>e.id));if(i.length){const{socket:e}=$y(n);null==e||e.emit("kick_client",{clientIds:i,reasonId:"end-meeting"})}e.stayBehind||t(oy())})),tS=Ge(P_,Xw,__,((e,t,r)=>{const n=[];e&&n.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&&n.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 n})),rS=Ge(P_,Xw,__,((e,t,r)=>{const n=[];if(e){const r=!!e.getAudioTracks().length;n.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e})}for(const e of r){if("streamer"===e.roleName||Q_(e))continue;const{presentationStream:t}=e,r=Ey(e,["presentationStream"]),i=e.displayName||"Guest",s=t&&t.active,o="pres-"+e.id,a=e.stream&&e.stream.active,c=e.isVideoEnabled;n.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,displayName:i,hasActivePresentation:!!s}),e.isVideoEnabled?{isVideoEnabled:c}:{})),s&&n.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${i})`,id:o,isPresentation:!0,isVideoEnabled:!0}),a&&{isRecording:null}))}return n})),nS=Ge(t_,rS,((e,t)=>[...e?[e]:[],...t])),iS={running:!1},sS=It({name:"connectionMonitor",initialState:iS,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},iS)}}),{connectionMonitorStarted:oS,connectionMonitorStopped:aS}=sS.actions,cS=()=>(e,t)=>{var r;r=()=>{const e=t(),r=nS(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},bf.getClients=r;const n=Mm({onUpdatedIssues:e=>{var r;const n=t(),i=H_(n);if(!i)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)})),i.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(oS({stopIssueSubscription:n.stop}))},dS=()=>(e,t)=>{const r=t(),n=uS(r);n&&n(),e(aS())},lS=e=>e.connectionMonitor.running,uS=e=>e.connectionMonitor.stopCallbackFunction,pS=Ge(o_,lS,((e,t)=>!t&&"connected"===e)),hS=Ge(o_,lS,((e,t)=>!(!t||!["kicked","left"].includes(e))));iy([pS],(({dispatch:e},t)=>{t&&e(cS())})),iy([hS],(({dispatch:e},t)=>{t&&e(dS())}));function fS(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const mS=It({name:"notifications",initialState:{emitter:new Jl,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:[]})}});mS.actions;const gS=e=>(t,r)=>{t(mS.actions.addNotification(e));const n=r(),i=vS(n);i.emit(e.type,e),i.emit("*",e)},vS=e=>e.notifications.emitter;ny({actionCreator:my.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const n=r(),i=__(n).find((({id:t})=>t===e.senderId));i?t(gS(fS({type:"chatMessageReceived",message:`${i.displayName} says: ${e.text}`,props:{client:i,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),ny({actionCreator:my.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=__(s).find((({id:e})=>e===i));o?t(gS(fS({type:n?"requestAudioEnable":"requestAudioDisable",message:n?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local audio change")}}),ny({actionCreator:my.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=__(s).find((({id:e})=>e===i));o?t(gS(fS({type:n?"requestVideoEnable":"requestVideoDisable",message:n?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local video change")}}),ny({actionCreator:my.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:n})=>{var i;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=n();if(!ky(d))return;const l=__(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=__(u).find((({id:e})=>e===a));(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(i=null==p?void 0:p.stickyReaction)||void 0===i?void 0:i.timestamp)&&t(gS(fS({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),iy([qy],(({dispatch:e,getState:t},r)=>{const n=t(),i=o_(n);["left","kicked"].includes(i)||("disconnected"===r?e(gS(fS({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(gS(fS({type:"signalOk",message:"Network connection available",props:{}}))))})),ny({actionCreator:my.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(gS(fS({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const bS={audioEnabled:{actions:[Ww.fulfilled],rtcEventName:"audioEnabled",getValue:e=>Iw(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[Kw.fulfilled],rtcEventName:"videoEnabled",getValue:e=>Ow(e),getOutput:e=>({enabled:e})},localStream:{actions:[ww.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=Aw(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:[T_.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=P_(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:[R_],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[qw],rtcEventName:"displayName",getValue:e=>uy(e),getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>Yw(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>(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})(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>hy(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>nw(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>qy(e),getOutput:e=>({status:e})},roomSessionId:{actions:[my.newClient,my.roomJoined,my.roomSessionEnded,my.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=>W_(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>wy(e),getOutput:e=>({userRole:e})}},yS=Object.values(bS).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)),wS=e=>"object"==typeof e?JSON.stringify(e):e,_S=It({initialState:{reportedValues:{}},name:"rtcAnalytics",reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),SS=()=>(e,t)=>{const r=t(),n=G_(r).rtcManager;n&&(n.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(bS).forEach((({rtcEventName:t,getValue:i,getOutput:s})=>{var o;const a=i(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=wS(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(n.sendStatsCustomEvent(t,c),e(CS({rtcEventName:t,value:a})))})))},{updateReportedValues:CS}=_S.actions;function RS({isPresentation:e,stream:t}){var r,n;return e?null!==(n=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==n?n: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)}ny({matcher:yt(...yS),effect:({type:e},{getState:t,dispatch:r})=>{var n;const i=t(),s=G_(i).rtcManager;if(!s)return;const o=Object.values(bS).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(i),u=wS(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(n=i.rtcAnalytics.reportedValues)||void 0===n?void 0:n[d])!==u&&(s.sendStatsCustomEvent(d,p),r(CS({rtcEventName:d,value:l})))}}),iy([q_],(({dispatch:e},t)=>{t&&e(SS())}));const kS=It({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:TS(e.sorted,{clientId:r,streamId:n})})},removeSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===n)))})}},extraReducers:e=>{e.addCase(my.roomJoined,((e,t)=>{if(!t.payload.room)return e;const{spotlights:r}=t.payload.room;return Object.assign(Object.assign({},e),{sorted:r})})),e.addCase(my.spotlightAdded,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:TS(e.sorted,{clientId:r,streamId:n})})})),e.addCase(my.spotlightRemoved,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===n)))})})),e.addMatcher(yt(my.clientKicked,my.clientLeft),((e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>e.clientId!==r))})}))}}),{addSpotlight:PS,removeSpotlight:ES}=kS.actions,OS=Yb((e=>Py(e)),(({id:e})=>(t,r)=>{const n=r(),i=nS(n).find((t=>t.clientId===e));if(!i)return;const{socket:s}=$y(n),o=RS(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)})),IS=Yb((e=>Py(e)),(({id:e})=>(t,r)=>{const n=r(),i=nS(n).find((t=>t.clientId===e));if(!i)return;const{socket:s}=$y(n),o=RS(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)})),DS=e=>e.spotlights.sorted;Ge(Xw,DS,((e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:n}){return!!e.find((e=>{const i=RS({isPresentation:t,stream:n});return e.clientId===r&&e.streamId===i}))}({clientId:e.id,stream:e.stream,spotlights:t})));const xS=Ge(nS,DS,((e,t)=>function(e,t){return e.reduce(((e,r)=>{const n=t.find((e=>r.clientId===e.clientId&&r.streamId===RS(e)));return n&&!e.includes(n)&&e.push(n),e}),[])}(t,e)));ny({actionCreator:T_.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=Xw(i);s&&r(PS({clientId:s.id,streamId:n.id}))}}),ny({actionCreator:R_,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=Xw(i);s&&r(ES({clientId:s.id,streamId:n.id}))}});const MS=It({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})}});MS.actions;const jS=It({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(my.roomJoined,((e,{payload:t})=>{var r;return(null===(r=t.room)||void 0===r?void 0:r.knockers.length)?Object.assign(Object.assign({},e),{waitingParticipants:t.room.knockers.map((e=>({id:e.clientId,displayName:e.displayName})))}):e})),e.addCase(my.roomKnocked,((e,t)=>{const{clientId:r,displayName:n}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:n}]})})),e.addCase(my.knockerLeft,((e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter((e=>e.id!==r))})}))}}),LS=Zb((e=>(t,r)=>{const{participantId:n}=e,i=r(),s=Hy(i);null==s||s.emit("handle_knock",{action:"accept",clientId:n,response:{}})})),AS=Zb((e=>(t,r)=>{const{participantId:n}=e,i=r(),s=Hy(i);null==s||s.emit("handle_knock",{action:"reject",clientId:n,response:{}})}));const NS=null===!1&&!1,BS=B({app:sy.reducer,authorization:vy.reducer,chat:Ky.reducer,cloudRecording:Qy.reducer,connectionMonitor:sS.reducer,deviceCredentials:Iy.reducer,localMedia:sw.reducer,localParticipant:Gw.reducer,localScreenshare:C_.reducer,notifications:mS.reducer,organization:tw.reducer,remoteParticipants:f_.reducer,room:X_.reducer,roomConnection:r_.reducer,rtcAnalytics:_S.reducer,rtcConnection:I_.reducer,signalConnection:My.reducer,spotlights:kS.reducer,streaming:MS.reducer,waitingParticipants:jS.reducer}),FS=(e,t)=>{var r;if(ay.match(t)){const n={app:Object.assign(Object.assign({},sy.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},sw.getInitialState()),null==e?void 0:e.localMedia)};return BS(n,t)}return BS(e,t)};class zS{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 VS(e,t){return Tf.ok(e,`${t} is required`),e}function US(e,t){return Tf.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function $S(e,t){return Tf.ok("number"==typeof e,`${t}<number> is required`),e}function GS(e,t){return Tf.ok("string"==typeof e,`${t}<string> is required`),e}function qS(e,t,r){const n=r||t.name[0].toLowerCase()+t.name.substring(1);return Tf.ok(e instanceof t,`${n}<${t.name}> is required`),e}function HS(e,t){return Tf.ok(Array.isArray(e),`${t}<array> is required`),e}function WS(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 KS(e,t,r){GS(t,"name"),function(e,t,r,n){GS(r,"name");const i=n||`${r} must be null or of type ${t}`;Tf.ok(null===e||typeof e===t,i)}(e,"string",t,r)}function JS({baseUrl:e,url:t}){return e?e+t:t}class QS{constructor({baseUrl:e}){GS(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return Qb.request(r)}request(e,t){return GS(e,"url"),Tf.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Tf.ok(t,"options are required"),this._requestAxios(e,t).then((e=>{const{data:t,headers:r,status:n,statusText:i,config:s}=e,o=s&&s.url?JS({baseUrl:s.baseURL,url:s.url}):null;return new zS({data:t,headers:r,status:n,statusText:i,url:o})})).catch((e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:n,status:i,statusText:s,config:o}=t,a=o&&o.url?JS({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new zS({data:r,headers:n,status:i,statusText:s,url:a}))}))}}class XS{constructor({httpClient:e}){Tf.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){Tf.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach((r=>{const n=e[r];t.append(r,n)})),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:XS.dataToFormData}))}}let YS;YS="object"==typeof window?window.btoa||uv:"object"==typeof global&&global.btoa||uv;const ZS=()=>Promise.resolve(null);class eC{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then((r=>{const n=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${YS(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),i=Object.assign({},t,{headers:n});return this._httpClient.request(e,i)}))}}class tC{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=ZS}={}){this.authenticatedHttpClient=new eC({httpClient:new QS({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new XS({httpClient:this.authenticatedHttpClient})}request(e,t){return GS(e,"url"),Tf.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Tf.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return GS(e,"url"),Tf.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),Tf.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function rC(e,t){return GS(WS(e,"data")[t],t)}const nC=(iC=rC,(e,t)=>{const r=WS(e,"data")[t];return null==r?null:iC(e,t)});var iC;function sC(e,t,r){return function(e,t){return HS(WS(e,"data")[t],t)}(e,t).map((e=>r(e)))}class oC{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 oC(rC(function(e,t){const r=WS(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),rC(e,"hmac"),nC(e,"userId")||void 0)}}class aC{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then((({data:e})=>oC.fromJson(e))).catch((e=>{if(e.response&&404===e.response.status)return null;throw e}))}}class cC{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 dC{constructor(e,t){VS(t,"localStorage"),this._key=GS(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 lC;try{lC=self.localStorage}catch(dO){lC={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var uC=lC;const pC="credentials_saved";class hC extends Jl{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const n=new aC({apiClient:new tC({baseUrl:e})});let i=null;if("localStorage"===r)i=new dC(t,uC);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);i=new cC(t,window.chrome.storage.local)}return new hC({deviceService:n,credentialsStore:i})}_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?oC.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(pC,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 fC{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:n}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=n}static fromJson(e){return new fC({isExhausted:US(e.isExhausted,"isExhausted"),renewsAt:new Date(GS(e.renewsAt,"renewsAt")),totalMinutesLimit:$S(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:$S(e.totalMinutesUsed,"totalMinutesUsed")})}}class mC{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:n,onTrialUntil:i,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=n,this.onTrialUntil=i||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new mC({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:US(e.isDeactivated,"isDeactivated"),isOnTrial:US(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?fC.fromJson(e.embeddedFreeTierStatus):null})}}function gC(e){return null!=e}function vC(e={}){return{maxNumberOfInvitationsAndUsers:gC(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:gC(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:gC(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:gC(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:gC(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class bC{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,qS(e,Object,"properties"),GS(e.organizationId,"organizationId"),GS(e.organizationName,"organizationName"),GS(e.subdomain,"subdomain"),qS(e.permissions,Object,"permissions"),qS(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 mC(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=qS(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},n=(null==t?void 0:t.onboardingSurvey)||null,i=qS(t.permissions,Object,"permissions");return new bC({organizationId:GS(t.organizationId,"organizationId"),organizationName:GS(t.organizationName,"organizationName"),subdomain:GS(t.subdomain,"subdomain"),permissions:i,limits:vC(qS(t.limits,Object,"limits")),account:t.account?mC.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:n,type:"string"==typeof t.type?t.type:null})}}bC.GLOBAL_ORGANIZATION_ID="1";class yC{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:n,consents:i}=r||{},s="email"in r?{value:r.email,verificationCode:GS(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(GS(t,"subdomain"),GS(e,"organizationName"),GS(n,"owner.displayName"),Tf.ok(s||o,"owner.email or owner.idToken is required"),i){HS(i,"consents");for(const{consentRevisionId:e,action:t}of i)GS(e,"consentRevisionId"),KS(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}),i&&{consents:i}),{displayName:n})}}).then((({data:e})=>rC(e,"organizationId")))}getOrganizationBySubdomain(e){return GS(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then((({data:e})=>bC.fromJson(e))).catch((e=>{if(e instanceof zS){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationByOrganizationId(e){return GS(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then((({data:e})=>bC.fromJson(e))).catch((e=>{if(e instanceof zS){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,n="phoneNumber"in e?e.phoneNumber:null;Tf.ok((r||n)&&!(r&&n),"either email or phoneNumber is required"),GS(t,"code");const i=r?{type:"email",value:r}:{type:"phoneNumber",value:n};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:i,code:t}}).then((({data:e})=>sC(e,"organizations",(e=>bC.fromJson(e)))))}getOrganizationsByIdToken({idToken:e}){return GS(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then((({data:e})=>sC(e,"organizations",(e=>bC.fromJson(Object.assign({permissions:{},limits:{}},WS(e,"organization")))))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then((({data:e})=>sC(e,"organizations",(e=>bC.fromJson(Object.assign({permissions:{},limits:{}},WS(e,"organization")))))))}getSubdomainAvailability(e){return GS(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then((({data:e})=>(qS(e,Object,"data"),{status:rC(e,"status")})))}updatePreferences({organizationId:e,preferences:t}){return VS(e,"organizationId"),VS(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}deleteOrganization({organizationId:e}){return VS(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then((()=>{}))}}class wC{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 _C="https://api.whereby.dev";const SC=s.createContext(null);P(SC);const CC=function(e=v){const t=e===v?O:P(e),r=()=>t().dispatch;return Object.assign(r,{withTypes:()=>r}),r}(SC),RC=function(e=v){const t=e===v?y:b(e),r=(e,r={})=>{const{equalityFn:n=_,devModeChecks:i={}}="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 n)throw new Error("You must pass a function as an equality function to useSelector");const{store:s,subscription:o,getServerState:a,stabilityCheck:c,identityFunctionCheck:d}=t(),l=h.useRef(!0),u=h.useCallback({[e.name](t){const r=e(t);{const{identityFunctionCheck:s,stabilityCheck:o}={stabilityCheck:c,identityFunctionCheck:d,...i};if("always"===o||"once"===o&&l.current){const i=e(t);if(!n(r,i)){let n;try{throw new Error}catch(e){({stack:n}=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:r,selected2:i,stack:n})}}if(("always"===s||"once"===s&&l.current)&&r===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})}l.current&&(l.current=!1)}return r}}[e.name],[e,c,i.stabilityCheck]),p=w(o.addNestedSub,s.getState,a||s.getState,u,n);return h.useDebugValue(p),p};return Object.assign(r,{withTypes:()=>r}),r}(SC);var TC=function(){return TC=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},TC.apply(this,arguments)};function kC(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}"function"==typeof SuppressedError&&SuppressedError;const PC=CC.withTypes(),EC=RC.withTypes(),OC=s.forwardRef(((e,t)=>{var{muted:r,mirror:n=!1,stream:i,onVideoResize:o}=e,a=kC(e,["muted","mirror","stream","onVideoResize"]);const c=PC(),d=EC(Ew),l=s.useRef(null),u=s.useRef(null);return s.useImperativeHandle(t,(()=>Object.assign(l.current,{captureAspectRatio:()=>{if(!l.current)return null;const e=l.current.videoHeight,t=l.current.videoWidth;return t&&e&&t+e>20?t/e:null}}))),s.useEffect((()=>{if(!l.current)return;const e=new ResizeObserver(iw((()=>{if(l.current&&(null==i?void 0:i.id)){const e=l.current.clientWidth,t=l.current.clientHeight;c(V_({streamId:i.id,width:e,height:t})),o&&o({width:e,height:t,stream:i})}}),{delay:1e3,edges:!0}));return e.observe(l.current),()=>{e.disconnect()}}),[i]),s.useEffect((()=>{l.current&&(l.current.srcObject!==i&&(l.current.srcObject=i),l.current.muted!==r&&(l.current.muted=Boolean(r)))}),[r,i,l]),s.useEffect((()=>{u.current&&!r&&i&&d&&(u.current.srcObject!==i&&(u.current.srcObject=i),u.current.setSinkId&&u.current.setSinkId(d))}),[i,u,d,r]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:l,autoPlay:!0,playsInline:!0},a,{style:Object.assign({transform:n?"scaleX(-1)":"none",width:"100%",height:"100%"},a.style)})),s.createElement("audio",{ref:u,autoPlay:!0,playsInline:!0}))}));OC.displayName="VideoView";const IC=Ge((e=>e.chat.chatMessages),(e=>e.cloudRecording),Xw,Aw,__,tS,o_,(e=>e.streaming),(e=>e.waitingParticipants.waitingParticipants),vS,xS,((e,t,r,n,i,s,o,a,c,d,l)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,connectionStatus:o,events:d,liveStream:a.isStreaming?{status:"streaming",startedAt:a.startedAt}:void 0,localScreenshareStatus:r.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},r),{stream:n}),remoteParticipants:i,screenshares:s,waitingParticipants:c,spotlightedParticipants:l}))),DC={localMediaOptions:{audio:!0,video:!0}};const xC=Ge((e=>e.localMedia.cameraDeviceError),zw,kw,Pw,Ew,(e=>e.localMedia.isSettingCameraDevice),(e=>e.localMedia.isSettingMicrophoneDevice),Fw,Aw,(e=>e.localMedia.microphoneDeviceError),Vw,Uw,(e=>e.localMedia.startError),((e,t,r,n,i,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:n,currentSpeakerDeviceId:i,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p})));var MC={MIN_WINDOW_HEIGHT:320,MIN_WINDOW_WIDTH:320,DESKTOP_BREAKPOINT:1025,TABLET_BREAKPOINT:750,PHONE_BREAKPOINT:500,TOP_TOOLBAR_HEIGHT:56,BOTTOM_TOOLBAR_HEIGHT:82,SIDEBAR_WIDTH:375,VIDEO_CONTROLS_MIN_WIDTH:420,ROOM_FOOTER_MIN_WIDTH:600,FLOATING_VIDEO_CONTROLS_BOTTOM_MARGIN:20,WATERMARK_BAR_HEIGHT:32,BREAKOUT_STAGE_BACKDROP_HEADER_HEIGHT:28,BREAKOUT_STAGE_BACKDROP_FOOTER_HEIGHT:56,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800,GROUPS_CELL_MARGIN:8,GROUPS_CELL_PADDING:12,GROUPS_CELL_NAV_HEIGHT:56,GROUPS_CELL_AVATAR_WRAPPER_BOTTOM_MARGIN:8,GROUPS_CELL_AVATAR_GRID_GAP:8,GROUPS_CELL_MIN_WIDTH:360,GROUPS_CELL_MAX_WIDTH:600,GROUPS_ROW_HEIGHT:72,GROUPS_ROW_GAP:1,FOLDABLE_SCREEN_STAGE_PADDING:8};function jC({top:e=0,left:t=0}={}){return{top:e,left:t}}function LC({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function AC({top:e=0,left:t=0,width:r=0,height:n=0}={}){return{bounds:LC({width:r,height:n}),origin:jC({top:e,left:t})}}function NC({top:e=0,left:t=0,bottom:r=0,right:n=0}={}){return{top:e,left:t,bottom:r,right:n}}function BC(e){return!!e&&!(e.width<=0||e.height<=0)}function FC(e,t){const{width:r,height:n}=t,i=n,s=i*e,o=Math.min(r/s,n/i);return{width:s*o,height:i*o}}const zC=({vertical:e,width:t,height:r,count:n,aspectRatio:i})=>{const s=[1,2,3].map((s=>(({width:e,height:t,rows:r,cols:n,aspectRatio:i})=>{const s=FC(i,{width:e/n,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(n/s):s,cols:e?s:Math.ceil(n/s),aspectRatio:i}))),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}},VC=({width:e,height:t,count:r,aspectRatio:n})=>{const i=zC({vertical:!0,width:e,height:t,count:r,aspectRatio:n}),s=zC({vertical:!1,width:e,height:t,count:r,aspectRatio:n});return i.weight>s.weight?{splits:i.splits,vertical:!0}:{splits:s.splits,vertical:!1}};function UC(e){var{aspectRatio:t,children:r,className:n,height:i,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=kC(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=i,h=0,f=0;t&&(({width:u,height:p}=FC(t,{width:a,height:i})),h=(a-u)/2,f=(i-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:n,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 $C({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 GC({cell:e,child:t,clientId:r,style:n={},withRoundedCorners:i=!1,withShadow:o=!1}){const a=!BC(e.bounds);return s.createElement(UC,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:n,withRoundedCorners:i,withShadow:o,key:r},t)}function qC({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:n,gridContent:i=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=AC(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return i.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){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 GC({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:n,style:p,withShadow:i})}));return c}({content:i,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){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 GC({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:n,withShadow:i})}))}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),n&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:n}){var i;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===(i=e.props.client)||void 0===i?void 0:i.id)||"floating";return GC({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:n,withShadow:!1})}({content:n,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:n}){const i=t.subgrid.cells;return e.map(((e,o)=>{var a,c,d,l;const u=i[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 GC({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:n})}))}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},BC(a.bounds)&&s.createElement("div",{style:$C(a)}),p,t&&s.createElement(s.Fragment,null))}const HC=16/9,WC=4/3,KC=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function JC({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let n=null;if(t===r)n=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(i=e).sort(((e,t)=>i.filter((t=>t===e)).length-i.filter((e=>e===t)).length)).pop():r;n=KC({value:t||r,min:WC,max:HC})}var i;return{minAr:t,maxAr:r,chosenAr:n}}function QC({width:e,height:t,cellCount:r,gridGap:n,cellAspectRatios:i=[WC],paddings:s=NC()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:n,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=JC({choices:i});let d=c.chosenAr;const{rows:l,cols:u}=function({count:e,width:t,height:r,aspectRatio:n}){if(e<=1)return{rows:1,cols:1};const{splits:i,vertical:s}=VC({width:t,height:r,count:e,aspectRatio:n});return s?{rows:Math.ceil(e/i),cols:i}:{rows:i,cols:Math.ceil(e/i)}}({count:r,width:o,height:a,aspectRatio:d});1===l?d=KC({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=KC({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:n,gridGap:i,aspectRatio:s}){const o=(e-(n-1)*i)/n,a=(t-(r-1)*i)/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*n/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:n,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:n,paddings:s}}const XC="rows",YC="columns";function ZC({layoutGrid:e,dim:t,secDim:r,index:n,count:i,gridGap:s}){const o=(t-s*(i-1))*(e.fractions?e.fractions[n]:1/i),a=e.lines[n];return[o,(r-s*(a-1))/a]}function eR({isHorizontal:e,layoutGrid:t,width:r,height:n,gridGap:i}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?n:r,u=e?r:n;for(let r=0;r<d;r++){const n=ZC({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:i}),p={width:e?n[1]:n[0],height:e?n[0]:n[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+i:c.y+=p.height+i;e?(c.y+=p.height+i,c.x=o):(c.x+=p.width+i,c.y=a)}return s}function tR({layoutGrid:e,width:t,height:r,gridGap:n}){switch(e.type){case XC:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return eR({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n});case YC:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return eR({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n})}}function rR({width:e,height:t,cellCount:r,gridGap:n=0,paddings:i=NC()}){const s=e-(i.left+i.right),o=t-(i.top+i.bottom);return{cellRects:tR({layoutGrid:Math.round(s/o*10)/10<=1?{1:{type:XC,lines:[1]},2:{type:XC,lines:[1,1]},3:{type:XC,lines:[2,1]},4:{type:XC,lines:[2,2]},5:{type:XC,lines:[2,2,1]},6:{type:XC,lines:[2,2,2]},7:{type:XC,lines:[3,2,2]},8:{type:XC,lines:[2,2,2,2]},9:{type:XC,lines:[3,2,2,2]},10:{type:XC,lines:[3,3,2,2]},11:{type:XC,lines:[3,3,3,2]},12:{type:XC,lines:[3,3,3,3]},13:{type:XC,lines:[2,2,3,3,3]},14:{type:XC,lines:[2,3,3,3,3]},15:{type:XC,lines:[3,3,3,3,3]},16:{type:XC,lines:[2,2,3,3,3,3]},17:{type:XC,lines:[2,3,3,3,3,3]},18:{type:XC,lines:[3,3,3,3,3,3]},19:{type:XC,lines:[2,2,3,3,3,3,3]},20:{type:XC,lines:[2,3,3,3,3,3,3]},21:{type:XC,lines:[3,3,3,3,3,3,3]},22:{type:XC,lines:[2,2,3,3,3,3,3,3]},23:{type:XC,lines:[2,3,3,3,3,3,3,3]},24:{type:XC,lines:[3,3,3,3,3,3,3,3]}}[r]||{type:XC,lines:[3,3,3,3,3,3,3,3]}:function(e){return{1:{type:YC,lines:[1]},2:{type:YC,lines:[1,1]},3:{type:YC,lines:[2,1]},4:{type:YC,lines:[2,2]},5:{type:XC,lines:[3,2],fractions:[.45,.55]},6:{type:YC,lines:[2,2,2]},7:{type:XC,lines:[4,3],fractions:[.45,.55]},8:{type:YC,lines:[2,2,2,2]},9:{type:YC,lines:[3,2,2,2]},10:{type:YC,lines:[3,3,2,2]},11:{type:YC,lines:[3,3,3,2]},12:{type:YC,lines:[3,3,3,3]},13:{type:YC,lines:[4,3,3,3]},14:{type:YC,lines:[4,4,3,3]},15:{type:YC,lines:[3,3,3,3,3]},16:{type:YC,lines:[4,3,3,3,3]},17:{type:YC,lines:[4,4,3,3,3]},18:{type:YC,lines:[4,4,4,3,3]},19:{type:YC,lines:[4,4,4,4,3]},20:{type:YC,lines:[4,4,4,4,4]},21:{type:YC,lines:[5,4,4,4,4]},22:{type:YC,lines:[5,5,4,4,4]},23:{type:YC,lines:[5,5,5,4,4]},24:{type:YC,lines:[5,5,5,5,4]}}[e]||{type:YC,lines:[5,5,5,5,5]}}(r),width:s,height:o,gridGap:n})||[],cellCount:r,gridGap:n,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:i}}function nR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:n,paddings:i=NC()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-i.left-i.right,p=e.height-i.top-i.bottom;return r&&(t?(c=Math.floor(u/n.width),a=Math.ceil(r/c),s=u,o=a*n.height,d=(u-c*n.width)/2):(a=Math.floor(p/n.height),c=Math.ceil(r/a),s=c*n.width,o=p,l=(p-a*n.height)/2)),{isPortrait:t,width:s+i.left+i.right,height:o+i.top+i.bottom,cellBounds:n,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:i}}const{BOTTOM_TOOLBAR_HEIGHT:iR,VIDEO_CONTROLS_MIN_WIDTH:sR,TABLET_BREAKPOINT:oR,SUBGRID_EMPTY_STAGE_MAX_WIDTH:aR}=MC,cR=200,dR=300,lR=200,uR=20,pR=12,hR=NC({top:4,bottom:28,left:8,right:8});function fR({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function mR({cellCount:e}){const t=e<=6;return LC({width:t?dR-50:dR,height:t?cR-50:cR})}function gR({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){let o;for(let a=0;a<n.length;a++){const c=n[a];if(o=nR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:LC({width:c+i.left+i.right,height:c+i.top+i.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}),a=o.cellBounds.width-i.left-i.right===n[n.length-1],c=LC({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=LC({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:n,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:n,cols:i,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/i):Math.floor(e%n),u=r?Math.floor(e%i):Math.floor(e/n),p=function({index:e,isPortrait:t,rows:r,cols:n,cellBounds:i,cellCount:s}){const o=r*n,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?n:r)-a)+1||e>c?0:a*(t?i.width:i.height)/2}({index:e,isPortrait:r,rows:n,cols:i,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:jC({top:r,left:n}),bounds:LC({width:s,height:c}),paddings:i,isSmallCell:a}}))}}function vR({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:n,gridGap:i,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:AC(),subgrid:Object.assign(Object.assign({},AC()),{contentBounds:LC(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:AC(Object.assign(Object.assign({},r),n)),subgrid:Object.assign(Object.assign({},AC()),{contentBounds:LC(),cells:[]}),hasOverflow:s};const y=h?uR:0;let w=null;if(v)if(h){const n=t[0];let i=d?iR:iR+e.top+(c||u?n/2:n)+e.bottom;r.height-i<cR&&(i=0),w=LC({width:r.width,height:i})}else w=LC(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=LC({width:Math.min(aR,r.width),height:r.height});let _=0;w.width>p&&(_=(w.width-p)/2);const S=gR({containerBounds:w,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:NC({top:y,left:_,right:_})}),C=LC({width:S.contentBounds.width-w.width,height:S.contentBounds.height-w.height}),R=C.width>0||C.height>0;let T,k=null;k=!v||h||R?S.contentBounds:S.bounds;let P=k;v?(P=LC(h?{width:0,height:w.height+y+i}:l?{width:0,height:S.bounds.height+i}:{width:S.bounds.width+i,height:0}),T=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})):T=LC();const E=Object.assign({},n);let O;return O=jC(v?{top:l?Math.max(n.top+g-P.height+i,0):n.top,left:l?n.left:Math.max(n.left+m-k.width,0)}:{top:n.top+Math.max(0,(g-k.height)/2),left:n.left+Math.max(0,(m-k.width)/2)}),{isPortrait:l,videosContainer:AC(Object.assign(Object.assign({},T),E)),subgrid:Object.assign(Object.assign({},AC(Object.assign(Object.assign({},k),O))),{cells:S.videoCells.map(((e,t)=>{var r,n;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(n=f[t])||void 0===n?void 0:n.clientId},e)})),contentBounds:S.contentBounds}),hasOverflow:R||h||s,overflowNeedBounds:h?LC():C}}function bR({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:n,hasPresentationContent:i,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=LC(),p=jC(),h=o?Object.assign({},e):LC(),f=o?Object.assign({},t):jC();if(i){const i=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:n}){const{width:i,height:s}=e;if(!(r.width>0))return{isPortrait:i<=s,supersizedContentBounds:e};const o=Math.round(i/2),a=Math.round(s/2),c=Math.max(i-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;if(t){const e=FC(t,{width:c,height:s}),r=FC(t,{width:i,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)}}else n&&(l=c/d>=5);return{isPortrait:l,supersizedContentBounds:{width:l?i:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:n||1,minGridContainerBounds:LC({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=i.isPortrait,u=i.supersizedContentBounds,p=Object.assign({},t),o&&(h=LC({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=jC({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},AC(Object.assign(Object.assign({},u),p))),videoGrid:AC(Object.assign(Object.assign({},h),f))}}function yR({containerBounds:e,paddings:t=NC(),videos:r,isConstrained:n,maxGridWidth:i,gridGap:s}){const{width:o,height:a}=e,c=i?Math.min(o,i):o,d=r.length;let l=null,u=null;if(n){const e=rR({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),n=d>4;u=r.map(((t,r)=>{const i=function({index:e,layout:t}){const{cellRects:r}=t,n=r[e]||AC();return{top:n.origin.y,left:n.origin.x,width:n.bounds.width,height:n.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:jC({top:i.top,left:i.left}),bounds:LC({width:i.width,height:i.height}),aspectRatio:i.width/i.height,isSmallCell:n,type:"video"}})),l=e}else{const e=r.map((e=>e.aspectRatio||1)),i=mR({cellCount:d}),o=QC({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:n,rows:i,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:n,cellCount:i,gridGap:s}){const o=e*t,a=o-i;if(!a)return 0;const c=o-a-1;return n>=c-(t-a)+1&&n<=c?a*r/2+s:0}({rows:i,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*n+c*a,left:d*r+d*a+l,width:r,height:n}}({index:t,layout:o}),s=o.cellWidth<i.width,a=n||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:jC({top:r.top,left:r.left}),bounds:LC({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 wR({a:e,b:t,gridGap:r,isPortrait:n}){const i=n?e.vertical:e.horizontal,s=n?t.vertical:t.horizontal;if(i===s)return{a:0,b:0};const o=i<s?e:t,a=n?o.vertical:o.horizontal,c=(r+(i+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function _R({gridGap:e,isConstrained:t,presentationVideos:r,videos:n,videosContainerLayout:i,gridLayoutPaddings:s=NC(),presentationGridLayoutPaddings:o=NC(),maxGridWidth:a}){return{gridLayout:yR({containerBounds:i.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:n}),presentationGridLayout:yR({containerBounds:i.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function SR({floatingVideo:e,frame:t,gridGap:r,isConstrained:n,isMaximizeMode:i=!1,isXLMeetingSize:s=!1,paddings:o=NC(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=hR,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=n&&f.length>pR,T=S/4,k=Math.ceil((f.length-pR)/3);S=R?S+T*k:S;const P=LC({width:_,height:S}),E=jC({top:o.top,left:o.left}),O=mR({cellCount:f.length}),I=d.width<oR||d.height<oR,D=i||g||!(v||w)||P.width<=P.height,x={cellPaddings:u,containerBounds:P,containerOrigin:E,gridGap:r,hasPresentationContent:v,hasVideoContent:w,isConstrained:n,isMaximizeMode:i,isSmallScreen:I,subgridVideos:p,maxGridWidth:C};let M=vR(Object.assign(Object.assign({},x),{cellSizeOptions:fR({hasOverflow:g,hasStage:v||w}),isPortrait:D,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})),j=!1;if(!g&&l&&!M.hasOverflow){vR(Object.assign(Object.assign({},x),{containerBounds:LC({width:P.width,height:P.height-iR}),cellSizeOptions:fR({hasOverflow:g,hasStage:v||w}),isPortrait:D,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})).hasOverflow&&(j=!0)}(j||M.hasOverflow&&!g)&&(g=!0,M=vR(Object.assign(Object.assign({},x),{cellSizeOptions:fR({hasOverflow:!0,hasStage:v||w}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})));const L=bR({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:w,minGridBounds:O});let{gridLayout:A,presentationGridLayout:N}=_R({gridGap:m||r,isConstrained:n,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:n,videosContainerLayout:i}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,n.extraVerticalPadding);s={presentationGrid:Math.min(i.isPortrait?n.extraVerticalPadding:t,e.height),grid:Math.min(i.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,n.extraHorizontalPadding);o={presentationGrid:Math.min(i.isPortrait?t:n.extraHorizontalPadding,e.width),grid:Math.min(i.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||LC(),stageLayout:M,gridLayout:A,presentationGridLayout:N,videosContainerLayout:L});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:n}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=n.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,n.presentationGrid.bounds.height-=2*e.presentationGrid,n.videoGrid.bounds.height-=2*e.grid,n.isPortrait&&(n.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=n.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,n.presentationGrid.bounds.width-=2*t.presentationGrid,n.videoGrid.bounds.width-=2*t.grid,n.isPortrait||(n.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:L}),({gridLayout:A,presentationGridLayout:N}=_R({gridGap:m||r,isConstrained:n,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C})))}const B=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:n,margin:i=8}){if(!r)return null;const s=FC(r.aspectRatio||0,{width:lR,height:lR}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+i)<sR;let c=0;o&&a?c=-1*n:o||a||(c=n);const d=jC({top:t.origin.top+(t.bounds.height-s.height-i)+c,left:t.origin.left+(t.bounds.width-s.width-i)});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:n,gridGap:i,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=n.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const n=wR({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:i,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=n.a,e.videoGrid.origin.top-=n.b,d.vertical=n.b):(e.presentationGrid.origin.left+=n.a,e.videoGrid.origin.left-=n.b,d.horizontal=n.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&&!n.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&n.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=wR({a:l,b:{horizontal:0,vertical:0},gridGap:i,isPortrait:n.isPortrait});n.isPortrait?n.subgrid.origin.top-=p.b:n.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:LC({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:jC({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:LC({height:g?F:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},L.presentationGrid),{cells:N.videoCells,paddings:NC({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:NC({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)||jC(),bounds:(null==B?void 0:B.bounds)||LC(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function CR({aspectRatio:e,avatarSize:t,cellPaddings:r,client:n,isDraggable:i=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:n,clientId:(null==n?void 0:n.id)||"",isDraggable:i,isPlaceholder:s,isSubgrid:o,type:"video"}}const RR=12,TR=12,kR=24;function PR({activeVideosSubgridTrigger:e=TR,stageParticipantLimit:t=RR,forceSubgrid:r=!0,enableSubgrid:n=!0,maximizedParticipant:i,floatingParticipant:o,isConstrained:a=!1}={}){const c=EC(nS),d=EC(xS),l=EC(S_),u=s.useMemo((()=>o),[o]),p=s.useMemo((()=>u?c.filter((e=>e.id!==u.id)):c),[c,u]),h=s.useMemo((()=>!!n&&(!!r||l>t)),[r,l,t,n]),f=s.useMemo((()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:n,maximizedParticipant:i,isPhoneResolution:s}){if(!r)return[];const o=n.length>0,a=(i?e.filter((e=>e.id!==i.id)):e).filter((e=>!e.isPresentation&&!n.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>kR){const e=[...l,...u],t=e.slice(0,kR);return t.length<=kR?[...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:i,isPhoneResolution:a})),[p,h,e,d,a]),m=s.useMemo((()=>p.filter((e=>!f.includes(e)))),[p,f]),g=s.useMemo((()=>i?[i]:d),[d,i]),v=s.useMemo((()=>m.filter((e=>!g.includes(e)))),[m,g]);return{floatingClientView:u,clientViewsInGrid:v,clientViewsInPresentationGrid:g,clientViewsInSubgrid:f}}var ER={exports:{}};const OR=55296,IR=56319,DR=56320,xR=127462,MR=127487,jR=127995,LR=127999,AR=65024,NR=65039,BR=8400,FR=8447,zR=8205,VR=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function UR(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,n=0;for(;r<e.length;)n+=$R(r+n,e),WR(e[r+n])&&n++,qR(e[r+n])&&n++,HR(e[r+n])&&n++,KR(e[r+n])?n++:(t.push(e.substring(r,r+n)),r+=n,n=0);return t}function $R(e,t){const r=t[e];if(!function(e){return e&&QR(e[0].charCodeAt(0),OR,IR)}(r)||e===t.length-1)return 1;const n=r+t[e+1];let i=t.substring(e+2,e+5);return GR(n)&&GR(i)||function(e){return QR(JR(e),jR,LR)}(i)?4:2}function GR(e){return QR(JR(e),xR,MR)}function qR(e){return"string"==typeof e&&QR(e.charCodeAt(0),AR,NR)}function HR(e){return"string"==typeof e&&QR(e.charCodeAt(0),BR,FR)}function WR(e){return"string"==typeof e&&-1!==VR.indexOf(e.charCodeAt(0))}function KR(e){return"string"==typeof e&&e.charCodeAt(0)===zR}function JR(e){return(e.charCodeAt(0)-OR<<10)+(e.charCodeAt(1)-DR)+65536}function QR(e,t,r){return e>=t&&e<=r}ER.exports=UR,ER.exports.substr=function(e,t,r){const n=UR(e);if(void 0===t)return e;if(t>=n.length)return"";const i=n.length-t;let s=t+(void 0===r?i:r);return s>t+i&&(s=void 0),n.slice(t,s).join("")};var XR=c(ER.exports);const YR=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map((e=>XR(e)[0])).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,n=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},n))};function ZR(e){var{avatarUrl:t,className:r,size:n=40,name:i,variant:o="round"}=e,a=kC(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${n}px`,width:`${n}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:i},a),!t&&i?s.createElement(YR,{name:i}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function eT({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:n}){return s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:n?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement(ZR,{variant:"square",avatarUrl:e,name:t,size:r?60:80})))}function tT(){return tT=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},tT.apply(this,arguments)}function rT(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(null==e||e(n),!1===r||!n.defaultPrevented)return null==t?void 0:t(n)}}function nT(...e){return t=>e.forEach((e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t)))}function iT(...e){return t.useCallback(nT(...e),e)}function sT(e,r=[]){let n=[];const i=()=>{const r=n.map((e=>t.createContext(e)));return function(n){const i=(null==n?void 0:n[e])||r;return t.useMemo((()=>({[`__scope${e}`]:{...n,[e]:i}})),[n,i])}};return i.scopeName=e,[function(r,i){const s=t.createContext(i),o=n.length;function a(r){const{scope:n,children:i,...a}=r,c=(null==n?void 0:n[e][o])||s,d=t.useMemo((()=>a),Object.values(a));return t.createElement(c.Provider,{value:d},i)}return n=[...n,i],a.displayName=r+"Provider",[a,function(n,a){const c=(null==a?void 0:a[e][o])||s,d=t.useContext(c);if(d)return d;if(void 0!==i)return i;throw new Error(`\`${n}\` must be used within \`${r}\``)}]},oT(i,...r)]}function oT(...e){const r=e[0];if(1===e.length)return r;const n=()=>{const n=e.map((e=>({useScope:e(),scopeName:e.scopeName})));return function(e){const i=n.reduce(((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]})),{});return t.useMemo((()=>({[`__scope${r.scopeName}`]:i})),[i])}};return n.scopeName=r.scopeName,n}const aT=t.forwardRef(((e,r)=>{const{children:n,...i}=e,s=t.Children.toArray(n),o=s.find(lT);if(o){const e=o.props.children,n=s.map((r=>r===o?t.Children.count(e)>1?t.Children.only(null):t.isValidElement(e)?e.props.children:null:r));return t.createElement(cT,tT({},i,{ref:r}),t.isValidElement(e)?t.cloneElement(e,void 0,n):null)}return t.createElement(cT,tT({},i,{ref:r}),n)}));aT.displayName="Slot";const cT=t.forwardRef(((e,r)=>{const{children:n,...i}=e;return t.isValidElement(n)?t.cloneElement(n,{...uT(i,n.props),ref:r?nT(r,n.ref):n.ref}):t.Children.count(n)>1?t.Children.only(null):null}));cT.displayName="SlotClone";const dT=({children:e})=>t.createElement(t.Fragment,null,e);function lT(e){return t.isValidElement(e)&&e.type===dT}function uT(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{s(...e),i(...e)}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}const pT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce(((e,r)=>{const n=t.forwardRef(((e,n)=>{const{asChild:i,...s}=e,o=i?aT:r;return t.useEffect((()=>{window[Symbol.for("radix-ui")]=!0}),[]),t.createElement(o,tT({},s,{ref:n}))}));return n.displayName=`Primitive.${r}`,{...e,[r]:n}}),{});function hT(e){const r=t.useRef(e);return t.useEffect((()=>{r.current=e})),t.useMemo((()=>(...e)=>{var t;return null===(t=r.current)||void 0===t?void 0:t.call(r,...e)}),[])}const fT="dismissableLayer.update",mT="dismissableLayer.pointerDownOutside",gT="dismissableLayer.focusOutside";let vT;const bT=t.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yT=t.forwardRef(((e,r)=>{var n;const{disableOutsidePointerEvents:i=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:c,onDismiss:d,...l}=e,u=t.useContext(bT),[p,h]=t.useState(null),f=null!==(n=null==p?void 0:p.ownerDocument)&&void 0!==n?n:null===globalThis||void 0===globalThis?void 0:globalThis.document,[,m]=t.useState({}),g=iT(r,(e=>h(e))),v=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=v.indexOf(b),w=p?v.indexOf(p):-1,_=u.layersWithOutsidePointerEventsDisabled.size>0,S=w>=y,C=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const n=hT(e),i=t.useRef(!1),s=t.useRef((()=>{}));return t.useEffect((()=>{const e=e=>{if(e.target&&!i.current){const t={originalEvent:e};function o(){_T(mT,n,t,{discrete:!0})}"touch"===e.pointerType?(r.removeEventListener("click",s.current),s.current=o,r.addEventListener("click",s.current,{once:!0})):o()}else r.removeEventListener("click",s.current);i.current=!1},t=window.setTimeout((()=>{r.addEventListener("pointerdown",e)}),0);return()=>{window.clearTimeout(t),r.removeEventListener("pointerdown",e),r.removeEventListener("click",s.current)}}),[r,n]),{onPointerDownCapture:()=>i.current=!0}}((e=>{const t=e.target,r=[...u.branches].some((e=>e.contains(t)));S&&!r&&(null==o||o(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f),R=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const n=hT(e),i=t.useRef(!1);return t.useEffect((()=>{const e=e=>{if(e.target&&!i.current){_T(gT,n,{originalEvent:e},{discrete:!1})}};return r.addEventListener("focusin",e),()=>r.removeEventListener("focusin",e)}),[r,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}((e=>{const t=e.target;[...u.branches].some((e=>e.contains(t)))||(null==a||a(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f);return function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const n=hT(e);t.useEffect((()=>{const e=e=>{"Escape"===e.key&&n(e)};return r.addEventListener("keydown",e),()=>r.removeEventListener("keydown",e)}),[n,r])}((e=>{w===u.layers.size-1&&(null==s||s(e),!e.defaultPrevented&&d&&(e.preventDefault(),d()))}),f),t.useEffect((()=>{if(p)return i&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(vT=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(p)),u.layers.add(p),wT(),()=>{i&&1===u.layersWithOutsidePointerEventsDisabled.size&&(f.body.style.pointerEvents=vT)}}),[p,f,i,u]),t.useEffect((()=>()=>{p&&(u.layers.delete(p),u.layersWithOutsidePointerEventsDisabled.delete(p),wT())}),[p,u]),t.useEffect((()=>{const e=()=>m({});return document.addEventListener(fT,e),()=>document.removeEventListener(fT,e)}),[]),t.createElement(pT.div,tT({},l,{ref:g,style:{pointerEvents:_?S?"auto":"none":void 0,...e.style},onFocusCapture:rT(e.onFocusCapture,R.onFocusCapture),onBlurCapture:rT(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:rT(e.onPointerDownCapture,C.onPointerDownCapture)}))}));function wT(){const e=new CustomEvent(fT);document.dispatchEvent(e)}function _T(e,t,n,{discrete:i}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),i?function(e,t){e&&r.flushSync((()=>e.dispatchEvent(t)))}(s,o):s.dispatchEvent(o)}let ST=0;function CT(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}const RT="focusScope.autoFocusOnMount",TT="focusScope.autoFocusOnUnmount",kT={bubbles:!1,cancelable:!0},PT=t.forwardRef(((e,r)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[c,d]=t.useState(null),l=hT(s),u=hT(o),p=t.useRef(null),h=iT(r,(e=>d(e))),f=t.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;t.useEffect((()=>{if(i){function e(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:DT(p.current,{select:!0})}function t(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||DT(p.current,{select:!0}))}function r(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&DT(c)}document.addEventListener("focusin",e),document.addEventListener("focusout",t);const n=new MutationObserver(r);return c&&n.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),n.disconnect()}}}),[i,c,f.paused]),t.useEffect((()=>{if(c){xT.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(RT,kT);c.addEventListener(RT,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const n of e)if(DT(n,{select:t}),document.activeElement!==r)return}((e=ET(c),e.filter((e=>"A"!==e.tagName))),{select:!0}),document.activeElement===t&&DT(c))}return()=>{c.removeEventListener(RT,l),setTimeout((()=>{const e=new CustomEvent(TT,kT);c.addEventListener(TT,u),c.dispatchEvent(e),e.defaultPrevented||DT(null!=t?t:document.body,{select:!0}),c.removeEventListener(TT,u),xT.remove(f)}),0)}}var e}),[c,l,u,f]);const m=t.useCallback((e=>{if(!n&&!i)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,r=document.activeElement;if(t&&r){const t=e.currentTarget,[i,s]=function(e){const t=ET(e),r=OT(t,e),n=OT(t.reverse(),e);return[r,n]}(t);i&&s?e.shiftKey||r!==s?e.shiftKey&&r===i&&(e.preventDefault(),n&&DT(s,{select:!0})):(e.preventDefault(),n&&DT(i,{select:!0})):r===t&&e.preventDefault()}}),[n,i,f.paused]);return t.createElement(pT.div,tT({tabIndex:-1},a,{ref:h,onKeyDown:m}))}));function ET(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 OT(e,t){for(const r of e)if(!IT(r,{upTo:t}))return r}function IT(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 DT(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()}}const xT=function(){let e=[];return{add(t){const r=e[0];t!==r&&(null==r||r.pause()),e=MT(e,t),e.unshift(t)},remove(t){var r;e=MT(e,t),null===(r=e[0])||void 0===r||r.resume()}}}();function MT(e,t){const r=[...e],n=r.indexOf(t);return-1!==n&&r.splice(n,1),r}const jT=Boolean(null===globalThis||void 0===globalThis?void 0:globalThis.document)?t.useLayoutEffect:()=>{},LT=s["useId".toString()]||(()=>{});let AT=0;function NT(e){const[t,r]=s.useState(LT());return jT((()=>{e||r((e=>null!=e?e:String(AT++)))}),[e]),e||(t?`radix-${t}`:"")}const BT=["top","right","bottom","left"],FT=Math.min,zT=Math.max,VT=Math.round,UT=Math.floor,$T=e=>({x:e,y:e}),GT={left:"right",right:"left",bottom:"top",top:"bottom"},qT={start:"end",end:"start"};function HT(e,t,r){return zT(e,FT(t,r))}function WT(e,t){return"function"==typeof e?e(t):e}function KT(e){return e.split("-")[0]}function JT(e){return e.split("-")[1]}function QT(e){return"x"===e?"y":"x"}function XT(e){return"y"===e?"height":"width"}function YT(e){return["top","bottom"].includes(KT(e))?"y":"x"}function ZT(e){return QT(YT(e))}function ek(e){return e.replace(/start|end/g,(e=>qT[e]))}function tk(e){return e.replace(/left|right|bottom|top/g,(e=>GT[e]))}function rk(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 nk(e){const{x:t,y:r,width:n,height:i}=e;return{width:n,height:i,top:r,left:t,right:t+n,bottom:r+i,x:t,y:r}}function ik(e,t,r){let{reference:n,floating:i}=e;const s=YT(t),o=ZT(t),a=XT(o),c=KT(t),d="y"===s,l=n.x+n.width/2-i.width/2,u=n.y+n.height/2-i.height/2,p=n[a]/2-i[a]/2;let h;switch(c){case"top":h={x:l,y:n.y-i.height};break;case"bottom":h={x:l,y:n.y+n.height};break;case"right":h={x:n.x+n.width,y:u};break;case"left":h={x:n.x-i.width,y:u};break;default:h={x:n.x,y:n.y}}switch(JT(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function sk(e,t){var r;void 0===t&&(t={});const{x:n,y:i,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=WT(t,e),f=rk(h),m=a[p?"floating"===u?"reference":"floating":u],g=nk(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:n,y:i,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=nk(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 ok(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function ak(e){return BT.some((t=>e[t]>=0))}function ck(e){return uk(e)?(e.nodeName||"").toLowerCase():"#document"}function dk(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function lk(e){var t;return null==(t=(uk(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function uk(e){return e instanceof Node||e instanceof dk(e).Node}function pk(e){return e instanceof Element||e instanceof dk(e).Element}function hk(e){return e instanceof HTMLElement||e instanceof dk(e).HTMLElement}function fk(e){return"undefined"!=typeof ShadowRoot&&(e instanceof ShadowRoot||e instanceof dk(e).ShadowRoot)}function mk(e){const{overflow:t,overflowX:r,overflowY:n,display:i}=wk(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&!["inline","contents"].includes(i)}function gk(e){return["table","td","th"].includes(ck(e))}function vk(e){const t=bk(),r=wk(e);return"none"!==r.transform||"none"!==r.perspective||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||["transform","perspective","filter"].some((e=>(r.willChange||"").includes(e)))||["paint","layout","strict","content"].some((e=>(r.contain||"").includes(e)))}function bk(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function yk(e){return["html","body","#document"].includes(ck(e))}function wk(e){return dk(e).getComputedStyle(e)}function _k(e){return pk(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Sk(e){if("html"===ck(e))return e;const t=e.assignedSlot||e.parentNode||fk(e)&&e.host||lk(e);return fk(t)?t.host:t}function Ck(e){const t=Sk(e);return yk(t)?e.ownerDocument?e.ownerDocument.body:e.body:hk(t)&&mk(t)?t:Ck(t)}function Rk(e,t,r){var n;void 0===t&&(t=[]),void 0===r&&(r=!0);const i=Ck(e),s=i===(null==(n=e.ownerDocument)?void 0:n.body),o=dk(i);return s?t.concat(o,o.visualViewport||[],mk(i)?i:[],o.frameElement&&r?Rk(o.frameElement):[]):t.concat(i,Rk(i,[],r))}function Tk(e){const t=wk(e);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const i=hk(e),s=i?e.offsetWidth:r,o=i?e.offsetHeight:n,a=VT(r)!==s||VT(n)!==o;return a&&(r=s,n=o),{width:r,height:n,$:a}}function kk(e){return pk(e)?e:e.contextElement}function Pk(e){const t=kk(e);if(!hk(t))return $T(1);const r=t.getBoundingClientRect(),{width:n,height:i,$:s}=Tk(t);let o=(s?VT(r.width):r.width)/n,a=(s?VT(r.height):r.height)/i;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const Ek=$T(0);function Ok(e){const t=dk(e);return bk()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:Ek}function Ik(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=!1);const i=e.getBoundingClientRect(),s=kk(e);let o=$T(1);t&&(n?pk(n)&&(o=Pk(n)):o=Pk(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==dk(e))&&t}(s,r,n)?Ok(s):$T(0);let c=(i.left+a.x)/o.x,d=(i.top+a.y)/o.y,l=i.width/o.x,u=i.height/o.y;if(s){const e=dk(s),t=n&&pk(n)?dk(n):n;let r=e,i=r.frameElement;for(;i&&n&&t!==r;){const e=Pk(i),t=i.getBoundingClientRect(),n=wk(i),s=t.left+(i.clientLeft+parseFloat(n.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(n.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=dk(i),i=r.frameElement}}return nk({width:l,height:u,x:c,y:d})}const Dk=[":popover-open",":modal"];function xk(e){return Dk.some((t=>{try{return e.matches(t)}catch(e){return!1}}))}function Mk(e){return Ik(lk(e)).left+_k(e).scrollLeft}function jk(e,t,r){let n;if("viewport"===t)n=function(e,t){const r=dk(e),n=lk(e),i=r.visualViewport;let s=n.clientWidth,o=n.clientHeight,a=0,c=0;if(i){s=i.width,o=i.height;const e=bk();(!e||e&&"fixed"===t)&&(a=i.offsetLeft,c=i.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)n=function(e){const t=lk(e),r=_k(e),n=e.ownerDocument.body,i=zT(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),s=zT(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let o=-r.scrollLeft+Mk(e);const a=-r.scrollTop;return"rtl"===wk(n).direction&&(o+=zT(t.clientWidth,n.clientWidth)-i),{width:i,height:s,x:o,y:a}}(lk(e));else if(pk(t))n=function(e,t){const r=Ik(e,!0,"fixed"===t),n=r.top+e.clientTop,i=r.left+e.clientLeft,s=hk(e)?Pk(e):$T(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:i*s.x,y:n*s.y}}(t,r);else{const r=Ok(e);n={...t,x:t.x-r.x,y:t.y-r.y}}return nk(n)}function Lk(e,t){const r=Sk(e);return!(r===t||!pk(r)||yk(r))&&("fixed"===wk(r).position||Lk(r,t))}function Ak(e,t,r){const n=hk(t),i=lk(t),s="fixed"===r,o=Ik(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=$T(0);if(n||!n&&!s)if(("body"!==ck(t)||mk(i))&&(a=_k(t)),n){const e=Ik(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else i&&(c.x=Mk(i));return{x:o.left+a.scrollLeft-c.x,y:o.top+a.scrollTop-c.y,width:o.width,height:o.height}}function Nk(e){return"static"===wk(e).position}function Bk(e,t){return hk(e)&&"fixed"!==wk(e).position?t?t(e):e.offsetParent:null}function Fk(e,t){const r=dk(e);if(xk(e))return r;if(!hk(e)){let t=Sk(e);for(;t&&!yk(t);){if(pk(t)&&!Nk(t))return t;t=Sk(t)}return r}let n=Bk(e,t);for(;n&&gk(n)&&Nk(n);)n=Bk(n,t);return n&&yk(n)&&Nk(n)&&!vk(n)?r:n||function(e){let t=Sk(e);for(;hk(t)&&!yk(t);){if(vk(t))return t;t=Sk(t)}return null}(e)||r}const zk={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:n,strategy:i}=e;const s="fixed"===i,o=lk(n),a=!!t&&xk(t.floating);if(n===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=$T(1);const l=$T(0),u=hk(n);if((u||!u&&!s)&&(("body"!==ck(n)||mk(o))&&(c=_k(n)),hk(n))){const e=Ik(n);d=Pk(n),l.x=e.x+n.clientLeft,l.y=e.y+n.clientTop}return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x,y:r.y*d.y-c.scrollTop*d.y+l.y}},getDocumentElement:lk,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:n,strategy:i}=e;const s="clippingAncestors"===r?xk(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let n=Rk(e,[],!1).filter((e=>pk(e)&&"body"!==ck(e))),i=null;const s="fixed"===wk(e).position;let o=s?Sk(e):e;for(;pk(o)&&!yk(o);){const t=wk(o),r=vk(o);r||"fixed"!==t.position||(i=null),(s?!r&&!i:!r&&"static"===t.position&&i&&["absolute","fixed"].includes(i.position)||mk(o)&&!r&&Lk(e,o))?n=n.filter((e=>e!==o)):i=t,o=Sk(o)}return t.set(e,n),n}(t,this._c):[].concat(r),o=[...s,n],a=o[0],c=o.reduce(((e,r)=>{const n=jk(t,r,i);return e.top=zT(n.top,e.top),e.right=FT(n.right,e.right),e.bottom=FT(n.bottom,e.bottom),e.left=zT(n.left,e.left),e}),jk(t,a,i));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:Fk,getElementRects:async function(e){const t=this.getOffsetParent||Fk,r=this.getDimensions,n=await r(e.floating);return{reference:Ak(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=Tk(e);return{width:t,height:r}},getScale:Pk,isElement:pk,isRTL:function(e){return"rtl"===wk(e).direction}};function Vk(e,t,r,n){void 0===n&&(n={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=n,d=kk(e),l=i||s?[...d?Rk(d):[],...Rk(t)]:[];l.forEach((e=>{i&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)}));const u=d&&a?function(e,t){let r,n=null;const i=lk(e);function s(){var e;clearTimeout(r),null==(e=n)||e.disconnect(),n=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const{left:d,top:l,width:u,height:p}=e.getBoundingClientRect();if(a||t(),!u||!p)return;const h={rootMargin:-UT(l)+"px "+-UT(i.clientWidth-(d+u))+"px "+-UT(i.clientHeight-(l+p))+"px "+-UT(d)+"px",threshold:zT(0,FT(1,c))||1};let f=!0;function m(e){const t=e[0].intersectionRatio;if(t!==c){if(!f)return o();t?o(!1,t):r=setTimeout((()=>{o(!1,1e-7)}),1e3)}f=!1}try{n=new IntersectionObserver(m,{...h,root:i.ownerDocument})}catch(e){n=new IntersectionObserver(m,h)}n.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver((e=>{let[n]=e;n&&n.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?Ik(e):null;return c&&function t(){const n=Ik(e);!m||n.x===m.x&&n.y===m.y&&n.width===m.width&&n.height===m.height||r();m=n,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach((e=>{i&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)})),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const Uk=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,n;const{x:i,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:n,elements:i}=e,s=await(null==n.isRTL?void 0:n.isRTL(i.floating)),o=KT(r),a=JT(r),c="y"===YT(r),d=["left","top"].includes(o)?-1:1,l=s&&c?-1:1,u=WT(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...u};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!=(n=a.arrow)&&n.alignmentOffset?{}:{x:i+c.x,y:s+c.y,data:{...c,placement:o}}}}},$k=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:n,placement:i}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=WT(e,t),d={x:r,y:n},l=await sk(t,c),u=YT(KT(i)),p=QT(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=HT(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=HT(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-n}}}}},Gk=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,n;const{placement:i,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}=WT(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=KT(i),b=KT(a)===a,y=await(null==c.isRTL?void 0:c.isRTL(d.floating)),w=p||(b||!m?[tk(a)]:function(e){const t=tk(e);return[ek(e),t,ek(t)]}(a));p||"none"===f||w.push(...function(e,t,r,n){const i=JT(e);let s=function(e,t,r){const n=["left","right"],i=["right","left"],s=["top","bottom"],o=["bottom","top"];switch(e){case"top":case"bottom":return r?t?i:n:t?n:i;case"left":case"right":return t?s:o;default:return[]}}(KT(e),"start"===r,n);return i&&(s=s.map((e=>e+"-"+i)),t&&(s=s.concat(s.map(ek)))),s}(a,m,f,y));const _=[a,...w],S=await sk(t,g),C=[];let R=(null==(n=s.flip)?void 0:n.overflows)||[];if(l&&C.push(S[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const n=JT(e),i=ZT(e),s=XT(i);let o="x"===i?n===(r?"end":"start")?"right":"left":"start"===n?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=tk(o)),[o,tk(o)]}(i,o,y);C.push(S[e[0]],S[e[1]])}if(R=[...R,{placement:i,overflows:C}],!C.every((e=>e<=0))){var T,k;const e=((null==(T=s.flip)?void 0:T.index)||0)+1,t=_[e];if(t)return{data:{index:e,overflows:R},reset:{placement:t}};let r=null==(k=R.filter((e=>e.overflows[0]<=0)).sort(((e,t)=>e.overflows[1]-t.overflows[1]))[0])?void 0:k.placement;if(!r)switch(h){case"bestFit":{var P;const e=null==(P=R.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:P[0];e&&(r=e);break}case"initialPlacement":r=a}if(i!==r)return{reset:{placement:r}}}return{}}}},qk=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){const{placement:r,rects:n,platform:i,elements:s}=t,{apply:o=(()=>{}),...a}=WT(e,t),c=await sk(t,a),d=KT(r),l=JT(r),u="y"===YT(r),{width:p,height:h}=n.floating;let f,m;"top"===d||"bottom"===d?(f=d,m=l===(await(null==i.isRTL?void 0:i.isRTL(s.floating))?"start":"end")?"left":"right"):(m=d,f="end"===l?"top":"bottom");const g=h-c.top-c.bottom,v=p-c.left-c.right,b=FT(h-c[f],g),y=FT(p-c[m],v),w=!t.middlewareData.shift;let _=b,S=y;if(u?S=l||w?FT(y,v):v:_=l||w?FT(b,g):g,w&&!l){const e=zT(c.left,0),t=zT(c.right,0),r=zT(c.top,0),n=zT(c.bottom,0);u?S=p-2*(0!==e||0!==t?e+t:zT(c.left,c.right)):_=h-2*(0!==r||0!==n?r+n:zT(c.top,c.bottom))}await o({...t,availableWidth:S,availableHeight:_});const C=await i.getDimensions(s.floating);return p!==C.width||h!==C.height?{reset:{rects:!0}}:{}}}},Hk=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:n="referenceHidden",...i}=WT(e,t);switch(n){case"referenceHidden":{const e=ok(await sk(t,{...i,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:ak(e)}}}case"escaped":{const e=ok(await sk(t,{...i,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:ak(e)}}}default:return{}}}}},Wk=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:n,placement:i,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=WT(e,t)||{};if(null==d)return{};const u=rk(l),p={x:r,y:n},h=ZT(i),f=XT(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,T=C/2-m[f]/2-1,k=FT(u[v],T),P=FT(u[b],T),E=k,O=C-m[f]-P,I=C/2-m[f]/2+R,D=HT(E,I,O),x=!c.arrow&&null!=JT(i)&&I!==D&&s.reference[f]/2-(I<E?k:P)-m[f]/2<0,M=x?I<E?I-E:I-O:0;return{[h]:p[h]+M,data:{[h]:D,centerOffset:I-D-M,...x&&{alignmentOffset:M}},reset:x}}}),Kk=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:n,placement:i,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=WT(e,t),l={x:r,y:n},u=YT(i),p=QT(u);let h=l[p],f=l[u];const m=WT(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=["top","left"].includes(KT(i)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),n=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>n&&(f=n)}return{[p]:h,[u]:f}}}},Jk=(e,t,r)=>{const n=new Map,i={platform:zk,...r},s={...i.platform,_c:n};return(async(e,t,r)=>{const{placement:n="bottom",strategy:i="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:i}),{x:l,y:u}=ik(d,n,c),p=n,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:n,placement:p,strategy:i,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:i}):y.rects),({x:l,y:u}=ik(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:i,middlewareData:h}})(e,t,{...i,platform:s})};var Qk="undefined"!=typeof document?t.useLayoutEffect:t.useEffect;function Xk(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,n,i;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;0!=n--;)if(!Xk(e[n],t[n]))return!1;return!0}if(i=Object.keys(e),r=i.length,r!==Object.keys(t).length)return!1;for(n=r;0!=n--;)if(!{}.hasOwnProperty.call(t,i[n]))return!1;for(n=r;0!=n--;){const r=i[n];if(("_owner"!==r||!e.$$typeof)&&!Xk(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function Yk(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Zk(e,t){const r=Yk(e);return Math.round(t*r)/r}function eP(e){const t=s.useRef(e);return Qk((()=>{t.current=e})),t}const tP=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:n}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?Wk({element:r.current,padding:n}).fn(t):{}:r?Wk({element:r,padding:n}).fn(t):{}}}),rP=(e,t)=>({...Uk(e),options:[e,t]}),nP=(e,t)=>({...$k(e),options:[e,t]}),iP=(e,t)=>({...Kk(e),options:[e,t]}),sP=(e,t)=>({...Gk(e),options:[e,t]}),oP=(e,t)=>({...qk(e),options:[e,t]}),aP=(e,t)=>({...Hk(e),options:[e,t]}),cP=(e,t)=>({...tP(e),options:[e,t]});const dP="Popper",[lP,uP]=sT(dP),[pP,hP]=lP(dP),fP=t.forwardRef(((e,r)=>{const{__scopePopper:n,virtualRef:i,...s}=e,o=hP("PopperAnchor",n),a=t.useRef(null),c=iT(r,a);return t.useEffect((()=>{o.onAnchorChange((null==i?void 0:i.current)||a.current)})),i?null:t.createElement(pT.div,tT({},s,{ref:c}))})),mP="PopperContent",[gP,vP]=lP(mP),bP=t.forwardRef(((e,r)=>{var n,i,a,c,d,l,u,p;const{__scopePopper:h,side:f="bottom",sideOffset:m=0,align:g="center",alignOffset:v=0,arrowPadding:b=0,avoidCollisions:y=!0,collisionBoundary:w=[],collisionPadding:_=0,sticky:S="partial",hideWhenDetached:C=!1,updatePositionStrategy:R="optimized",onPlaced:T,...k}=e,P=hP(mP,h),[E,O]=t.useState(null),I=iT(r,(e=>O(e))),[D,x]=t.useState(null),M=function(e){const[r,n]=t.useState(void 0);return jT((()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver((t=>{if(!Array.isArray(t))return;if(!t.length)return;const r=t[0];let i,s;if("borderBoxSize"in r){const e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,s=t.blockSize}else i=e.offsetWidth,s=e.offsetHeight;n({width:i,height:s})}));return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}n(void 0)}),[e]),r}(D),j=null!==(n=null==M?void 0:M.width)&&void 0!==n?n:0,L=null!==(i=null==M?void 0:M.height)&&void 0!==i?i:0,A=f+("center"!==g?"-"+g:""),N="number"==typeof _?_:{top:0,right:0,bottom:0,left:0,..._},B=Array.isArray(w)?w:[w],F=B.length>0,z={padding:N,boundary:B.filter(yP),altBoundary:F},{refs:V,floatingStyles:U,placement:$,isPositioned:G,middlewareData:q}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:i,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(n);Xk(f,n)||m(n);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!==T.current&&(T.current=e,y(e))}),[]),S=a||g,C=c||b,R=s.useRef(null),T=s.useRef(null),k=s.useRef(p),P=null!=l,E=eP(l),O=eP(i),I=s.useCallback((()=>{if(!R.current||!T.current)return;const e={placement:t,strategy:r,middleware:f};O.current&&(e.platform=O.current),Jk(R.current,T.current,e).then((e=>{const t={...e,isPositioned:!0};D.current&&!Xk(k.current,t)&&(k.current=t,o.flushSync((()=>{h(t)})))}))}),[f,t,r,O]);Qk((()=>{!1===u&&k.current.isPositioned&&(k.current.isPositioned=!1,h((e=>({...e,isPositioned:!1}))))}),[u]);const D=s.useRef(!1);Qk((()=>(D.current=!0,()=>{D.current=!1})),[]),Qk((()=>{if(S&&(R.current=S),C&&(T.current=C),S&&C){if(E.current)return E.current(S,C,I);I()}}),[S,C,I,E,P]);const x=s.useMemo((()=>({reference:R,floating:T,setReference:w,setFloating:_})),[w,_]),M=s.useMemo((()=>({reference:S,floating:C})),[S,C]),j=s.useMemo((()=>{const e={position:r,left:0,top:0};if(!M.floating)return e;const t=Zk(M.floating,p.x),n=Zk(M.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+n+"px)",...Yk(M.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:n}}),[r,d,M.floating,p.x,p.y]);return s.useMemo((()=>({...p,update:I,refs:x,elements:M,floatingStyles:j})),[p,I,x,M,j])}({strategy:"fixed",placement:A,whileElementsMounted:(...e)=>Vk(...e,{animationFrame:"always"===R}),elements:{reference:P.anchor},middleware:[rP({mainAxis:m+L,alignmentAxis:v}),y&&nP({mainAxis:!0,crossAxis:!1,limiter:"partial"===S?iP():void 0,...z}),y&&sP({...z}),oP({...z,apply:({elements:e,rects:t,availableWidth:r,availableHeight:n})=>{const{width:i,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${n}px`),o.setProperty("--radix-popper-anchor-width",`${i}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),D&&cP({element:D,padding:b}),wP({arrowWidth:j,arrowHeight:L}),C&&aP({strategy:"referenceHidden",...z})]}),[H,W]=_P($),K=hT(T);jT((()=>{G&&(null==K||K())}),[G,K]);const J=null===(a=q.arrow)||void 0===a?void 0:a.x,Q=null===(c=q.arrow)||void 0===c?void 0:c.y,X=0!==(null===(d=q.arrow)||void 0===d?void 0:d.centerOffset),[Y,Z]=t.useState();return jT((()=>{E&&Z(window.getComputedStyle(E).zIndex)}),[E]),t.createElement("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:G?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[null===(l=q.transformOrigin)||void 0===l?void 0:l.x,null===(u=q.transformOrigin)||void 0===u?void 0:u.y].join(" ")},dir:e.dir},t.createElement(gP,{scope:h,placedSide:H,onArrowChange:x,arrowX:J,arrowY:Q,shouldHideArrow:X},t.createElement(pT.div,tT({"data-side":H,"data-align":W},k,{ref:I,style:{...k.style,animation:G?void 0:"none",opacity:null!==(p=q.hide)&&void 0!==p&&p.referenceHidden?0:void 0}}))))}));function yP(e){return null!==e}const wP=e=>({name:"transformOrigin",options:e,fn(t){var r,n,i,s,o;const{placement:a,rects:c,middlewareData:d}=t,l=0!==(null===(r=d.arrow)||void 0===r?void 0:r.centerOffset),u=l?0:e.arrowWidth,p=l?0:e.arrowHeight,[h,f]=_P(a),m={start:"0%",center:"50%",end:"100%"}[f],g=(null!==(n=null===(i=d.arrow)||void 0===i?void 0:i.x)&&void 0!==n?n:0)+u/2,v=(null!==(s=null===(o=d.arrow)||void 0===o?void 0:o.y)&&void 0!==s?s:0)+p/2;let b="",y="";return"bottom"===h?(b=l?m:`${g}px`,y=-p+"px"):"top"===h?(b=l?m:`${g}px`,y=`${c.floating.height+p}px`):"right"===h?(b=-p+"px",y=l?m:`${v}px`):"left"===h&&(b=`${c.floating.width+p}px`,y=l?m:`${v}px`),{data:{x:b,y:y}}}});function _P(e){const[t,r="center"]=e.split("-");return[t,r]}const SP=e=>{const{__scopePopper:r,children:n}=e,[i,s]=t.useState(null);return t.createElement(pP,{scope:r,anchor:i,onAnchorChange:s},n)},CP=fP,RP=bP,TP=t.forwardRef(((e,n)=>{var i;const{container:s=(null===globalThis||void 0===globalThis||null===(i=globalThis.document)||void 0===i?void 0:i.body),...o}=e;return s?r.createPortal(t.createElement(pT.div,tT({},o,{ref:n})),s):null}));const kP=e=>{const{present:n,children:i}=e,s=function(e){const[n,i]=t.useState(),s=t.useRef({}),o=t.useRef(e),a=t.useRef("none"),c=e?"mounted":"unmounted",[d,l]=function(e,r){return t.useReducer(((e,t)=>{const n=r[e][t];return null!=n?n:e}),e)}(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return t.useEffect((()=>{const e=PP(s.current);a.current="mounted"===d?e:"none"}),[d]),jT((()=>{const t=s.current,r=o.current;if(r!==e){const n=a.current,i=PP(t);if(e)l("MOUNT");else if("none"===i||"none"===(null==t?void 0:t.display))l("UNMOUNT");else{l(r&&n!==i?"ANIMATION_OUT":"UNMOUNT")}o.current=e}}),[e,l]),jT((()=>{if(n){const e=e=>{const t=PP(s.current).includes(e.animationName);e.target===n&&t&&r.flushSync((()=>l("ANIMATION_END")))},t=e=>{e.target===n&&(a.current=PP(s.current))};return n.addEventListener("animationstart",t),n.addEventListener("animationcancel",e),n.addEventListener("animationend",e),()=>{n.removeEventListener("animationstart",t),n.removeEventListener("animationcancel",e),n.removeEventListener("animationend",e)}}l("ANIMATION_END")}),[n,l]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:t.useCallback((e=>{e&&(s.current=getComputedStyle(e)),i(e)}),[])}}(n),o="function"==typeof i?i({present:s.isPresent}):t.Children.only(i),a=iT(s.ref,o.ref);return"function"==typeof i||s.isPresent?t.cloneElement(o,{ref:a}):null};function PP(e){return(null==e?void 0:e.animationName)||"none"}function EP({prop:e,defaultProp:r,onChange:n=(()=>{})}){const[i,s]=function({defaultProp:e,onChange:r}){const n=t.useState(e),[i]=n,s=t.useRef(i),o=hT(r);return t.useEffect((()=>{s.current!==i&&(o(i),s.current=i)}),[i,s,o]),n}({defaultProp:r,onChange:n}),o=void 0!==e,a=o?e:i,c=hT(n),d=t.useCallback((t=>{if(o){const r="function"==typeof t?t(e):t;r!==e&&c(r)}else s(t)}),[o,e,s,c]);return[a,d]}kP.displayName="Presence";var OP=new WeakMap,IP=new WeakMap,DP={},xP=0,MP=function(e){return e&&(e.host||MP(e.parentNode))},jP=function(e,t,r,n){var i=function(e,t){return t.map((function(t){if(e.contains(t))return t;var r=MP(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]);DP[r]||(DP[r]=new WeakMap);var s=DP[r],o=[],a=new Set,c=new Set(i),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};i.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(n),i=null!==t&&"false"!==t,c=(OP.get(e)||0)+1,d=(s.get(e)||0)+1;OP.set(e,c),s.set(e,d),o.push(e),1===c&&i&&IP.set(e,!0),1===d&&e.setAttribute(r,"true"),i||e.setAttribute(n,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}}))};return l(t),a.clear(),xP++,function(){o.forEach((function(e){var t=OP.get(e)-1,i=s.get(e)-1;OP.set(e,t),s.set(e,i),t||(IP.has(e)||e.removeAttribute(n),IP.delete(e)),i||e.removeAttribute(r)})),--xP||(OP=new WeakMap,OP=new WeakMap,IP=new WeakMap,DP={})}},LP=function(e,t,r){void 0===r&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),i=t||function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live]"))),jP(n,i,r,"aria-hidden")):function(){return null}},AP="right-scroll-bar-position",NP="width-before-scroll-bar";function BP(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var FP=new WeakMap;function zP(e,r){var n,i,o,a=(n=r||null,i=function(t){return e.forEach((function(e){return BP(e,t)}))},o=t.useState((function(){return{value:n,callback:i,facade:{get current(){return o.value},set current(e){var t=o.value;t!==e&&(o.value=e,o.callback(e,t))}}}}))[0],o.callback=i,o.facade);return s.useLayoutEffect((function(){var t=FP.get(a);if(t){var r=new Set(t),n=new Set(e),i=a.current;r.forEach((function(e){n.has(e)||BP(e,null)})),n.forEach((function(e){r.has(e)||BP(e,i)}))}FP.set(a,e)}),[e]),a}function VP(e){return e}var UP=function(e){var t=e.sideCar,r=kC(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return s.createElement(n,TC({},r))};UP.isSideCarExport=!0;var $P=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=VP);var r=[],n=!1;return{read:function(){if(n)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 i=t(e,n);return r.push(i),function(){r=r.filter((function(e){return e!==i}))}},assignSyncMedium:function(e){for(n=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){n=!0;var t=[];if(r.length){var i=r;r=[],i.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=TC({async:!0,ssr:!1},e),t}(),GP=function(){},qP=s.forwardRef((function(e,t){var r=s.useRef(null),n=s.useState({onScrollCapture:GP,onWheelCapture:GP,onTouchMoveCapture:GP}),i=n[0],o=n[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noIsolation,m=e.inert,g=e.allowPinchZoom,v=e.as,b=void 0===v?"div":v,y=kC(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as"]),w=h,_=zP([r,t]),S=TC(TC({},y),i);return s.createElement(s.Fragment,null,u&&s.createElement(w,{sideCar:$P,removeScrollBar:l,shards:p,noIsolation:f,inert:m,setCallbacks:o,allowPinchZoom:!!g,lockRef:r}),a?s.cloneElement(s.Children.only(c),TC(TC({},S),{ref:_})):s.createElement(b,TC({},S,{className:d,ref:_}),c))}));qP.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},qP.classNames={fullWidth:NP,zeroRight:AP};function HP(){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 WP=function(){var e=0,t=null;return{add:function(r){var n,i;0==e&&(t=HP())&&(i=r,(n=t).styleSheet?n.styleSheet.cssText=i:n.appendChild(document.createTextNode(i)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},KP=function(){var e,t=(e=WP(),function(t,r){s.useEffect((function(){return e.add(t),function(){e.remove()}}),[t&&r])});return function(e){var r=e.styles,n=e.dynamic;return t(r,n),null}},JP={left:0,top:0,right:0,gap:0},QP=function(e){return parseInt(e||"",10)||0},XP=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return JP;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],n=t["padding"===e?"paddingTop":"marginTop"],i=t["padding"===e?"paddingRight":"marginRight"];return[QP(r),QP(n),QP(i)]}(e),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},YP=KP(),ZP="data-scroll-locked",eE=function(e,t,r,n){var i=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(n,";\n padding-right: ").concat(a,"px ").concat(n,";\n }\n body[").concat(ZP,"] {\n overflow: hidden ").concat(n,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(n,";"),"margin"===r&&"\n padding-left: ".concat(i,"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(n,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),"\n }\n \n .").concat(AP," {\n right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(NP," {\n margin-right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(AP," .").concat(AP," {\n right: 0 ").concat(n,";\n }\n \n .").concat(NP," .").concat(NP," {\n margin-right: 0 ").concat(n,";\n }\n \n body[").concat(ZP,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},tE=function(){var e=parseInt(document.body.getAttribute(ZP)||"0",10);return isFinite(e)?e:0},rE=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,i=void 0===n?"margin":n;s.useEffect((function(){return document.body.setAttribute(ZP,(tE()+1).toString()),function(){var e=tE()-1;e<=0?document.body.removeAttribute(ZP):document.body.setAttribute(ZP,e.toString())}}),[]);var o=s.useMemo((function(){return XP(i)}),[i]);return s.createElement(YP,{styles:eE(o,!t,i,r?"":"!important")})},nE=!1;if("undefined"!=typeof window)try{var iE=Object.defineProperty({},"passive",{get:function(){return nE=!0,!0}});window.addEventListener("test",iE,iE),window.removeEventListener("test",iE,iE)}catch(lO){nE=!1}var sE=!!nE&&{passive:!1},oE=function(e,t){var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},aE=function(e,t){var r=t;do{if("undefined"!=typeof ShadowRoot&&r instanceof ShadowRoot&&(r=r.host),cE(e,r)){var n=dE(e,r);if(n[1]>n[2])return!0}r=r.parentNode}while(r&&r!==document.body);return!1},cE=function(e,t){return"v"===e?function(e){return oE(e,"overflowY")}(t):function(e){return oE(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)},lE=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},uE=function(e){return[e.deltaX,e.deltaY]},pE=function(e){return e&&"current"in e?e.current:e},hE=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},fE=0,mE=[];var gE,vE=(gE=function(e){var t=s.useRef([]),r=s.useRef([0,0]),n=s.useRef(),i=s.useState(fE++)[0],o=s.useState((function(){return KP()}))[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(i));var t=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(pE),!0).filter(Boolean);return t.forEach((function(e){return e.classList.add("allow-interactivity-".concat(i))})),function(){document.body.classList.remove("block-interactivity-".concat(i)),t.forEach((function(e){return e.classList.remove("allow-interactivity-".concat(i))}))}}}),[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback((function(e,t){if("touches"in e&&2===e.touches.length)return!a.current.allowPinchZoom;var i,s=lE(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=aE(u,l);if(!p)return!0;if(p?i=u:(i="v"===u?"h":"v",p=aE(u,l)),!p)return!1;if(!n.current&&"changedTouches"in e&&(c||d)&&(n.current=i),!i)return!0;var h=n.current||i;return function(e,t,r,n,i){var s=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),o=s*n,a=r.target,c=t.contains(a),d=!1,l=o>0,u=0,p=0;do{var h=dE(e,a),f=h[0],m=h[1]-h[2]-s*f;(f||m)&&cE(e,a)&&(u+=m,p+=f),a=a.parentNode}while(!c&&a!==document.body||c&&(t.contains(a)||t===a));return(l&&(i&&0===u||!i&&o>u)||!l&&(i&&0===p||!i&&-o>p))&&(d=!0),d}(h,t,e,"h"===h?c:d,!0)}),[]),d=s.useCallback((function(e){var r=e;if(mE.length&&mE[mE.length-1]===o){var n="deltaY"in r?uE(r):lE(r),i=t.current.filter((function(e){return e.name===r.type&&e.target===r.target&&(t=e.delta,i=n,t[0]===i[0]&&t[1]===i[1]);var t,i}))[0];if(i&&i.should)r.cancelable&&r.preventDefault();else if(!i){var s=(a.current.shards||[]).map(pE).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,n,i){var s={name:e,delta:r,target:n,should: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=lE(e),n.current=void 0}),[]),p=s.useCallback((function(t){l(t.type,uE(t),t.target,c(t,e.lockRef.current))}),[]),h=s.useCallback((function(t){l(t.type,lE(t),t.target,c(t,e.lockRef.current))}),[]);s.useEffect((function(){return mE.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,sE),document.addEventListener("touchmove",d,sE),document.addEventListener("touchstart",u,sE),function(){mE=mE.filter((function(e){return e!==o})),document.removeEventListener("wheel",d,sE),document.removeEventListener("touchmove",d,sE),document.removeEventListener("touchstart",u,sE)}}),[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:hE(i)}):null,f?s.createElement(rE,{gapMode:"margin"}):null)},$P.useMedium(gE),UP),bE=s.forwardRef((function(e,t){return s.createElement(qP,TC({},e,{ref:t,sideCar:vE}))}));bE.classNames=qP.classNames;var yE=bE;const wE="Popover",[_E,SE]=sT(wE,[uP]),CE=uP(),[RE,TE]=_E(wE),kE=t.forwardRef(((e,r)=>{const{__scopePopover:n,...i}=e,s=TE("PopoverTrigger",n),o=CE(n),a=iT(r,s.triggerRef),c=t.createElement(pT.button,tT({type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":LE(s.open)},i,{ref:a,onClick:rT(e.onClick,s.onOpenToggle)}));return s.hasCustomAnchor?c:t.createElement(CP,tT({asChild:!0},o),c)})),PE="PopoverPortal",[EE,OE]=_E(PE,{forceMount:void 0}),IE="PopoverContent",DE=t.forwardRef(((e,r)=>{const n=OE(IE,e.__scopePopover),{forceMount:i=n.forceMount,...s}=e,o=TE(IE,e.__scopePopover);return t.createElement(kP,{present:i||o.open},o.modal?t.createElement(xE,tT({},s,{ref:r})):t.createElement(ME,tT({},s,{ref:r})))})),xE=t.forwardRef(((e,r)=>{const n=TE(IE,e.__scopePopover),i=t.useRef(null),s=iT(r,i),o=t.useRef(!1);return t.useEffect((()=>{const e=i.current;if(e)return LP(e)}),[]),t.createElement(yE,{as:aT,allowPinchZoom:!0},t.createElement(jE,tT({},e,{ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:rT(e.onCloseAutoFocus,(e=>{var t;e.preventDefault(),o.current||null===(t=n.triggerRef.current)||void 0===t||t.focus()})),onPointerDownOutside:rT(e.onPointerDownOutside,(e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,n=2===t.button||r;o.current=n}),{checkForDefaultPrevented:!1}),onFocusOutside:rT(e.onFocusOutside,(e=>e.preventDefault()),{checkForDefaultPrevented:!1})})))})),ME=t.forwardRef(((e,r)=>{const n=TE(IE,e.__scopePopover),i=t.useRef(!1),s=t.useRef(!1);return t.createElement(jE,tT({},e,{ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{var r,o;(null===(r=e.onCloseAutoFocus)||void 0===r||r.call(e,t),t.defaultPrevented)||(i.current||null===(o=n.triggerRef.current)||void 0===o||o.focus(),t.preventDefault());i.current=!1,s.current=!1},onInteractOutside:t=>{var r,o;null===(r=e.onInteractOutside)||void 0===r||r.call(e,t),t.defaultPrevented||(i.current=!0,"pointerdown"===t.detail.originalEvent.type&&(s.current=!0));const a=t.target;(null===(o=n.triggerRef.current)||void 0===o?void 0:o.contains(a))&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&s.current&&t.preventDefault()}}))})),jE=t.forwardRef(((e,r)=>{const{__scopePopover:n,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=TE(IE,n),f=CE(n);return t.useEffect((()=>{var e,t;const r=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",null!==(e=r[0])&&void 0!==e?e:CT()),document.body.insertAdjacentElement("beforeend",null!==(t=r[1])&&void 0!==t?t:CT()),ST++,()=>{1===ST&&document.querySelectorAll("[data-radix-focus-guard]").forEach((e=>e.remove())),ST--}}),[]),t.createElement(PT,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:s,onUnmountAutoFocus:o},t.createElement(yT,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1)},t.createElement(RP,tT({"data-state":LE(h.open),role:"dialog",id:h.contentId},f,p,{ref:r,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)"}}))))}));function LE(e){return e?"open":"closed"}const AE=e=>{const{__scopePopover:r,forceMount:n,children:i,container:s}=e,o=TE(PE,r);return t.createElement(EE,{scope:r,forceMount:n},t.createElement(kP,{present:n||o.open},t.createElement(TP,{asChild:!0,container:s},i)))},NE=DE,BE=e=>{const{__scopePopover:r,children:n,open:i,defaultOpen:s,onOpenChange:o,modal:a=!1}=e,c=CE(r),d=t.useRef(null),[l,u]=t.useState(!1),[p=!1,h]=EP({prop:i,defaultProp:s,onChange:o});return t.createElement(SP,c,t.createElement(RE,{scope:r,contentId:NT(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:t.useCallback((()=>h((e=>!e))),[h]),hasCustomAnchor:l,onCustomAnchorAdd:t.useCallback((()=>u(!0)),[]),onCustomAnchorRemove:t.useCallback((()=>u(!1)),[]),modal:a},n))},FE=kE,zE=s.forwardRef(((e,t)=>{var{style:r,align:n="center",sideOffset:i=4}=e,o=kC(e,["style","align","sideOffset"]);return s.createElement(AE,null,s.createElement(NE,Object.assign({ref:t,align:n,sideOffset:i,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)))}));zE.displayName=NE.displayName;const VE=s.createContext({}),UE=s.createContext({}),$E=()=>{const e=s.useContext(VE),t=s.useContext(UE);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},GE=s.createContext({}),qE=e=>{const{children:t}=e,r=kC(e,["children"]),[n,i]=s.useState(!1);return s.createElement(GE.Provider,{value:{open:n,setOpen:i}},s.createElement(BE,Object.assign({},r,{open:n,onOpenChange:i}),t))},HE=s.forwardRef(((e,t)=>{var{children:r,style:n}=e,i=kC(e,["children","style"]);return s.createElement(zE,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},n)},i),r)}));HE.displayName="ParticipantMenuContent";const WE=s.forwardRef(((e,t)=>{var{children:r,style:n}=e,i=kC(e,["children","style"]);return s.createElement(FE,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},n)},i),r)}));WE.displayName=FE.displayName;const KE=s.forwardRef(((e,t)=>{var{children:r,style:n,participantAction:i}=e,o=kC(e,["children","style","participantAction"]);const{participant:a,setOpen:c,maximizedParticipant:d,setMaximizedParticipant:l,setFloatingParticipant:u,floatingParticipant:p}=(()=>{const e=s.useContext(GE),t=$E();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),h=PC(),f=EC(xS).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(i){case"maximize":v=()=>{l(m?null:a),c(!1)};break;case"spotlight":v=()=>{h(f?IS({id:a.id}):OS({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%"},n)},o),r)}));function JE(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 QE(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 XE(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 YE(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 ZE(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 eO({participant:e}){const t=EC(xS).find((t=>t.id===e.id)),{isHovered:r,maximizedParticipant:n,floatingParticipant:i}=$E(),o=(null==n?void 0:n.id)===e.id,a=(null==i?void 0:i.id)===e.id;return r?s.createElement(qE,null,s.createElement(WE,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(JE,{height:20,width:20,transform:"rotate(90)"})),s.createElement(HE,null,e.isLocalClient?s.createElement(KE,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},a?s.createElement(s.Fragment,null,s.createElement(ZE,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(YE,{height:16,width:16}),"Pop out")):null,s.createElement(KE,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(QE,{height:16,width:16}),o?"Minimize":"Maximize"),s.createElement(KE,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(XE,{height:16,width:16}),t?"Remove spotlight":"Spotlight"))):null}KE.displayName="ParticipantMenuItem";const tO=s.forwardRef((({className:e,participant:t,children:r},n)=>{const[i,o]=s.useState(!1),a=s.useCallback((()=>{o(!0)}),[]),c=s.useCallback((()=>{o(!1)}),[]);return s.createElement(UE.Provider,{value:{participant:t,isHovered:i}},s.createElement("div",{ref:n,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))}));tO.displayName="GridCell";const rO=s.forwardRef(((e,t)=>{var{stream:r,style:n}=e,i=kC(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=$E();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?s.createElement(OC,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),n),muted:d.isLocalClient},i,{stream:h,onVideoResize:p})):s.createElement(eT,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0})}));function nO({cellView:e,enableParticipantMenu:t,render:r}){const n=null==e?void 0:e.client;if(n)return"video"===e.type?s.createElement(tO,{participant:n},n.isVideoEnabled?s.createElement(s.Fragment,null,r?r({participant:n}):s.createElement(s.Fragment,null,s.createElement(rO,null),t?s.createElement(eO,{participant:n}):null)):s.createElement(eT,{isSmallCell:!1,displayName:(null==n?void 0:n.displayName)||"Guest",withRoundedCorners:!0})):void 0}return rO.displayName="GridVideoView",e.GridCell=tO,e.GridVideoView=rO,e.ParticipantMenu=qE,e.ParticipantMenuContent=HE,e.ParticipantMenuItem=KE,e.ParticipantMenuTrigger=WE,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:n,videoGridGap:i,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}=function({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=RR,gridGap:n=8,videoGridGap:i=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:_}=PR({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo((()=>_?[CR({client:_,aspectRatio:p[_.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[]),[_,p]),C=s.useMemo((()=>b.map((e=>CR({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[b,p]),R=s.useMemo((()=>y.map((e=>CR({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[y,p]),T=s.useMemo((()=>w.map((e=>CR({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})))),[w,p]),k=s.useMemo((()=>AC(c)),[c]);s.useEffect((()=>{a&&u(c.width<500||c.height<500)}),[c,a]);const P=s.useMemo((()=>SR({floatingVideo:S[0],frame:k,gridGap:n,isConstrained:l,roomBounds:k.bounds,videos:C,videoGridGap:i,presentationVideos:R,subgridVideos:T})),[k,S,C,R,T,n,i]);return{containerFrame:k,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:R,cellViewsInSubgrid:T,clientAspectRatios:p,videoStage:P,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:n,videoGridGap:i,enableSubgrid:o,enableConstrainedGrid:c}),R=s.useCallback((({aspectRatio:e,clientId:t})=>{b((r=>Object.assign(Object.assign({},r),{[t]:e})))}),[b]),T=s.useMemo((()=>nO(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{}))),[u]),k=s.useMemo((()=>h.map((t=>nO(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[h]),P=s.useMemo((()=>p.map((t=>nO(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[p]),E=s.useMemo((()=>f.map((e=>nO({cellView:e,enableParticipantMenu:a})))),[f]);return s.useEffect((()=>{if(!d.current)return;const e=new ResizeObserver(iw((()=>{var e,t,r,n;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(n=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==n?n:480})}),{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}}),[]),s.createElement(VE.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(qC,{containerFrame:l,floatingContent:T,layoutVideoStage:g,presentationGridContent:k,gridContent:P,subgridContent:E})))},e.VideoView=OC,e.WherebyProvider=function({children:e}){const t=(({preloadedState:e,injectServices:t})=>gt({devTools:NS,reducer:FS,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(ry.middleware),preloadedState:e}))({injectServices:function(){const e=hC.create({baseUrl:_C}),t=new tC({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:_C}),r=new yC({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=wm({host:new URL(e).host});return new wC({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}()});return s.createElement(k,{context:SC,store:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){const t=PC(),r=EC(xC);return s.useEffect((()=>(t(Cw(e)),()=>{t(Rw())})),[]),{state:r,actions:{setCameraDevice:s.useCallback((e=>t(aw({deviceId:e}))),[t]),setMicrophoneDevice:s.useCallback((e=>t(cw({deviceId:e}))),[t]),setSpeakerDevice:s.useCallback((e=>t(dw({deviceId:e}))),[t]),toggleCameraEnabled:s.useCallback((e=>t(lw({enabled:e}))),[t]),toggleMicrophoneEnabled:s.useCallback((e=>t(uw({enabled:e}))),[t]),toggleLowDataModeEnabled:s.useCallback((e=>t(pw({enabled:e}))),[t])}}},e.useRoomConnection=function(e,t=DC){const r=PC(),n=EC(IC),i=s.useMemo((()=>{const r=new URL(e),n=new URLSearchParams(r.search),i=t.roomKey||n.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:i,roomUrl:e,userAgent:"browser-sdk:3.10.5",externalId:t.externalId||null}}),[e,t]);s.useEffect((()=>()=>{r(oy())}),[]);const o=s.useCallback((e=>r(Jy({text:e}))),[r]),a=s.useCallback((()=>r(i_())),[r]),c=s.useCallback((e=>r(Hw({displayName:e}))),[r]),d=s.useCallback((e=>r(lw({enabled:e}))),[r]),l=s.useCallback((e=>r(uw({enabled:e}))),[r]),u=s.useCallback((e=>r(pw({enabled:e}))),[r]),p=s.useCallback((e=>r(Jw({enabled:e}))),[r]),h=s.useCallback((e=>r(b_({clientIds:[e],enable:!0}))),[r]),f=s.useCallback((e=>r(y_({clientIds:[e],enable:!0}))),[r]),m=s.useCallback((e=>r(LS({participantId:e}))),[r]),g=s.useCallback((e=>r(AS({participantId:e}))),[r]),v=s.useCallback((()=>r(Yy())),[r]),b=s.useCallback((()=>r(T_())),[r]),y=s.useCallback((()=>r(Zy())),[r]),w=s.useCallback((()=>r(k_())),[r]),_=s.useCallback((()=>r(ay(i))),[r]),S=s.useCallback((()=>r(oy())),[r]),C=s.useCallback((e=>r(Y_({locked:e}))),[r]),R=s.useCallback((e=>r(b_({clientIds:e,enable:!1}))),[r]),T=s.useCallback((e=>r(y_({clientIds:e,enable:!1}))),[r]),k=s.useCallback((e=>r(OS({id:e}))),[r]),P=s.useCallback((e=>r(IS({id:e}))),[r]),E=s.useCallback((e=>r(Z_({clientId:e}))),[r]),O=s.useCallback((e=>r(eS({stayBehind:e}))),[r]),{events:I}=n;return{state:kC(n,["events"]),events:I,actions:{toggleLowDataMode:u,toggleRaiseHand:p,askToSpeak:h,askToTurnOnCamera:f,acceptWaitingParticipant:m,knock:a,joinRoom:_,leaveRoom:S,lockRoom:C,muteParticipants:R,turnOffParticipantCameras:T,kickParticipant:E,endMeeting:O,rejectWaitingParticipant:g,sendChatMessage:o,setDisplayName:c,startCloudRecording:v,startScreenshare:b,stopCloudRecording:y,stopScreenshare:w,toggleCamera:d,toggleMicrophone:l,spotlightParticipant:k,removeSpotlight:P}}},e}({},React,ReactDOM);
|
|
3
|
+
let jo;Po.AwaitQueue=class{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}async push(e,t){if(t=t??e.name,Do.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,n)=>{const i={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:e=>{if(i.completed)return;i.completed=!0,this.pendingTasks.delete(i.id),Do.debug(`resolving task [name:${i.name}]`),r(e);const[t]=this.pendingTasks.values();t&&!t.executedAt&&this.execute(t)},reject:e=>{if(!i.completed&&(i.completed=!0,this.pendingTasks.delete(i.id),Do.debug(`rejecting task [name:${i.name}]: %s`,String(e)),n(e),!this.stopping)){const[e]=this.pendingTasks.values();e&&!e.executedAt&&this.execute(e)}}};this.pendingTasks.set(i.id,i),1===this.pendingTasks.size&&this.execute(i)}))}stop(){Do.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Do.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new xo);this.stopping=!1}remove(e){Do.debug(`remove() [taskIdx:${e}]`);const t=Array.from(this.pendingTasks.values())[e];t?t.reject(new Mo):Do.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(Do.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)}}};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=ls,Bo=Is,Fo=new ss.Logger("Producer");class zo extends No.EnhancedEventEmitter{constructor({id:e,localId:t,rtpSender:r,track:n,rtpParameters:i,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=n,this._kind=n.kind,this._rtpParameters=i,this._paused=!!o&&!n.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=ls,$o=Is,Go=new ss.Logger("Consumer");class qo extends Uo.EnhancedEventEmitter{constructor({id:e,localId:t,producerId:r,rtpReceiver:n,track:i,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=n,this._track=i,this._rtpParameters=s,this._paused=!i.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=ls,Ko=Is,Jo=new ss.Logger("DataProducer");class Qo extends Wo.EnhancedEventEmitter{constructor({id:e,dataChannel:t,sctpStreamParameters:r,appData:n}){super(),this._closed=!1,this._observer=new Wo.EnhancedEventEmitter,Jo.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=r,this._appData=n??{},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=ls,Zo=new ss.Logger("DataConsumer");class ea extends Yo.EnhancedEventEmitter{constructor({id:e,dataProducerId:t,dataChannel:r,sctpStreamParameters:n,appData:i}){super(),this._closed=!1,this._observer=new Yo.EnhancedEventEmitter,Zo.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=r,this._sctpStreamParameters=n,this._appData=i??{},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,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=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}),na=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&ta(r,t,n[i]);return ra(r,t),r}}(),ia=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ko,"__esModule",{value:!0}),ko.Transport=void 0;const sa=Po,oa=ia(Lo),aa=ss,ca=ls,da=Is,la=na(Ms),ua=na(As),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:n,dtlsParameters:i,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:n,dtlsParameters:i,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:n,stopTracks:i=!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:n,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:i,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(i)try{e.stop()}catch(e){}throw t}))}async consume({id:e,producerId:t,kind:r,rtpParameters:n,streamId:i,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(n);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:i,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:n="",protocol:i="",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:n,protocol:i});ua.validateSctpStreamParameters(a);const{id:c}=await new Promise(((e,t)=>{this.safeEmit("producedata",{sctpStreamParameters:a,label:n,protocol:i,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:n="",protocol:i="",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:n,protocol:i}),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:n,rtpParameters:i,streamId:s,onRtpReceiver:o}=t.consumerOptions;r.push({trackId:e,kind:n,rtpParameters:i,streamId:s,onRtpReceiver:o})}try{const n=await this._handler.receive(r);for(let r=0;r<n.length;++r){const i=e[r],s=n[r],{id:o,producerId:a,kind:c,rtpParameters:d,appData:l}=i.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),i.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,n)=>{this._awaitQueue.push((async()=>await this._handler.replaceTrack(e.localId,t)),"producer @replacetrack event").then(r).catch(n)})),e.on("@setmaxspatiallayer",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setMaxSpatialLayer(e.localId,t)),"producer @setmaxspatiallayer event").then(r).catch(n)})),e.on("@setrtpencodingparameters",((t,r,n)=>{this._awaitQueue.push((async()=>await this._handler.setRtpEncodingParameters(e.localId,t)),"producer @setrtpencodingparameters event").then(r).catch(n)})),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)}))}};ko.Transport=ba;var ya={},wa={},_a={},Sa={exports:{}},Ca=Sa.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(Ca).forEach((function(e){Ca[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}));var Ra=Sa.exports;!function(e){var t=function(e){return String(Number(e))===e?Number(e):e},r=function(e,r,n){var i=e.name&&e.names;e.push&&!r[e.push]?r[e.push]=[]:i&&!r[e.name]&&(r[e.name]={});var s=e.push?{}:i?r[e.name]:r;!function(e,r,n,i){if(i&&!n)r[i]=t(e[1]);else for(var s=0;s<n.length;s+=1)null!=e[s+1]&&(r[n[s]]=t(e[s+1]))}(n.match(e.reg),s,e.names,e.name),e.push&&r[e.push].push(s)},n=Ra,i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(i))return r(c,o,i)}})),t.media=s,t};var s=function(e,r){var n=r.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&r.length>1&&(e[n[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=[],n=e.split(" ").map(t),i=0;i<n.length;i+=3)r.push({component:n[i],ip:n[i+1],port:n[i+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,n=!1;return"~"!==e[0]?r=t(e):(r=t(e.substring(1,e.length)),n=!0),{scid:r,paused:n}}))}))}}(_a);var Ta=Ra,ka=/%[sdv%]/g,Pa=function(e){var t=1,r=arguments,n=r.length;return e.replace(ka,(function(e){if(t>=n)return e;var i=r[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}}))},Ea=function(e,t,r){var n=[e+"="+(t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format)];if(t.names)for(var i=0;i<t.names.length;i+=1){var s=t.names[i];t.name?n.push(r[t.name][s]):n.push(r[t.names[i]])}else n.push(r[t.name]);return Pa.apply(null,n)},Oa=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ia=["i","c","b","a"],Da=_a,xa=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||Oa,n=t.innerOrder||Ia,i=[];return r.forEach((function(t){Ta[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Ea(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Ea(t,r,e))}))}))})),e.media.forEach((function(e){i.push(Ea("m",Ta.m[0],e)),n.forEach((function(t){Ta[t].forEach((function(r){r.name in e&&null!=e[r.name]?i.push(Ea(t,r,e)):r.push in e&&null!=e[r.push]&&e[r.push].forEach((function(e){i.push(Ea(t,r,e))}))}))}))})),i.join("\r\n")+"\r\n"},Ma=Ra;wa.grammar=Ma,wa.write=xa,wa.parse=Da.parse,wa.parseParams=Da.parseParams,wa.parseFmtpConfig=Da.parseFmtpConfig,wa.parsePayloads=Da.parsePayloads,wa.parseRemoteCandidates=Da.parseRemoteCandidates,wa.parseImageAttributes=Da.parseImageAttributes,wa.parseSimulcastStreamList=Da.parseSimulcastStreamList;var ja={},La=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Aa=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Na=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&La(r,t,n[i]);return Aa(r,t),r}}();Object.defineProperty(ja,"__esModule",{value:!0}),ja.extractRtpCapabilities=function({sdpObject:e}){const t=new Map,r=[];let n=!1,i=!1;for(const s of e.media){const e=s.type;switch(e){case"audio":if(n)continue;n=!0;break;case"video":if(i)continue;i=!0;break;default:continue}for(const r of s.rtp){const n={kind:e,mimeType:`${e}/${r.codec}`,preferredPayloadType:r.payload,clockRate:r.rate,channels:r.encoding,parameters:{},rtcpFeedback:[]};t.set(n.preferredPayloadType,n)}for(const e of s.fmtp||[]){const r=Ba.parseParams(e.config),n=t.get(e.payload);n&&(r?.hasOwnProperty("profile-level-id")&&(r["profile-level-id"]=String(r["profile-level-id"])),n.parameters=r)}for(const r of s.rtcpFb||[]){const n={type:r.type,parameter:r.subtype};if(n.parameter||delete n.parameter,"*"!==r.payload){const e=t.get(r.payload);if(!e)continue;e.rtcpFeedback.push(n)}else for(const r of t.values())r.kind!==e||/.+\/rtx$/i.test(r.mimeType)||r.rtcpFeedback.push(n)}for(const t of s.ext||[]){if(t["encrypt-uri"])continue;const n={kind:e,uri:t.uri,preferredId:t.value};r.push(n)}}return{codecs:Array.from(t.values()),headerExtensions:r}},ja.extractDtlsParameters=function({sdpObject:e}){let t,r=e.setup,n=e.fingerprint;if(!r||!n){const t=(e.media||[]).find((e=>0!==e.port));t&&(r??(r=t.setup),n??(n=t.fingerprint))}if(!r)throw new Error("no a=setup found at SDP session or media level");if(!n)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:n.type,value:n.hash}]}},ja.getCname=function({offerMediaObject:e}){const t=(e.ssrcs||[]).find((e=>"cname"===e.attribute));if(!t)return"";return t.value},ja.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 n=t.fmtp.find((e=>e.payload===r.payloadType));n||(n={payload:r.payloadType,config:""},t.fmtp.push(n));const i=Ba.parseParams(n.config);switch(e){case"audio/opus":{const e=r.parameters["sprop-stereo"];void 0!==e&&(i.stereo=Number(e)?1:0);break}}n.config="";for(const e of Object.keys(i))n.config&&(n.config+=";"),n.config+=`${e}=${i[e]}`}};const Ba=Na(wa);var Fa={};Object.defineProperty(Fa,"__esModule",{value:!0}),Fa.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 n of e.ssrcGroups||[]){if("FID"!==n.semantics)continue;let[e,i]=n.ssrcs.split(/\s+/);e=Number(e),i=Number(i),t.has(e)&&(t.delete(e),t.delete(i),r.set(e,i))}for(const e of t)r.set(e,null);const n=[];for(const[e,t]of r){const r={ssrc:e};t&&(r.rtx={ssrc:t}),n.push(r)}return n},Fa.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[n,i]=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:`${n} ${i}`});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:`${n} ${i}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${r} ${s}`})}};var za={};Object.defineProperty(za,"__esModule",{value:!0}),za.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 Va={};Object.defineProperty(Va,"__esModule",{value:!0}),Va.HandlerInterface=void 0;const Ua=ls;class $a extends Ua.EnhancedEventEmitter{constructor(){super()}}Va.HandlerInterface=$a;var Ga={},qa={},Ha=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Wa=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ka=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Ha(r,t,n[i]);return Wa(r,t),r}}();Object.defineProperty(qa,"__esModule",{value:!0}),qa.OfferMediaSection=qa.AnswerMediaSection=qa.MediaSection=void 0;const Ja=Ka(wa),Qa=Ka(Ms);class Xa{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,planB:n=!1}){if(this._mediaObject={},this._planB=n,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}}qa.MediaSection=Xa;qa.AnswerMediaSection=class extends Xa{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,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,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.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:Ya(e),rate:e.clockRate};e.channels>1&&(t.encoding=e.channels),this._mediaObject.rtp.push(t);const r=Qa.clone(e.parameters)??{};let n=Qa.clone(e.rtcpFeedback)??[];if(d){const{opusStereo:t,opusFec:i,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!==i&&(m.parameters.useinbandfec=i?1:0,r.useinbandfec=i?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)),n=n.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 i={payload:e.payloadType,config:""};for(const e of Object.keys(r))i.config&&(i.config+=";"),i.config+=`${e}=${r[e]}`;i.config&&this._mediaObject.fmtp.push(i);for(const t of n)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=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=n.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.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,n=Ja.parseSimulcastStreamList(r);for(const e of n)for(const r of e)r.paused=!t[r.scid]?.active;this._mediaObject.simulcast.list1=n.map((e=>e.map((e=>`${e.paused?"~":""}${e.scid}`)).join(","))).join(";")}};function Ya(e){const t=new RegExp("^(audio|video)/(.+)","i").exec(e.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}qa.OfferMediaSection=class extends Xa{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,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,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.protocol=n?"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:Ya(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=n.port,this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:n.port,maxMessageSize:n.maxMessageSize}):(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=n.port,this._mediaObject.maxMessageSize=n.maxMessageSize)}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}planBReceive({offerRtpParameters:e,streamId:t,trackId:r}){const n=e.encodings[0],i=n.ssrc,s=n.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:Ya(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:i,attribute:"cname",value:e.rtcp.cname}),this._mediaObject.ssrcs.push({id:i,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:`${i} ${s}`}))}planBStopReceiving({offerRtpParameters:e}){const t=e.encodings[0],r=t.ssrc,n=t.rtx?.ssrc;this._mediaObject.ssrcs=this._mediaObject.ssrcs.filter((e=>e.id!==r&&e.id!==n)),n&&(this._mediaObject.ssrcGroups=this._mediaObject.ssrcGroups.filter((e=>e.ssrcs!==`${r} ${n}`)))}};var Za=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),ec=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),tc=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Za(r,t,n[i]);return ec(r,t),r}}();Object.defineProperty(Ga,"__esModule",{value:!0}),Ga.RemoteSdp=void 0;const rc=tc(wa),nc=qa,ic=new ss.Logger("RemoteSdp");Ga.RemoteSdp=class{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:r,sctpParameters:n,plainRtpParameters:i,planB:s=!1}){if(this._mediaSections=[],this._midToIndex=new Map,this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=r,this._sctpParameters=n,this._plainRtpParameters=i,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:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){ic.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){ic.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:n,codecOptions:i,extmapAllowMixed:s=!1}){const o=new nc.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,offerMediaObject:e,offerRtpParameters:r,answerRtpParameters:n,codecOptions:i,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:n,trackId:i}){const s=this._midToIndex.get(e);let o;if(void 0!==s&&(o=this._mediaSections[s]),o)o.planBReceive({offerRtpParameters:r,streamId:n,trackId:i}),this._replaceMediaSection(o);else{o=new nc.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,planB:this._planB,mid:e,kind:t,offerRtpParameters:r,streamId:n,trackId:i});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?(ic.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 nc.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 nc.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++,rc.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 n=this._mediaSections[r];this._mediaSections[r]=e,this._midToIndex.delete(n.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 sc={};Object.defineProperty(sc,"__esModule",{value:!0}),sc.parse=function(e){const t=oc.exec(e??"");return t?{spatialLayers:Number(t[1]),temporalLayers:Number(t[2])}:{spatialLayers:1,temporalLayers:1}};const oc=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");var ac=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),cc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),dc=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&ac(r,t,n[i]);return cc(r,t),r}}();Object.defineProperty(ya,"__esModule",{value:!0}),ya.Chrome111=void 0;const lc=dc(wa),uc=ss,pc=dc(Ms),hc=dc(As),fc=dc(ja),mc=dc(Fa),gc=dc(za),vc=Is,bc=Va,yc=Ga,wc=sc,_c=new uc.Logger("Chrome111"),Sc={OS:1024,MIS:1024};class Cc extends bc.HandlerInterface{static createFactory(){return()=>new Cc}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(_c.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){_c.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=lc.parse(t.sdp),n=fc.extractRtpCapabilities({sdpObject:r});return gc.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return _c.debug("getNativeSctpCapabilities()"),{numStreams:Sc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),_c.debug("run()"),this._direction=e,this._remoteSdp=new yc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:hc.getSendingRtpParameters("audio",d),video:hc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:hc.getSendingRemoteRtpParameters("audio",d),video:hc.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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)})):(_c.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(),_c.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),_c.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});_c.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};_c.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};_c.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();_c.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:n,onRtpSender:i}){if(this.assertNotClosed(),this.assertSendDirection(),_c.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,wc.parse)(r.scalabilityMode).temporalLayers:3;t>e&&(e=t)}t.forEach(((t,r)=>{t.rid=`r${r}`,t.scalabilityMode=`L1T${e}`}))}const s=pc.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=hc.reduceCodecs(s.codecs,n);const o=pc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=hc.reduceCodecs(o.codecs,n);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(c.sender);const d=await this._pc.createOffer();let l=lc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),_c.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const u=c.mid;s.mid=u,l=lc.parse(this._pc.localDescription.sdp);const p=l.media[a.idx];if(s.rtcp.cname=fc.getCname({offerMediaObject:p}),t)if(1===t.length){const e=mc.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=mc.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 _c.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(),_c.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();_c.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};_c.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),_c.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();_c.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};_c.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),_c.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();_c.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};_c.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?_c.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):_c.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(),_c.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();_c.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};_c.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),_c.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();_c.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};_c.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};_c.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Sc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=lc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),_c.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};_c.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;_c.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};_c.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=lc.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));fc.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:lc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),_c.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){_c.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()};_c.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();_c.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){_c.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()};_c.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();_c.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){_c.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()};_c.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();_c.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};_c.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()};_c.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=lc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}_c.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=lc.parse(this._pc.localDescription.sdp));const r=fc.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 vc.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=Cc;var Rc={},Tc=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),kc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Pc=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Tc(r,t,n[i]);return kc(r,t),r}}();Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.Chrome74=void 0;const Ec=Pc(wa),Oc=ss,Ic=Pc(Ms),Dc=Pc(As),xc=Pc(ja),Mc=Pc(Fa),jc=Pc(za),Lc=Is,Ac=Va,Nc=Ga,Bc=sc,Fc=new Oc.Logger("Chrome74"),zc={OS:1024,MIS:1024};class Vc extends Ac.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"Chrome74"}close(){if(Fc.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Fc.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=Ec.parse(t.sdp),n=xc.extractRtpCapabilities({sdpObject:r});return jc.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Fc.debug("getNativeSctpCapabilities()"),{numStreams:zc}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Fc.debug("run()"),this._direction=e,this._remoteSdp=new Nc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Dc.getSendingRtpParameters("audio",d),video:Dc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Dc.getSendingRemoteRtpParameters("audio",d),video:Dc.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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)})):(Fc.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(),Fc.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Fc.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Fc.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Fc.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Fc.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Fc.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:n}){this.assertNotClosed(),this.assertSendDirection(),Fc.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&t.length>1&&t.forEach(((e,t)=>{e.rid=`r${t}`}));const i=Ic.clone(this._sendingRtpParametersByKind[e.kind]);i.codecs=Dc.reduceCodecs(i.codecs,n);const s=Ic.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=Dc.reduceCodecs(s.codecs,n);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=Ec.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let u=!1;const p=(0,Bc.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===i.codecs[0].mimeType.toLowerCase()&&(Fc.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=Ec.parse(d.sdp),c=l.media[o.idx],Mc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:Ec.write(l)}),Fc.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);const h=a.mid;if(i.mid=h,l=Ec.parse(this._pc.localDescription.sdp),c=l.media[o.idx],i.rtcp.cname=xc.getCname({offerMediaObject:c}),t)if(1===t.length){let e=Mc.getRtpEncodings({offerMediaObject:c});Object.assign(e[0],t[0]),u&&(e=[e[0]]),i.encodings=e}else i.encodings=t;else i.encodings=Mc.getRtpEncodings({offerMediaObject:c});if(i.encodings.length>1&&("video/vp8"===i.codecs[0].mimeType.toLowerCase()||"video/h264"===i.codecs[0].mimeType.toLowerCase()))for(const e of i.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${p.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:i,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return Fc.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:i,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),Fc.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();Fc.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Fc.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Fc.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();Fc.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Fc.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Fc.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();Fc.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Fc.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Fc.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Fc.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(),Fc.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Fc.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Fc.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Fc.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Fc.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Fc.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Fc.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%zc.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Ec.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Fc.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Fc.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;Fc.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Fc.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=Ec.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));xc.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Ec.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Fc.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Fc.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()};Fc.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Fc.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){Fc.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()};Fc.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Fc.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){Fc.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()};Fc.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Fc.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Fc.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()};Fc.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Ec.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Fc.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=Ec.parse(this._pc.localDescription.sdp));const r=xc.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 Lc.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')}}Rc.Chrome74=Vc;var Uc={},$c=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Gc=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),qc=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&$c(r,t,n[i]);return Gc(r,t),r}}();Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.Chrome70=void 0;const Hc=qc(wa),Wc=ss,Kc=qc(Ms),Jc=qc(As),Qc=qc(ja),Xc=qc(Fa),Yc=Va,Zc=Ga,ed=sc,td=new Wc.Logger("Chrome70"),rd={OS:1024,MIS:1024};class nd extends Yc.HandlerInterface{static createFactory(){return()=>new nd}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(td.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){td.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=Hc.parse(t.sdp);return Qc.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return td.debug("getNativeSctpCapabilities()"),{numStreams:rd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){td.debug("run()"),this._direction=e,this._remoteSdp=new Zc.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Jc.getSendingRtpParameters("audio",d),video:Jc.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Jc.getSendingRemoteRtpParameters("audio",d),video:Jc.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(td.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){td.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(td.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});td.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};td.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};td.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();td.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:n}){this.assertSendDirection(),td.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const i=Kc.clone(this._sendingRtpParametersByKind[e.kind]);i.codecs=Jc.reduceCodecs(i.codecs,n);const s=Kc.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=Jc.reduceCodecs(s.codecs,n);const o=this._remoteSdp.getNextMediaSectionIdx(),a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});let c,d=await this._pc.createOffer(),l=Hc.parse(d.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),t&&t.length>1&&(td.debug("send() | enabling legacy simulcast"),l=Hc.parse(d.sdp),c=l.media[o.idx],Xc.addLegacySimulcast({offerMediaObject:c,numStreams:t.length}),d={type:"offer",sdp:Hc.write(l)});let u=!1;const p=(0,ed.parse)((t??[{}])[0].scalabilityMode);if(t&&1===t.length&&p.spatialLayers>1&&"video/vp9"===i.codecs[0].mimeType.toLowerCase()&&(td.debug("send() | enabling legacy simulcast for VP9 SVC"),u=!0,l=Hc.parse(d.sdp),c=l.media[o.idx],Xc.addLegacySimulcast({offerMediaObject:c,numStreams:p.spatialLayers}),d={type:"offer",sdp:Hc.write(l)}),td.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d),t){td.debug("send() | applying given encodings");const e=a.sender.getParameters();for(let r=0;r<(e.encodings??[]).length;++r){const n=e.encodings[r],i=t[r];if(!i)break;e.encodings[r]=Object.assign(n,i)}await a.sender.setParameters(e)}const h=a.mid;if(i.mid=h,l=Hc.parse(this._pc.localDescription.sdp),c=l.media[o.idx],i.rtcp.cname=Qc.getCname({offerMediaObject:c}),i.encodings=Xc.getRtpEncodings({offerMediaObject:c}),t)for(let e=0;e<i.encodings.length;++e)t[e]&&Object.assign(i.encodings[e],t[e]);if(u&&(i.encodings=[i.encodings[0]]),i.encodings.length>1&&("video/vp8"===i.codecs[0].mimeType.toLowerCase()||"video/h264"===i.codecs[0].mimeType.toLowerCase()))for(const e of i.encodings)e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:c,reuseMid:o.reuseMid,offerRtpParameters:i,answerRtpParameters:s,codecOptions:r});const f={type:"answer",sdp:this._remoteSdp.getSdp()};return td.debug("send() | calling pc.setRemoteDescription() [answer:%o]",f),await this._pc.setRemoteDescription(f),this._mapMidTransceiver.set(h,a),{localId:h,rtpParameters:i,rtpSender:a.sender}}async stopSending(e){this.assertSendDirection(),td.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();td.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};td.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?td.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):td.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(),td.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();td.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};td.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),td.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();td.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};td.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:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};td.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%rd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Hc.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),td.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};td.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;td.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};td.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=Hc.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Qc.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:Hc.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),td.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){td.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()};td.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();td.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};td.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()};td.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Hc.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}td.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=Hc.parse(this._pc.localDescription.sdp));const r=Qc.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')}}Uc.Chrome70=nd;var id={},sd={};Object.defineProperty(sd,"__esModule",{value:!0}),sd.getRtpEncodings=function({offerMediaObject:e,track:t}){const r=new Set;for(const n of e.ssrcs||[]){if("msid"!==n.attribute)continue;if(n.value.split(" ")[1]===t.id){const e=n.id;r.add(e)}}if(0===r.size)throw new Error(`a=ssrc line with msid information not found [track.id:${t.id}]`);const n=new Map;for(const t of e.ssrcGroups||[]){if("FID"!==t.semantics)continue;let[e,i]=t.ssrcs.split(/\s+/);e=Number(e),i=Number(i),r.has(e)&&(r.delete(e),r.delete(i),n.set(e,i))}for(const e of r)n.set(e,null);const i=[];for(const[e,t]of n){const r={ssrc:e};t&&(r.rtx={ssrc:t}),i.push(r)}return i},sd.addLegacySimulcast=function({offerMediaObject:e,track:t,numStreams:r}){if(r<=1)throw new TypeError("numStreams must be greater than 1");let n,i,s;if(!(e.ssrcs||[]).find((e=>{if("msid"!==e.attribute)return!1;return e.value.split(" ")[1]===t.id&&(n=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])===n&&(i=Number(t[1]),!0)}));const o=e.ssrcs.find((e=>"cname"===e.attribute&&e.id===n));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(n+e),i&&d.push(i+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 n=c[r],i=d[r];e.ssrcs.push({id:i,attribute:"cname",value:a}),e.ssrcs.push({id:i,attribute:"msid",value:`${s} ${t.id}`}),e.ssrcGroups.push({semantics:"FID",ssrcs:`${n} ${i}`})}};var od=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),ad=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),cd=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&od(r,t,n[i]);return ad(r,t),r}}();Object.defineProperty(id,"__esModule",{value:!0}),id.Chrome67=void 0;const dd=cd(wa),ld=ss,ud=cd(Ms),pd=cd(As),hd=cd(ja),fd=cd(sd),md=Va,gd=Ga,vd=new ld.Logger("Chrome67"),bd={OS:1024,MIS:1024};class yd extends md.HandlerInterface{static createFactory(){return()=>new yd}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(vd.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){vd.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=dd.parse(t.sdp);return hd.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return vd.debug("getNativeSctpCapabilities()"),{numStreams:bd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){vd.debug("run()"),this._direction=e,this._remoteSdp=new gd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:pd.getSendingRtpParameters("audio",d),video:pd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:pd.getSendingRemoteRtpParameters("audio",d),video:pd.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(vd.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){vd.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(vd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});vd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};vd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};vd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();vd.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:n}){this.assertSendDirection(),vd.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&vd.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let i,s=await this._pc.createOffer(),o=dd.parse(s.sdp);const a=ud.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=pd.reduceCodecs(a.codecs);const c=ud.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=pd.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(vd.debug("send() | enabling simulcast"),o=dd.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),fd.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:dd.write(o)}),vd.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=dd.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=hd.getCname({offerMediaObject:i}),a.encodings=fd.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};vd.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(),vd.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();vd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void vd.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};vd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?vd.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):vd.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.track;await r.replaceTrack(t),n&&this._sendStream.removeTrack(n),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),vd.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(n)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),vd.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.setParameters(n)}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:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};vd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%bd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=dd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),vd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};vd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,streamId:i}=t;vd.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:n,streamId:i??n.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};vd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let n=await this._pc.createAnswer();const i=dd.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,s=i.media.find((e=>String(e.mid)===n));hd.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}n={type:"answer",sdp:dd.write(i)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:i}),vd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const r of e){const{kind:e,trackId:n,rtpParameters:i}=r,s=n,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:i,rtpReceiver:a}),t.push({localId:s,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){vd.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()};vd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();vd.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};vd.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()};vd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=dd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}vd.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=dd.parse(this._pc.localDescription.sdp));const r=hd.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')}}id.Chrome67=yd;var wd={},_d=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Sd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Cd=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&_d(r,t,n[i]);return Sd(r,t),r}}();Object.defineProperty(wd,"__esModule",{value:!0}),wd.Chrome55=void 0;const Rd=Cd(wa),Td=ss,kd=Is,Pd=Cd(Ms),Ed=Cd(As),Od=Cd(ja),Id=Cd(sd),Dd=Va,xd=Ga,Md=new Td.Logger("Chrome55"),jd={OS:1024,MIS:1024};class Ld extends Dd.HandlerInterface{static createFactory(){return()=>new Ld}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(Md.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Md.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=Rd.parse(t.sdp);return Od.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Md.debug("getNativeSctpCapabilities()"),{numStreams:jd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Md.debug("run()"),this._direction=e,this._remoteSdp=new xd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:Ed.getSendingRtpParameters("audio",d),video:Ed.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Ed.getSendingRemoteRtpParameters("audio",d),video:Ed.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(Md.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){Md.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Md.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Md.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Md.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Md.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Md.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:n}){this.assertSendDirection(),Md.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&Md.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let i,s=await this._pc.createOffer(),o=Rd.parse(s.sdp);const a=Pd.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Ed.reduceCodecs(a.codecs);const c=Pd.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Ed.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Md.debug("send() | enabling simulcast"),o=Rd.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),Id.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:Rd.write(o)}),Md.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Rd.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=Od.getCname({offerMediaObject:i}),a.encodings=Id.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Md.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(),Md.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();Md.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Md.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};Md.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new kd.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new kd.UnsupportedError(" not implemented")}async setRtpEncodingParameters(e,t){throw new kd.UnsupportedError("not supported")}async getSenderStats(e){throw new kd.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};Md.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%jd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Rd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Md.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Md.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,streamId:i}=t;Md.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:n,streamId:i??n.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Md.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let n=await this._pc.createAnswer();const i=Rd.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,s=i.media.find((e=>String(e.mid)===n));Od.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}n={type:"answer",sdp:Rd.write(i)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:i}),Md.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const r of e){const{kind:e,trackId:n,rtpParameters:i}=r,s=e,o=n,a=r.streamId??i.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:i}),t.push({localId:o,track:c})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Md.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()};Md.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Md.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new kd.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Md.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()};Md.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Rd.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Md.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=Rd.parse(this._pc.localDescription.sdp));const r=Od.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')}}wd.Chrome55=Ld;var Ad={},Nd=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Bd=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Fd=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Nd(r,t,n[i]);return Bd(r,t),r}}();Object.defineProperty(Ad,"__esModule",{value:!0}),Ad.Firefox120=void 0;const zd=Fd(wa),Vd=ss,Ud=Is,$d=Fd(Ms),Gd=Fd(As),qd=Fd(ja),Hd=Fd(Fa),Wd=Va,Kd=Ga,Jd=sc,Qd=new Vd.Logger("Firefox120"),Xd={OS:16,MIS:2048};class Yd extends Wd.HandlerInterface{static createFactory(){return()=>new Yd}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(Qd.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){Qd.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 n=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const i=zd.parse(n.sdp);return qd.extractRtpCapabilities({sdpObject:i})}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw n}}async getNativeSctpCapabilities(){return Qd.debug("getNativeSctpCapabilities()"),{numStreams:Xd}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Qd.debug("run()"),this._direction=e,this._remoteSdp=new Kd.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Gd.getSendingRtpParameters("audio",d),video:Gd.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Gd.getSendingRemoteRtpParameters("audio",d),video:Gd.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(Qd.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 Ud.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),Qd.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Qd.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Qd.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Qd.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Qd.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:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),Qd.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=$d.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Gd.reduceCodecs(s.codecs,n);const o=$d.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Gd.reduceCodecs(o.codecs,n);const a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(a.sender);const c=await this._pc.createOffer();let d=zd.parse(c.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:d});const l=(0,Jd.parse)((t??[{}])[0].scalabilityMode);Qd.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);const u=a.mid;s.mid=u,d=zd.parse(this._pc.localDescription.sdp);const p=d.media[d.media.length-1];if(s.rtcp.cname=qd.getCname({offerMediaObject:p}),t)if(1===t.length){const e=Hd.getRtpEncodings({offerMediaObject:p});Object.assign(e[0],t[0]),s.encodings=e}else s.encodings=t;else s.encodings=Hd.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 Qd.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(),Qd.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();Qd.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qd.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Qd.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();Qd.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qd.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Qd.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();Qd.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qd.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Qd.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Qd.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(),Qd.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Qd.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Qd.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Qd.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Qd.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Qd.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Qd.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Xd.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=zd.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),Qd.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Qd.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;Qd.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Qd.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=zd.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));qd.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:zd.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),Qd.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Qd.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()};Qd.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qd.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){Qd.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()};Qd.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qd.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){Qd.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()};Qd.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Qd.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Qd.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()};Qd.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=zd.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}Qd.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=zd.parse(this._pc.localDescription.sdp));const r=qd.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 Ud.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')}}Ad.Firefox120=Yd;var Zd={},el=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),tl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),rl=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&el(r,t,n[i]);return tl(r,t),r}}();Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.Firefox60=void 0;const nl=rl(wa),il=ss,sl=Is,ol=rl(Ms),al=rl(As),cl=rl(ja),dl=rl(Fa),ll=Va,ul=Ga,pl=sc,hl=new il.Logger("Firefox60"),fl={OS:16,MIS:2048};class ml extends ll.HandlerInterface{static createFactory(){return()=>new ml}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(hl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){hl.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 n=e.addTransceiver(r,{direction:"sendrecv"}),i=n.sender.getParameters(),s=[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}];i.encodings=s,await n.sender.setParameters(i);const o=await e.createOffer();try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}const a=nl.parse(o.sdp);return cl.extractRtpCapabilities({sdpObject:a})}catch(n){try{t.remove()}catch(e){}try{r.stop()}catch(e){}try{e.close()}catch(e){}throw n}}async getNativeSctpCapabilities(){return hl.debug("getNativeSctpCapabilities()"),{numStreams:fl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),hl.debug("run()"),this._direction=e,this._remoteSdp=new ul.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:al.getSendingRtpParameters("audio",d),video:al.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:al.getSendingRemoteRtpParameters("audio",d),video:al.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(hl.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 sl.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),hl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});hl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};hl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};hl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();hl.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:n}){this.assertNotClosed(),this.assertSendDirection(),hl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),t&&((t=ol.clone(t)).forEach(((e,t)=>{e.rid=`r${t}`})),t.reverse());const i=ol.clone(this._sendingRtpParametersByKind[e.kind]);i.codecs=al.reduceCodecs(i.codecs,n);const s=ol.clone(this._sendingRemoteRtpParametersByKind[e.kind]);s.codecs=al.reduceCodecs(s.codecs,n);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=nl.parse(a.sdp);this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:c});const d=(0,pl.parse)((t??[{}])[0].scalabilityMode);hl.debug("send() | calling pc.setLocalDescription() [offer:%o]",a),await this._pc.setLocalDescription(a);const l=o.mid;i.mid=l,c=nl.parse(this._pc.localDescription.sdp);const u=c.media[c.media.length-1];if(i.rtcp.cname=cl.getCname({offerMediaObject:u}),t)if(1===t.length){const e=dl.getRtpEncodings({offerMediaObject:u});Object.assign(e[0],t[0]),i.encodings=e}else i.encodings=t.reverse();else i.encodings=dl.getRtpEncodings({offerMediaObject:u});if(i.encodings.length>1&&("video/vp8"===i.codecs[0].mimeType.toLowerCase()||"video/h264"===i.codecs[0].mimeType.toLowerCase()))for(const e of i.encodings)e.scalabilityMode?e.scalabilityMode=`L1T${d.temporalLayers}`:e.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:u,offerRtpParameters:i,answerRtpParameters:s,codecOptions:r,extmapAllowMixed:!0});const p={type:"answer",sdp:this._remoteSdp.getSdp()};return hl.debug("send() | calling pc.setRemoteDescription() [answer:%o]",p),await this._pc.setRemoteDescription(p),this._mapMidTransceiver.set(l,o),{localId:l,rtpParameters:i,rtpSender:o.sender}}async stopSending(e){if(this.assertSendDirection(),hl.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();hl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};hl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),hl.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();hl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};hl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),hl.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();hl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};hl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?hl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):hl.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(),hl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated transceiver not found");const n=r.sender.getParameters();t=n.encodings.length-1-t,n.encodings.forEach(((e,r)=>{e.active=r>=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();hl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};hl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),hl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();hl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};hl.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};hl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%fl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=nl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:t}),hl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};hl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;hl.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};hl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=nl.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,o=r.get(e),a=s.media.find((e=>String(e.mid)===o));cl.applyCodecParameters({offerRtpParameters:n,answerMediaObject:a}),i={type:"answer",sdp:nl.write(s)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:s}),hl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){hl.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()};hl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();hl.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){hl.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()};hl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();hl.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){hl.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()};hl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();hl.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};hl.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()};hl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=nl.parse(t.sdp);await this.setupTransport({localDtlsRole:"client",localSdpObject:e})}hl.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=nl.parse(this._pc.localDescription.sdp));const r=cl.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')}}Zd.Firefox60=ml;var gl={},vl=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),bl=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&vl(r,t,n[i]);return bl(r,t),r}}();Object.defineProperty(gl,"__esModule",{value:!0});var wl=gl.Safari12=void 0;const _l=yl(wa),Sl=ss,Cl=yl(Ms),Rl=yl(As),Tl=yl(ja),kl=yl(Fa),Pl=yl(za),El=Is,Ol=Va,Il=Ga,Dl=sc,xl=new Sl.Logger("Safari12"),Ml={OS:1024,MIS:1024};class jl extends Ol.HandlerInterface{static createFactory(){return()=>new jl}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(xl.debug("close()"),!this._closed){if(this._closed=!0,this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}}async getNativeRtpCapabilities(){xl.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=_l.parse(t.sdp),n=Tl.extractRtpCapabilities({sdpObject:r});return Pl.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return xl.debug("getNativeSctpCapabilities()"),{numStreams:Ml}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),xl.debug("run()"),this._direction=e,this._remoteSdp=new Il.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:Rl.getSendingRtpParameters("audio",d),video:Rl.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Rl.getSendingRemoteRtpParameters("audio",d),video:Rl.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(xl.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(),xl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),xl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});xl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};xl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};xl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();xl.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:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),xl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id);const s=Cl.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=Rl.reduceCodecs(s.codecs,n);const o=Cl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=Rl.reduceCodecs(o.codecs,n);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});i&&i(c.sender);let d,l=await this._pc.createOffer(),u=_l.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});const p=(0,Dl.parse)((t??[{}])[0].scalabilityMode);t&&t.length>1&&(xl.debug("send() | enabling legacy simulcast"),u=_l.parse(l.sdp),d=u.media[a.idx],kl.addLegacySimulcast({offerMediaObject:d,numStreams:t.length}),l={type:"offer",sdp:_l.write(u)}),xl.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);const h=c.mid;if(s.mid=h,u=_l.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=Tl.getCname({offerMediaObject:d}),s.encodings=kl.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 xl.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;xl.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();xl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};xl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),xl.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();xl.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};xl.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),xl.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();xl.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};xl.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?xl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):xl.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(),xl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();xl.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};xl.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),xl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();xl.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};xl.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};xl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ml.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=_l.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),xl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};xl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;xl.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};xl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=_l.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));Tl.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:_l.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),xl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){xl.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()};xl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();xl.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){xl.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()};xl.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();xl.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){xl.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()};xl.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();xl.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};xl.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()};xl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=_l.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}xl.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=_l.parse(this._pc.localDescription.sdp));const r=Tl.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 El.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')}}wl=gl.Safari12=jl;var Ll={},Al=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Nl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Bl=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Al(r,t,n[i]);return Nl(r,t),r}}();Object.defineProperty(Ll,"__esModule",{value:!0}),Ll.Safari11=void 0;const Fl=Bl(wa),zl=ss,Vl=Bl(Ms),Ul=Bl(As),$l=Bl(ja),Gl=Bl(sd),ql=Va,Hl=Ga,Wl=new zl.Logger("Safari11"),Kl={OS:1024,MIS:1024};class Jl extends ql.HandlerInterface{static createFactory(){return()=>new Jl}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(Wl.debug("close()"),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Wl.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=Fl.parse(t.sdp);return $l.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Wl.debug("getNativeSctpCapabilities()"),{numStreams:Kl}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Wl.debug("run()"),this._direction=e,this._remoteSdp=new Hl.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:Ul.getSendingRtpParameters("audio",d),video:Ul.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Ul.getSendingRemoteRtpParameters("audio",d),video:Ul.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(Wl.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){Wl.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Wl.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Wl.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Wl.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Wl.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Wl.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:n}){this.assertSendDirection(),Wl.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&Wl.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addTrack(e,this._sendStream);let i,s=await this._pc.createOffer(),o=Fl.parse(s.sdp);const a=Vl.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Ul.reduceCodecs(a.codecs);const c=Vl.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Ul.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Wl.debug("send() | enabling simulcast"),o=Fl.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),Gl.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:Fl.write(o)}),Wl.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Fl.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=$l.getCname({offerMediaObject:i}),a.encodings=Gl.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Wl.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();Wl.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Wl.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};Wl.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){this.assertSendDirection(),t?Wl.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Wl.debug("replaceTrack() [localId:%s, no track]",e);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.track;await r.replaceTrack(t),n&&this._sendStream.removeTrack(n),t&&this._sendStream.addTrack(t)}async setMaxSpatialLayer(e,t){this.assertSendDirection(),Wl.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(n)}async setRtpEncodingParameters(e,t){this.assertSendDirection(),Wl.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapSendLocalIdRtpSender.get(e);if(!r)throw new Error("associated RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.setParameters(n)}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:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Wl.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Kl.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Fl.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Wl.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Wl.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,streamId:i}=t;Wl.debug("receive() [trackId:%s, kind:%s]",e,r);const s=r;this._remoteSdp.receive({mid:s,kind:r,offerRtpParameters:n,streamId:i??n.rtcp.cname,trackId:e})}const r={type:"offer",sdp:this._remoteSdp.getSdp()};Wl.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",r),await this._pc.setRemoteDescription(r);let n=await this._pc.createAnswer();const i=Fl.parse(n.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,s=i.media.find((e=>String(e.mid)===n));$l.applyCodecParameters({offerRtpParameters:r,answerMediaObject:s})}n={type:"answer",sdp:Fl.write(i)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:i}),Wl.debug("receive() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(const r of e){const{kind:e,trackId:n,rtpParameters:i}=r,s=e,o=n,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:i,rtpReceiver:a}),t.push({localId:o,track:a.track,rtpReceiver:a})}return t}async stopReceiving(e){this.assertRecvDirection();for(const t of e){Wl.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()};Wl.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Wl.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Wl.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()};Wl.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Fl.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Wl.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=Fl.parse(this._pc.localDescription.sdp));const r=$l.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')}}Ll.Safari11=Jl;var Ql={},Xl={},Yl=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Zl=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),eu=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Yl(r,t,n[i]);return Zl(r,t),r}}();Object.defineProperty(Xl,"__esModule",{value:!0}),Xl.getCapabilities=function(){const e=RTCRtpReceiver.getCapabilities(),t=tu.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},Xl.mangleRtpParameters=function(e){const t=tu.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 tu=eu(Ms);var ru=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),nu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),iu=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&ru(r,t,n[i]);return nu(r,t),r}}();Object.defineProperty(Ql,"__esModule",{value:!0}),Ql.Edge11=void 0;const su=ss,ou=Is,au=iu(Ms),cu=iu(As),du=iu(Xl),lu=Va,uu=new su.Logger("Edge11");class pu extends lu.HandlerInterface{static createFactory(){return()=>new pu}constructor(){super(),this._rtpSenders=new Map,this._rtpReceivers=new Map,this._nextSendLocalId=0,this._transportReady=!1}get name(){return"Edge11"}close(){uu.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 uu.debug("getNativeRtpCapabilities()"),du.getCapabilities()}async getNativeSctpCapabilities(){return uu.debug("getNativeSctpCapabilities()"),{numStreams:{OS:0,MIS:0}}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){uu.debug("run()"),this._sendingRtpParametersByKind={audio:cu.getSendingRtpParameters("audio",d),video:cu.getSendingRtpParameters("video",d)},this._remoteIceParameters=t,this._remoteIceCandidates=r,this._remoteDtlsParameters=n,this._cname=`CNAME-${au.generateRandomNumber()}`,this.setIceGatherer({iceServers:s,iceTransportPolicy:o}),this.setIceTransport(),this.setDtlsTransport()}async updateIceServers(e){throw new ou.UnsupportedError("not supported")}async restartIce(e){if(uu.debug("restartIce()"),this._remoteIceParameters=e,this._transportReady){uu.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:n}){uu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),uu.debug("send() | calling new RTCRtpSender()");const i=new RTCRtpSender(e,this._dtlsTransport),s=au.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=cu.reduceCodecs(s.codecs,n);const o=s.codecs.some((e=>/.+\/rtx$/i.test(e.mimeType)));t||(t=[{}]);for(const e of t)e.ssrc=au.generateRandomNumber(),o&&(e.rtx={ssrc:au.generateRandomNumber()});s.encodings=t,s.rtcp={cname:this._cname,reducedSize:!0,mux:!0};const a=du.mangleRtpParameters(s);uu.debug("send() | calling rtpSender.send() [params:%o]",a),await i.send(a);const c=String(this._nextSendLocalId);return this._nextSendLocalId++,this._rtpSenders.set(c,i),{localId:c,rtpParameters:s,rtpSender:i}}async stopSending(e){uu.debug("stopSending() [localId:%s]",e);const t=this._rtpSenders.get(e);if(!t)throw new Error("RTCRtpSender not found");this._rtpSenders.delete(e);try{uu.debug("stopSending() | calling rtpSender.stop()"),t.stop()}catch(e){throw uu.warn("stopSending() | rtpSender.stop() failed:%o",e),e}}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){t?uu.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):uu.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){uu.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.setParameters(n)}async setRtpEncodingParameters(e,t){uu.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._rtpSenders.get(e);if(!r)throw new Error("RTCRtpSender not found");const n=r.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.setParameters(n)}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 ou.UnsupportedError("not implemented")}async receive(e){const t=[];for(const t of e){const{trackId:e,kind:r}=t;uu.debug("receive() [trackId:%s, kind:%s]",e,r)}this._transportReady||await this.setupTransport({localDtlsRole:"server"});for(const r of e){const{trackId:e,kind:n,rtpParameters:i}=r;uu.debug("receive() | calling new RTCRtpReceiver()");const s=new RTCRtpReceiver(this._dtlsTransport,n);s.addEventListener("error",(e=>{uu.error('rtpReceiver "error" event [event:%o]',e)}));const o=du.mangleRtpParameters(i);uu.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){uu.debug("stopReceiving() [localId:%s]",t);const e=this._rtpReceivers.get(t);if(!e)throw new Error("RTCRtpReceiver not found");this._rtpReceivers.delete(t);try{uu.debug("stopReceiving() | calling rtpReceiver.stop()"),e.stop()}catch(e){uu.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 ou.UnsupportedError("not implemented")}setIceGatherer({iceServers:e,iceTransportPolicy:t}){const r=new RTCIceGatherer({iceServers:e??[],gatherPolicy:t??"all"});r.addEventListener("error",(e=>{uu.error('iceGatherer "error" event [event:%o]',e)}));try{r.gather()}catch(e){uu.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=>{uu.debug('iceTransport "candidatepairchange" event [pair:%o]',e.pair)})),this._iceTransport=e}setDtlsTransport(){const e=new RTCDtlsTransport(this._iceTransport);e.addEventListener("statechange",(()=>{uu.debug('dtlsTransport "statechange" event [state:%s]',e.state)})),e.addEventListener("dtlsstatechange",(()=>{uu.debug('dtlsTransport "dtlsstatechange" event [state:%s]',e.state),"closed"===e.state&&this.emit("@connectionstatechange","closed")})),e.addEventListener("error",(e=>{uu.error('dtlsTransport "error" event [event:%o]',e)})),this._dtlsTransport=e}async setupTransport({localDtlsRole:e}){uu.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}}Ql.Edge11=pu;var hu={},fu=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),mu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),gu=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&fu(r,t,n[i]);return mu(r,t),r}}();Object.defineProperty(hu,"__esModule",{value:!0}),hu.ReactNativeUnifiedPlan=void 0;const vu=gu(wa),bu=ss,yu=gu(Ms),wu=gu(As),_u=gu(ja),Su=gu(Fa),Cu=gu(za),Ru=Is,Tu=Va,ku=Ga,Pu=sc,Eu=new bu.Logger("ReactNativeUnifiedPlan"),Ou={OS:1024,MIS:1024};class Iu extends Tu.HandlerInterface{static createFactory(){return()=>new Iu}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(Eu.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(){Eu.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=vu.parse(t.sdp),n=_u.extractRtpCapabilities({sdpObject:r});return Cu.addNackSuppportForOpus(n),n}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Eu.debug("getNativeSctpCapabilities()"),{numStreams:Ou}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){this.assertNotClosed(),Eu.debug("run()"),this._direction=e,this._remoteSdp=new ku.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i}),this._sendingRtpParametersByKind={audio:wu.getSendingRtpParameters("audio",d),video:wu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:wu.getSendingRemoteRtpParameters("audio",d),video:wu.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(Eu.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(),Eu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),Eu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Eu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Eu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Eu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Eu.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:n,onRtpSender:i}){this.assertNotClosed(),this.assertSendDirection(),Eu.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=yu.clone(this._sendingRtpParametersByKind[e.kind]);s.codecs=wu.reduceCodecs(s.codecs,n);const o=yu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);o.codecs=wu.reduceCodecs(o.codecs,n);const a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:t});i&&i(c.sender);let d,l=await this._pc.createOffer(),u=vu.parse(l.sdp);this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:u});let p=!1;const h=(0,Pu.parse)((t??[{}])[0].scalabilityMode);t&&1===t.length&&h.spatialLayers>1&&"video/vp9"===s.codecs[0].mimeType.toLowerCase()&&(Eu.debug("send() | enabling legacy simulcast for VP9 SVC"),p=!0,u=vu.parse(l.sdp),d=u.media[a.idx],Su.addLegacySimulcast({offerMediaObject:d,numStreams:h.spatialLayers}),l={type:"offer",sdp:vu.write(u)}),Eu.debug("send() | calling pc.setLocalDescription() [offer:%o]",l),await this._pc.setLocalDescription(l);let f=c.mid??void 0;if(f||Eu.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),s.mid=f,u=vu.parse(this._pc.localDescription.sdp),d=u.media[a.idx],s.rtcp.cname=_u.getCname({offerMediaObject:d}),t)if(1===t.length){let e=Su.getRtpEncodings({offerMediaObject:d});Object.assign(e[0],t[0]),p&&(e=[e[0]]),s.encodings=e}else s.encodings=t;else s.encodings=Su.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 Eu.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;Eu.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();Eu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Eu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),Eu.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();Eu.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Eu.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),Eu.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();Eu.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",r),await this._pc.setLocalDescription(r);const n={type:"answer",sdp:this._remoteSdp.getSdp()};Eu.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?Eu.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Eu.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(),Eu.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{e.active=r<=t})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Eu.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Eu.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),Eu.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);const r=this._mapMidTransceiver.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const n=r.sender.getParameters();n.encodings.forEach(((e,r)=>{n.encodings[r]={...e,...t}})),await r.sender.setParameters(n),this._remoteSdp.muxMediaSectionSimulcast(e,n.encodings);const i=await this._pc.createOffer();Eu.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);const s={type:"answer",sdp:this._remoteSdp.getSdp()};Eu.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:n,protocol:i}){this.assertNotClosed(),this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmits:r,protocol:i};Eu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Ou.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=vu.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Eu.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Eu.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i,streamId:s}=t;Eu.debug("receive() [trackId:%s, kind:%s]",e,n);const o=i.mid??String(this._mapMidTransceiver.size);r.set(e,o),this._remoteSdp.receive({mid:o,kind:n,offerRtpParameters:i,streamId:s??i.rtcp.cname,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Eu.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);for(const t of e){const{trackId:e,onRtpReceiver:n}=t;if(n){const t=r.get(e),i=this._pc.getTransceivers().find((e=>e.mid===t));if(!i)throw new Error("transceiver not found");n(i.receiver)}}let i=await this._pc.createAnswer();const s=vu.parse(i.sdp);for(const t of e){const{trackId:e,rtpParameters:n}=t,i=r.get(e),o=s.media.find((e=>String(e.mid)===i));_u.applyCodecParameters({offerRtpParameters:n,answerMediaObject:o})}i={type:"answer",sdp:vu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Eu.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{trackId:e}=n,i=r.get(e),s=this._pc.getTransceivers().find((e=>e.mid===i));if(!s)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(i,s),t.push({localId:i,track:s.receiver.track,rtpReceiver:s.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(const t of e){Eu.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()};Eu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Eu.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){Eu.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()};Eu.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Eu.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){Eu.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()};Eu.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Eu.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:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o,protocol:r};Eu.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()};Eu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=vu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Eu.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=vu.parse(this._pc.localDescription.sdp));const r=_u.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 Ru.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')}}hu.ReactNativeUnifiedPlan=Iu;var Du={},xu=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Mu=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),ju=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&xu(r,t,n[i]);return Mu(r,t),r}}();Object.defineProperty(Du,"__esModule",{value:!0}),Du.ReactNative=void 0;const Lu=ju(wa),Au=ss,Nu=Is,Bu=ju(Ms),Fu=ju(As),zu=ju(ja),Vu=ju(sd),Uu=Va,$u=Ga,Gu=new Au.Logger("ReactNative"),qu={OS:1024,MIS:1024};class Hu extends Uu.HandlerInterface{static createFactory(){return()=>new Hu}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(Gu.debug("close()"),this._sendStream.release(!1),this._pc)try{this._pc.close()}catch(e){}this.emit("@close")}async getNativeRtpCapabilities(){Gu.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=Lu.parse(t.sdp);return zu.extractRtpCapabilities({sdpObject:r})}catch(t){try{e.close()}catch(e){}throw t}}async getNativeSctpCapabilities(){return Gu.debug("getNativeSctpCapabilities()"),{numStreams:qu}}run({direction:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,extendedRtpCapabilities:d}){Gu.debug("run()"),this._direction=e,this._remoteSdp=new $u.RemoteSdp({iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,planB:!0}),this._sendingRtpParametersByKind={audio:Fu.getSendingRtpParameters("audio",d),video:Fu.getSendingRtpParameters("video",d)},this._sendingRemoteRtpParametersByKind={audio:Fu.getSendingRemoteRtpParameters("audio",d),video:Fu.getSendingRemoteRtpParameters("video",d)},n.role&&"auto"!==n.role&&(this._forcedLocalDtlsRole="server"===n.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(Gu.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){Gu.debug("updateIceServers()");const t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(Gu.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),this._transportReady)if("send"===this._direction){const e=await this._pc.createOffer({iceRestart:!0});Gu.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e);const t={type:"answer",sdp:this._remoteSdp.getSdp()};Gu.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",t),await this._pc.setRemoteDescription(t)}else{const e={type:"offer",sdp:this._remoteSdp.getSdp()};Gu.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();Gu.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:n}){this.assertSendDirection(),Gu.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),n&&Gu.warn("send() | codec selection is not available in %s handler",this.name),this._sendStream.addTrack(e),this._pc.addStream(this._sendStream);let i,s=await this._pc.createOffer(),o=Lu.parse(s.sdp);const a=Bu.clone(this._sendingRtpParametersByKind[e.kind]);a.codecs=Fu.reduceCodecs(a.codecs);const c=Bu.clone(this._sendingRemoteRtpParametersByKind[e.kind]);if(c.codecs=Fu.reduceCodecs(c.codecs),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),"video"===e.kind&&t&&t.length>1&&(Gu.debug("send() | enabling simulcast"),o=Lu.parse(s.sdp),i=o.media.find((e=>"video"===e.type)),Vu.addLegacySimulcast({offerMediaObject:i,track:e,numStreams:t.length}),s={type:"offer",sdp:Lu.write(o)}),Gu.debug("send() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s),o=Lu.parse(this._pc.localDescription.sdp),i=o.media.find((t=>t.type===e.kind)),a.rtcp.cname=zu.getCname({offerMediaObject:i}),a.encodings=Vu.getRtpEncodings({offerMediaObject:i,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:i,offerRtpParameters:a,answerRtpParameters:c,codecOptions:r});const d={type:"answer",sdp:this._remoteSdp.getSdp()};Gu.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(),Gu.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();Gu.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",r);try{await this._pc.setLocalDescription(r)}catch(e){if(0===this._sendStream.getTracks().length)return void Gu.warn("stopSending() | ignoring expected error due no sending tracks: %s",e.toString());throw e}if("stable"===this._pc.signalingState)return;const n={type:"answer",sdp:this._remoteSdp.getSdp()};Gu.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}async pauseSending(e){}async resumeSending(e){}async replaceTrack(e,t){throw new Nu.UnsupportedError("not implemented")}async setMaxSpatialLayer(e,t){throw new Nu.UnsupportedError("not implemented")}async setRtpEncodingParameters(e,t){throw new Nu.UnsupportedError("not implemented")}async getSenderStats(e){throw new Nu.UnsupportedError("not implemented")}async sendDataChannel({ordered:e,maxPacketLifeTime:t,maxRetransmits:r,label:n,protocol:i}){this.assertSendDirection();const s={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e,maxPacketLifeTime:t,maxRetransmitTime:t,maxRetransmits:r,protocol:i};Gu.debug("sendDataChannel() [options:%o]",s);const o=this._pc.createDataChannel(n,s);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%qu.MIS,!this._hasDataChannelMediaSection){const e=await this._pc.createOffer(),t=Lu.parse(e.sdp),r=t.media.find((e=>"application"===e.type));this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:t}),Gu.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",e),await this._pc.setLocalDescription(e),this._remoteSdp.sendSctpAssociation({offerMediaObject:r});const n={type:"answer",sdp:this._remoteSdp.getSdp()};Gu.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n),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:n,rtpParameters:i}=t;Gu.debug("receive() [trackId:%s, kind:%s]",e,n);const s=n;let o=t.streamId??i.rtcp.cname;Gu.debug("receive() | forcing a random remote streamId to avoid well known bug in react-native-webrtc"),o+=`-hack-${Bu.generateRandomNumber()}`,r.set(e,o),this._remoteSdp.receive({mid:s,kind:n,offerRtpParameters:i,streamId:o,trackId:e})}const n={type:"offer",sdp:this._remoteSdp.getSdp()};Gu.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",n),await this._pc.setRemoteDescription(n);let i=await this._pc.createAnswer();const s=Lu.parse(i.sdp);for(const t of e){const{kind:e,rtpParameters:r}=t,n=e,i=s.media.find((e=>String(e.mid)===n));zu.applyCodecParameters({offerRtpParameters:r,answerMediaObject:i})}i={type:"answer",sdp:Lu.write(s)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:s}),Gu.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(const n of e){const{kind:e,trackId:i,rtpParameters:s}=n,o=i,a=e,c=r.get(i),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){Gu.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()};Gu.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);const r=await this._pc.createAnswer();Gu.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",r),await this._pc.setLocalDescription(r)}async pauseReceiving(e){}async resumeReceiving(e){}async getReceiverStats(e){throw new Nu.UnsupportedError("not implemented")}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:r}){this.assertRecvDirection();const{streamId:n,ordered:i,maxPacketLifeTime:s,maxRetransmits:o}=e,a={negotiated:!0,id:n,ordered:i,maxPacketLifeTime:s,maxRetransmitTime:s,maxRetransmits:o,protocol:r};Gu.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()};Gu.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",e),await this._pc.setRemoteDescription(e);const t=await this._pc.createAnswer();if(!this._transportReady){const e=Lu.parse(t.sdp);await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:e})}Gu.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=Lu.parse(this._pc.localDescription.sdp));const r=zu.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')}}Du.ReactNative=Hu;var Wu=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),Ku=a&&a.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ju=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 n=e(t),i=0;i<n.length;i++)"default"!==n[i]&&Wu(r,t,n[i]);return Ku(r,t),r}}();Object.defineProperty(rs,"__esModule",{value:!0}),rs.Device=void 0,rs.detectDevice=gp;const Qu=is,Xu=ss,Yu=ls,Zu=Is,ep=Ju(Ms),tp=Ju(As),rp=ko,np=ya,ip=Rc,sp=Uc,op=id,ap=wd,cp=Ad,dp=Zd,lp=gl,up=Ll,pp=Ql,hp=hu,fp=Du,mp=new Xu.Logger("Device");function gp(e){if(!e&&"object"==typeof navigator&&"ReactNative"===navigator.product)return mp.debug("detectDevice() | React-Native detected"),"undefined"==typeof RTCPeerConnection?void mp.warn("detectDevice() | unsupported react-native-webrtc without RTCPeerConnection, forgot to call registerGlobals()?"):"undefined"!=typeof RTCRtpTransceiver?(mp.debug("detectDevice() | ReactNative UnifiedPlan handler chosen"),"ReactNativeUnifiedPlan"):(mp.debug("detectDevice() | ReactNative PlanB handler chosen"),"ReactNative");if(e||"object"==typeof navigator&&"string"==typeof navigator.userAgent){e??(e=navigator.userAgent);const t=new Qu.UAParser(e);mp.debug("detectDevice() | browser detected [userAgent:%s, parsed:%o]",e,t.getResult());const r=t.getBrowser(),n=r.name?.toLowerCase(),i=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=n&&["chrome","chromium","mobile chrome","chrome webview","chrome headless"].includes(n),f=n&&["firefox","mobile firefox","mobile focus"].includes(n),m=n&&["safari","mobile safari"].includes(n),g=n&&["edge"].includes(n);if((h||g)&&!p&&i>=111)return"Chrome111";if(h&&!p&&i>=74||g&&!p&&i>=88)return"Chrome74";if(h&&!p&&i>=70)return"Chrome70";if(h&&!p&&i>=67)return"Chrome67";if(h&&!p&&i>=55)return"Chrome55";if(f&&!p&&i>=120)return"Firefox120";if(f&&!p&&i>=60)return"Firefox60";if(f&&p&&d>=14.3)return"Safari12";if(m&&i>=12&&"undefined"!=typeof RTCRtpTransceiver&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(m&&i>=11)return"Safari11";if(g&&!p&&i>=11&&i<=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"}mp.warn("detectDevice() | browser not supported [name:%s, version:%s]",n,i)}else mp.warn("detectDevice() | unknown device")}rs.Device=class{constructor({handlerName:e,handlerFactory:t}={}){if(this._loaded=!1,this._observer=new Yu.EnhancedEventEmitter,mp.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)mp.debug("constructor() | handler given: %s",e);else{if(!(e=gp()))throw new Zu.UnsupportedError("device not supported");mp.debug("constructor() | detected handler: %s",e)}switch(e){case"Chrome111":this._handlerFactory=np.Chrome111.createFactory();break;case"Chrome74":this._handlerFactory=ip.Chrome74.createFactory();break;case"Chrome70":this._handlerFactory=sp.Chrome70.createFactory();break;case"Chrome67":this._handlerFactory=op.Chrome67.createFactory();break;case"Chrome55":this._handlerFactory=ap.Chrome55.createFactory();break;case"Firefox120":this._handlerFactory=cp.Firefox120.createFactory();break;case"Firefox60":this._handlerFactory=dp.Firefox60.createFactory();break;case"Safari12":this._handlerFactory=lp.Safari12.createFactory();break;case"Safari11":this._handlerFactory=up.Safari11.createFactory();break;case"Edge11":this._handlerFactory=pp.Edge11.createFactory();break;case"ReactNativeUnifiedPlan":this._handlerFactory=hp.ReactNativeUnifiedPlan.createFactory();break;case"ReactNative":this._handlerFactory=fp.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 Zu.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Zu.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e}){let t;mp.debug("load() [routerRtpCapabilities:%o]",e);try{if(this._loaded)throw new Zu.InvalidStateError("already loaded");const r=ep.clone(e);tp.validateRtpCapabilities(r),t=this._handlerFactory();const n=await t.getNativeRtpCapabilities();mp.debug("load() | got native RTP capabilities:%o",n);const i=ep.clone(n);tp.validateRtpCapabilities(i),this._extendedRtpCapabilities=tp.getExtendedRtpCapabilities(i,r),mp.debug("load() | got extended RTP capabilities:%o",this._extendedRtpCapabilities),this._canProduceByKind.audio=tp.canSend("audio",this._extendedRtpCapabilities),this._canProduceByKind.video=tp.canSend("video",this._extendedRtpCapabilities),this._recvRtpCapabilities=tp.getRecvRtpCapabilities(this._extendedRtpCapabilities),tp.validateRtpCapabilities(this._recvRtpCapabilities),mp.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),this._sctpCapabilities=await t.getNativeSctpCapabilities(),mp.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),tp.validateSctpCapabilities(this._sctpCapabilities),mp.debug("load() succeeded"),this._loaded=!0,t.close()}catch(e){throw t&&t.close(),e}}canProduce(e){if(!this._loaded)throw new Zu.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:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return mp.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createRecvTransport({id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d}){return mp.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:r,dtlsParameters:n,sctpParameters:i,iceServers:s,iceTransportPolicy:o,additionalSettings:a,proprietaryConstraints:c,appData:d})}createTransport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,sctpParameters:s,iceServers:o,iceTransportPolicy:a,additionalSettings:c,proprietaryConstraints:d,appData:l}){if(!this._loaded)throw new Zu.InvalidStateError("not loaded");if("string"!=typeof t)throw new TypeError("missing id");if("object"!=typeof r)throw new TypeError("missing iceParameters");if(!Array.isArray(n))throw new TypeError("missing iceCandidates");if("object"!=typeof i)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 rp.Transport({direction:e,id:t,iceParameters:r,iceCandidates:n,dtlsParameters:i,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 vp={},bp={};Object.defineProperty(bp,"__esModule",{value:!0});var yp={};function wp(){}function _p(){_p.init.call(this)}function Sp(e){return void 0===e._maxListeners?_p.defaultMaxListeners:e._maxListeners}function Cp(e,t,r,n){var i,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 wp,e._eventsCount=0),o){if("function"==typeof o?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),!o.warned&&(i=Sp(e))&&i>0&&o.length>i){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 Rp(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Tp(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 kp(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Object.defineProperty(yp,"__esModule",{value:!0}),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=a&&a.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(rs,e),r(ko,e),r(Ao,e),r(Vo,e),r(Ho,e),r(Xo,e),r(bp,e),r(yp,e),r(Va,e),r(Is,e)}(vp),function(e){var t=a&&a.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=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}),n=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(n){if(n&&n.__esModule)return n;var i={};if(null!=n)for(var s=e(n),o=0;o<s.length;o++)"default"!==s[o]&&t(i,n,s[o]);return r(i,n),i}}(),i=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=i(ts);e.debug=s.default;const o=rs;Object.defineProperty(e,"Device",{enumerable:!0,get:function(){return o.Device}}),Object.defineProperty(e,"detectDevice",{enumerable:!0,get:function(){return o.detectDevice}});const c=n(vp);e.types=c,e.version="3.7.18";var d=sc;Object.defineProperty(e,"parseScalabilityMode",{enumerable:!0,get:function(){return d.parse}})}(Xi),wp.prototype=Object.create(null),_p.EventEmitter=_p,_p.usingDomains=!1,_p.prototype.domain=void 0,_p.prototype._events=void 0,_p.prototype._maxListeners=void 0,_p.defaultMaxListeners=10,_p.init=function(){this.domain=null,_p.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new wp,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},_p.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},_p.prototype.getMaxListeners=function(){return Sp(this)},_p.prototype.emit=function(e){var t,r,n,i,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(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=kp(e,n),s=0;s<n;++s)i[s].call(r)}(r,l,this);break;case 2:!function(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,s=kp(e,i),o=0;o<i;++o)s[o].call(r,n)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,n,i){if(t)e.call(r,n,i);else for(var s=e.length,o=kp(e,s),a=0;a<s;++a)o[a].call(r,n,i)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,n,i,s){if(t)e.call(r,n,i,s);else for(var o=e.length,a=kp(e,o),c=0;c<o;++c)a[c].call(r,n,i,s)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s<n;s++)i[s-1]=arguments[s];!function(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,s=kp(e,i),o=0;o<i;++o)s[o].apply(r,n)}(r,l,this,i)}return!0},_p.prototype.addListener=function(e,t){return Cp(this,e,t,!1)},_p.prototype.on=_p.prototype.addListener,_p.prototype.prependListener=function(e,t){return Cp(this,e,t,!0)},_p.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Rp(this,e,t)),this},_p.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Rp(this,e,t)),this},_p.prototype.removeListener=function(e,t){var r,n,i,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new wp:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,s=r.length;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){o=r[s].listener,i=s;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new wp,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,o||t)}return this},_p.prototype.off=function(e,t){return this.removeListener(e,t)},_p.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new wp,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new wp:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),s=0;s<i.length;++s)"removeListener"!==(n=i[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new wp,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},_p.prototype.listeners=function(e){var t,r,n=this._events;return r=n&&(t=n[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},_p.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Tp.call(e,t)},_p.prototype.listenerCount=Tp,_p.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const Pp=Object.create(null);Pp.open="0",Pp.close="1",Pp.ping="2",Pp.pong="3",Pp.message="4",Pp.upgrade="5",Pp.noop="6";const Ep=Object.create(null);Object.keys(Pp).forEach((e=>{Ep[Pp[e]]=e}));const Op={type:"error",data:"parser error"},Ip="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Dp="function"==typeof ArrayBuffer,xp=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Mp=({type:e,data:t},r,n)=>Ip&&t instanceof Blob?r?n(t):jp(t,n):Dp&&(t instanceof ArrayBuffer||xp(t))?r?n(t):jp(new Blob([t]),n):n(Pp[e]+(t||"")),jp=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Lp(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Ap;const Np="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bp="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let aO=0;aO<64;aO++)Bp[Np.charCodeAt(aO)]=aO;const Fp="function"==typeof ArrayBuffer,zp=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Up(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Vp(e.substring(1),t)};return Ep[r]?e.length>1?{type:Ep[r],data:e.substring(1)}:{type:Ep[r]}:Op},Vp=(e,t)=>{if(Fp){const r=(e=>{let t,r,n,i,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=Bp[e.charCodeAt(t)],n=Bp[e.charCodeAt(t+1)],i=Bp[e.charCodeAt(t+2)],s=Bp[e.charCodeAt(t+3)],l[c++]=r<<2|n>>4,l[c++]=(15&n)<<4|i>>2,l[c++]=(3&i)<<6|63&s;return d})(e);return Up(r,t)}return{base64:!0,data:e}},Up=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,$p=String.fromCharCode(30);function Gp(){return new TransformStream({transform(e,t){!function(e,t){Ip&&e.data instanceof Blob?e.data.arrayBuffer().then(Lp).then(t):Dp&&(e.data instanceof ArrayBuffer||xp(e.data))?t(Lp(e.data)):Mp(e,!1,(e=>{Ap||(Ap=new TextEncoder),t(Ap.encode(e))}))}(e,(r=>{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(r)}))}})}let qp;function Hp(e){return e.reduce(((e,t)=>e+t.length),0)}function Wp(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;i<t;i++)r[i]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),r}function Kp(e){if(e)return function(e){for(var t in Kp.prototype)e[t]=Kp.prototype[t];return e}(e)}Kp.prototype.on=Kp.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Kp.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Kp.prototype.off=Kp.prototype.removeListener=Kp.prototype.removeAllListeners=Kp.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},Kp.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},Kp.prototype.emitReserved=Kp.prototype.emit,Kp.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Kp.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Jp="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Qp(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Xp=Jp.setTimeout,Yp=Jp.clearTimeout;function Zp(e,t){t.useNativeTimers?(e.setTimeoutFn=Xp.bind(Jp),e.clearTimeoutFn=Yp.bind(Jp)):(e.setTimeoutFn=Jp.setTimeout.bind(Jp),e.clearTimeoutFn=Jp.clearTimeout.bind(Jp))}class eh extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class th extends Kp{constructor(e){super(),this.writable=!1,Zp(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new eh(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=zp(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 rh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),nh=64,ih={};let sh,oh=0,ah=0;function ch(e){let t="";do{t=rh[e%nh]+t,e=Math.floor(e/nh)}while(e>0);return t}function dh(){const e=ch(+new Date);return e!==sh?(oh=0,sh=e):e+"."+ch(oh++)}for(;ah<nh;ah++)ih[rh[ah]]=ah;let lh=!1;try{lh="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(cO){}const uh=lh;function ph(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||uh))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Jp[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function hh(){}const fh=null!=new ph({xdomain:!1}).responseType;class mh extends Kp{constructor(e,t){super(),Zp(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 e;const t=Qp(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new ph(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=mh.requestsCount++,mh.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=hh,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete mh.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(mh.requestsCount=0,mh.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",gh);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Jp?"pagehide":"unload",gh,!1)}function gh(){for(let e in mh.requests)mh.requests.hasOwnProperty(e)&&mh.requests[e].abort()}const vh="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),bh=Jp.WebSocket||Jp.MozWebSocket,yh="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const wh={websocket:class extends th{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=yh?{}:Qp(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=yh?new bh(e,t,r):t?new bh(e,t):new bh(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],n=t===e.length-1;Mp(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}n&&vh((()=>{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]=dh()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!bh}},webtransport:class extends th{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){qp||(qp=new TextDecoder);const r=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===n){if(Hp(r)<1)break;const e=Wp(r,1);s=128==(128&e[0]),i=127&e[0],n=i<126?3:126===i?1:2}else if(1===n){if(Hp(r)<2)break;const e=Wp(r,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(Hp(r)<8)break;const e=Wp(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){a.enqueue(Op);break}i=s*Math.pow(2,32)+t.getUint32(4),n=3}else{if(Hp(r)<i)break;const e=Wp(r,i);a.enqueue(zp(s?e:qp.decode(e),t)),n=0}if(0===i||i>e){a.enqueue(Op);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),n=Gp();n.readable.pipeTo(e.writable),this.writer=n.writable.getWriter();const i=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),i())})).catch((e=>{}))};i();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],n=t===e.length-1;this.writer.write(r).then((()=>{n&&vh((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends th{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=fh&&!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($p),n=[];for(let e=0;e<r.length;e++){const i=zp(r[e],t);if(n.push(i),"error"===i.type)break}return n})(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,n=new Array(r);let i=0;e.forEach(((e,s)=>{Mp(e,!1,(e=>{n[s]=e,++i===r&&t(n.join($p))}))}))})(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]=dh()),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 mh(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}}},_h=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Sh=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ch(e){if(e.length>2e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");-1!=r&&-1!=n&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=_h.exec(e||""),s={},o=14;for(;o--;)s[Sh[o]]=i[o]||"";return-1!=r&&-1!=n&&(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,n=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,s.path),s.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(r[t]=n)})),r}(0,s.query),s}let Rh=class e extends Kp{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Ch(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=Ch(t.host).host),Zp(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,n=r.length;e<n;e++){let n=r[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[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 wh[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),n=!1;e.priorWebsocketSuccess=!1;const i=()=>{n||(r.send([{type:"ping",data:"probe"}]),r.once("packet",(t=>{if(!n)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((()=>{n||"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(){n||(n=!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",i),r.removeListener("error",o),r.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};r.once("open",i),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((()=>{n||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 r=0;r<this.writeBuffer.length;r++){const n=this.writeBuffer[r].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,r=0;for(let n=0,i=e.length;n<i;n++)t=e.charCodeAt(n),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(n++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;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,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),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 n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}};Rh.protocol=4;const Th="function"==typeof ArrayBuffer,kh=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Ph=Object.prototype.toString,Eh="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ph.call(Blob),Oh="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ph.call(File);function Ih(e){return Th&&(e instanceof ArrayBuffer||kh(e))||Eh&&e instanceof Blob||Oh&&e instanceof File}function Dh(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Dh(e[t]))return!0;return!1}if(Ih(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Dh(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Dh(e[t]))return!0;return!1}function xh(e){const t=[],r=e.data,n=e;return n.data=Mh(r,t),n.attachments=t.length,{packet:n,buffers:t}}function Mh(e,t){if(!e)return e;if(Ih(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 n=0;n<e.length;n++)r[n]=Mh(e[n],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=Mh(e[n],t));return r}return e}function jh(e,t){return e.data=Lh(e.data,t),delete e.attachments,e}function Lh(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]=Lh(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Lh(e[r],t));return e}const Ah=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Nh;!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"}(Nh||(Nh={}));function Bh(e){return"[object Object]"===Object.prototype.toString.call(e)}class Fh extends Kp{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===Nh.BINARY_EVENT;r||t.type===Nh.BINARY_ACK?(t.type=r?Nh.EVENT:Nh.ACK,this.reconstructor=new zh(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Ih(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===Nh[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Nh.BINARY_EVENT||r.type===Nh.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=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(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Fh.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Nh.CONNECT:return Bh(t);case Nh.DISCONNECT:return void 0===t;case Nh.CONNECT_ERROR:return"string"==typeof t||Bh(t);case Nh.EVENT:case Nh.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ah.indexOf(t[0]));case Nh.ACK:case Nh.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class zh{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=jh(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Vh=Object.freeze({__proto__:null,Decoder:Fh,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Nh.EVENT&&e.type!==Nh.ACK||!Dh(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Nh.EVENT?Nh.BINARY_EVENT:Nh.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Nh.BINARY_EVENT&&e.type!==Nh.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=xh(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}},get PacketType(){return Nh},protocol:5});function Uh(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const $h=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Gh extends Kp{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=[Uh(e,"open",this.onopen.bind(this)),Uh(e,"packet",this.onpacket.bind(this)),Uh(e,"error",this.onerror.bind(this)),Uh(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($h.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:Nh.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const n=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const i=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"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{t.push(((e,t)=>r?e?i(e):n(t):n(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,...n)=>{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,...n)),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:Nh.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 Nh.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 Nh.EVENT:case Nh.BINARY_EVENT:this.onevent(e);break;case Nh.ACK:case Nh.BINARY_ACK:this.onack(e);break;case Nh.DISCONNECT:this.ondisconnect();break;case Nh.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(...n){r||(r=!0,t.packet({type:Nh.ACK,id:e,data:n}))}}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:Nh.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 qh(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}qh.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=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},qh.prototype.reset=function(){this.attempts=0},qh.prototype.setMin=function(e){this.ms=e},qh.prototype.setMax=function(e){this.max=e},qh.prototype.setJitter=function(e){this.jitter=e};class Hh extends Kp{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,Zp(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 qh({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||Vh;this.encoder=new n.Encoder,this.decoder=new n.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 Rh(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=Uh(t,"open",(function(){r.onopen(),e&&e()})),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=Uh(t,"error",i);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{n(),i(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(n),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(Uh(e,"ping",this.onping.bind(this)),Uh(e,"data",this.ondata.bind(this)),Uh(e,"error",this.onerror.bind(this)),Uh(e,"close",this.onclose.bind(this)),Uh(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){vh((()=>{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 Gh(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 Wh={};function Kh(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=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),n=Ch(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=Wh[i]&&s in Wh[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Hh(n,t):(Wh[i]||(Wh[i]=new Hh(n,t)),a=Wh[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(Kh,{Manager:Hh,Socket:Gh,io:Kh,connect:Kh});const Jh=new URLSearchParams(window.location.search).has("debug");class Qh{constructor(){this._isEnabled=!1,this._isEnabled=Jh}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 Xh(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError,hn.default;const Yh={id:Sn(),connectionNumber:0},Zh=()=>{};let ef=Zh;const tf=function(e,t=console){const r=[];let n,i,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==n||n.close()),r&&(g=!0)}else"customEvent"===e[0]&&"clientId"===e[2].type?s=e:"customEvent"===e[0]&&"organizationId"===e[2].type?i=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==n?void 0:n.readyState)===WebSocket.OPEN?(m=0,n.send(JSON.stringify(e))):"getstats"===e[0]?v<20&&(v++,r.push(e)):"customEvent"===e[0]&&"insightsStats"===e[2].type||r.push(e),(null==n?void 0:n.readyState)===WebSocket.CLOSED&&d&&setTimeout((()=>{n.readyState===WebSocket.CLOSED&&d&&b.connect()}),1e3*m)},close:()=>{d=!1,null==n||n.close()},connect:()=>{d=!0,m+=1,null==n||n.close(),b.connected=!0,n=new WebSocket(e+window.location.pathname,"1.0"),n.onerror=e=>{b.connected=!1,t.warn("[RTCSTATS] WebSocket error",e)},n.onclose=e=>{b.connected=!1,t.info(`[RTCSTATS] Closed ${e.code}`),ef()},n.onopen=()=>{for(Yh.connectionNumber++,n.send(JSON.stringify(["clientInfo",null,Yh])),i&&n.send(JSON.stringify(i)),s&&n.send(JSON.stringify(s)),c&&n.send(JSON.stringify(c)),o&&n.send(JSON.stringify(o)),a&&n.send(JSON.stringify(a)),l&&n.send(JSON.stringify(l)),p&&n.send(JSON.stringify(p)),u&&n.send(JSON.stringify(u)),h&&n.send(JSON.stringify(h)),f&&n.send(JSON.stringify(f));r.length;)n.send(JSON.stringify(r.shift()));v=0}}};return b}("wss://rtcstats.srv.whereby.com"),rf=gn(tf.trace,1e4,[""]);ef=(null==rf?void 0:rf.resetDelta)||Zh;const nf={sendEvent:(e,t)=>{tf.trace("customEvent",null,{type:e,value:t})},sendAudioMuted:e=>{nf.sendEvent("audio_muted",{muted:e})},sendVideoMuted:e=>{nf.sendEvent("video_muted",{muted:e})},server:tf};let sf=[],of=0;const af=new WeakMap,cf=e=>{sf=sf.filter((t=>t!==e))};if(window.RTCPeerConnection){const dO=window.RTCPeerConnection;function lO(e){const t=new dO(e);sf.push(t),af.set(t,{index:of++});const r=()=>{"closed"===t.connectionState&&(cf(t),t.removeEventListener("connectionstatechange",r))};return t.addEventListener("connectionstatechange",r),t}lO.prototype=dO.prototype,window.RTCPeerConnection=lO}const df=e=>{var t;return null===(t=af.get(e))||void 0===t?void 0:t.index},lf=new WeakMap;const uf=()=>Promise.all(sf.map((e=>Xh(void 0,void 0,void 0,(function*(){let t=lf.get(e);t||(t={ssrcToTrackId:{}},lf.set(e,t));try{const r=yield e.getStats();let n=null;if(r.forEach((e=>{if(!("inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||e.trackIdentifier||t.ssrcToTrackId[e.ssrc])){if(e.mediaSourceId){const n=r.get(e.mediaSourceId);n&&n.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=n.trackIdentifier)}if(!t.ssrcToTrackId[e.ssrc]&&e.trackId){const n=r.get(e.trackId);n&&n.trackIdentifier&&(t.ssrcToTrackId[e.ssrc]=n.trackIdentifier)}t.ssrcToTrackId[e.ssrc]||(n||(n=[]),n.push(e.ssrc))}})),n){const r=[...e.getSenders(),...e.getReceivers()];(yield Promise.all(r.map((e=>e.getStats())))).forEach(((e,n)=>{e.forEach((e=>{"inbound-rtp"!==e.type&&"outbound-rtp"!==e.type||(t.ssrcToTrackId[e.ssrc]=r[n].track.id)}))})),n.forEach((e=>{t.ssrcToTrackId[e]||(t.ssrcToTrackId[e]="?"+e)}))}return[e,r,t]}catch(r){return nf.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]}}))))),pf=(e,t,r,n,i,s)=>{let o=e[n];o||(o={tracks:{},startTime:t,updated:t},e[n]=o),o.updated=t;let a=o.tracks[i];a||(a={ssrcs:{},startTime:t,updated:t},o.tracks[i]=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},hf=(e,t)=>{Object.entries(e).forEach((([r,n])=>{n.updated<t?delete e[r]:Object.entries(n.tracks).forEach((([e,r])=>{r.updated<t?delete n.tracks[e]:Object.entries(r.ssrcs).forEach((([e,n])=>{n.updated<t&&delete r.ssrcs[e]}))}))}))};function ff(e,{logger:t,interval:r},n){return Xh(this,void 0,void 0,(function*(){const i=ff.bind(null,e,{interval:r,logger:t});try{const t=e.getClients(),s=t.find((e=>e.isLocalClient&&!e.isPresentation))||{id:"unknown"};let o=e.statsByView[s.id];o||(o={tracks:{},candidatePairs:{},pressure:null},e.statsByView[s.id]=o),o.pressure=e.lastPressureObserverRecord;if(Date.now()-e.lastUpdateTime<400)return n?e.statsByView:(e.subscriptions.forEach((r=>{var n;return null===(n=r.onUpdatedStats)||void 0===n?void 0:n.call(r,e.statsByView,t)})),void(e.nextTimeout=setTimeout(i,r)));if(e.lastUpdateTime=Date.now(),(yield uf()).forEach((([n,i,a])=>{const c=df(n);"closed"===n.connectionState&&(i=new Map,cf(n)),a.previousSSRCs=a.currentSSRCs||{},a.currentSSRCs={},i.forEach((n=>{var d,l,u;if("candidate-pair"===n.type&&/inprogress|succeeded/.test(n.state)){const t=null===(d=a._oldReport)||void 0===d?void 0:d.get(n.id),s=t?n.timestamp-t.timestamp:r,l=c+":"+n.id;let u=o.candidatePairs[l];u||(u={startTime:e.lastUpdateTime,id:l},o.candidatePairs[l]=u),function(e,t,r,n,i){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/n,e.bitrateOut=8e3*o/n,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=i.get(t.remoteCandidateId),c=i.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,n,t,s,i),u.lastRtcStatsTime=e.lastUpdateTime}if("inbound-rtp"===n.type||"outbound-rtp"===n.type){const o=n.mediaType||n.kind,d=n.ssrc;let p=n.trackIdentifier||a.ssrcToTrackId[d],h=null===(l=a._oldReport)||void 0===l?void 0:l.get(n.id);if(h&&h.mediaSourceId!==n.mediaSourceId){const e=i.get(n.mediaSourceId);e&&e.trackIdentifier&&(p=e.trackIdentifier,a.ssrcToTrackId[d]=p)}const f=t.find((e=>{var t;return(null===(t=e[o].track)||void 0===t?void 0:t.id)===p}))||s;if(!n.trackIdentifier&&a.ssrcToTrackId[d]&&(null===(u=f[o].track)||void 0===u?void 0:u.id)&&f[o].track.id!==a.ssrcToTrackId[d]&&(p=f[o].track.id,a.ssrcToTrackId[d]=f[o].track.id),a.currentSSRCs[d]=f.id,h){const e=i.get(n.transportId),t=a._oldReport.get(h.transportId);(t&&(null==e?void 0:e.selectedCandidatePairId)!==t.selectedCandidatePairId||n.bytesReceived<h.bytesReceived||n.bytesSent<h.bytesSent)&&(h=null)}const m=h?n.timestamp-h.timestamp:r,g=pf(e.statsByView,e.lastUpdateTime,c,f.id,p,d);!function(e,t,r,n,i){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&&i.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,n,0,0,i),function(e,t,r,n,i){const s=(t.nackCount||0)-((null==r?void 0:r.nackCount)||0);if(e.nackCount=(e.nackCount||0)+s,e.nackRate=1e3*s/n,"in"===e.direction){const i=t.packetsReceived-((null==r?void 0:r.packetsReceived)||0);e.packetCount=(e.packetCount||0)+i,e.packetRate=1e3*i/n;const s=t.packetsLost-((null==r?void 0:r.packetsLost)||0);e.packetLossCount=(e.packetLossCount||0)+s,e.packetLossRate=1e3*s/n,e.lossRatio=s/(s+i)*1e3/n;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/n,e.mediaRatio=o/c,"audio"===t.kind){const n=(t.fecBytesReceived||0)-((null==r?void 0:r.fecBytesReceived)||0);e.fecRatio=n/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/n;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/n,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/n,t.remoteId){const r=i.get(t.remoteId);r&&(e.roundTripTime=r.roundTripTime||0,e.jitter=r.jitter||0,e.fractionLost=r.fractionLost||0)}}}(g,n,h,m,i),"video"===o&&function(e,t,r,n,i){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/n;const o=t.firCount-((null==r?void 0:r.firCount)||0);if(e.firCount=(e.firCount||0)+o,e.firRate=1e3*o/n,"in"===e.direction){const i=t.keyFramesDecoded-((null==r?void 0:r.keyFramesDecoded)||0);e.kfCount=(e.kfCount||0)+i,e.kfRate=1e3*i/n;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/n}else{const s=t.keyFramesEncoded-((null==r?void 0:r.keyFramesEncoded)||0);e.kfCount=(e.kfCount||0)+s,e.kfRate=1e3*s/n;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/n;const c=t.totalEncodeTime-((null==r?void 0:r.totalEncodeTime)||0);if(e.encodeTime=c/o,t.mediaSourceId){const r=i.get(t.mediaSourceId);r&&(e.sourceWidth=r.width||0,e.sourceHeight=r.height||0,e.sourceFps=r.framesPerSecond||0)}}}(g,n,h,m,i),"audio"===o&&function(e,t,r,n,i){const s=t.packetsDiscarded-((null==r?void 0:r.packetsDiscarded)||0);if(e.packetsDiscarded=(e.packetsDiscarded||0)+s,"in"===e.direction){const n=t.totalAudioEnergy-((null==r?void 0:r.totalAudioEnergy)||0),i=t.totalSamplesDuration-((null==r?void 0:r.totalSamplesDuration)||0);e.audioLevel=Math.sqrt(n/i);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,n,h)}})),a._oldReport=i,Object.keys(a.previousSSRCs).filter((e=>!a.currentSSRCs[e])).forEach((t=>{const r=a.previousSSRCs[t];if(r){const n=e.statsByView[r];n&&Object.values(n.tracks).forEach((e=>{e.ssrcs[t]&&delete e.ssrcs[t]}))}}))})),hf(e.statsByView,e.lastUpdateTime),Object.entries((null==o?void 0:o.candidatePairs)||{}).forEach((([t,r])=>{const n=r.lastRtcStatsTime===e.lastUpdateTime;r.active=n,n||(r.state="old/inactive",r.inactiveFromTime?e.lastUpdateTime-r.inactiveFromTime>4e3&&delete o.candidatePairs[t]:r.inactiveFromTime=e.lastUpdateTime)})),n)return e.statsByView;e.subscriptions.forEach((r=>{var n;return null===(n=r.onUpdatedStats)||void 0===n?void 0:n.call(r,e.statsByView,t)}))}catch(r){t.warn(r),e.numFailedStatsReports++,nf.sendEvent("collectStatsFailed",{name:null==r?void 0:r.name,cause:null==r?void 0:r.cause,message:null==r?void 0:r.message})}e.nextTimeout=setTimeout(i,r)}))}const mf={};function gf(e,t=mf,r=window.document){e.forEach((({hostnamePattern:e,token:n})=>{const i=`${e}-${n}`;if(!t[i]&&e.test(r.location.hostname)){const e=r.createElement("meta");e.httpEquiv="origin-trial",e.content=n,r.head.append(e),t[i]=!0}}))}const vf={sampleRate:1,originTrials:[{hostnamePattern:/hereby\.dev/,token:"AkSNPHJw6EK08X0QU7kORnK9NABzRLAC7dqfXOwk5JwFAQG4Ey7WxLXxsnhieCgC1QHUdevE2EFICy7uBGDANwUAAABqeyJvcmlnaW4iOiJodHRwczovL2hlcmVieS5kZXY6NDQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="},{hostnamePattern:/whereby\.com/,token:"Asc2wu8KpSx648i932NICteQDFcB05yl2QUUSHD7AQo8JGP2Fp6FF91TvYVJBsKGzLMH349rysPw5q9tqPC/PAUAAABqeyJvcmlnaW4iOiJodHRwczovL3doZXJlYnkuY29tOjQ0MyIsImZlYXR1cmUiOiJDb21wdXRlUHJlc3N1cmVfdjIiLCJleHBpcnkiOjE3MTY5NDA3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="}]};const bf={currentMonitor:null,getClients:()=>[],lastUpdateTime:0,statsByView:{},subscriptions:[],numFailedStatsReports:0},yf={interval:2e3,logger:new Qh},wf=()=>{var e;return null===(e=bf.currentMonitor)||void 0===e?void 0:e.getUpdatedStats()};function _f(e,{interval:t,logger:r}){const n=ff.bind(null,e,{interval:t,logger:r});let i;try{i=function(e,{sampleRate:t,originTrials:r}=vf,n=globalThis.window){let i;if(gf(r),"PressureObserver"in n)return i=new n.PressureObserver(e,{sampleRate:t}),i.observe("cpu",{sampleInterval:1e3*t}),{stop:()=>{i.unobserve("cpu")}}}((t=>e.lastPressureObserverRecord=t.pop()))}catch(e){r.warn("Failed to observe CPU pressure",e)}return setTimeout(n,t),{getUpdatedStats:()=>n(!0),stop:()=>{clearTimeout(e.nextTimeout),i&&i.stop()}}}var Sf;const Cf=null!==(Sf=hn.default)&&void 0!==Sf?Sf:hn,Rf=new Qh,Tf=Cf.browserDetails.browser,kf=Cf.browserDetails.version;function Pf(e,t){let r=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),n=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+)/),n=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(n[e],"g"),r[e]);return t}function Ef(e){return"firefox"!==Tf?e:tn.splitLines(e.trim()).map((e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e)).join("\r\n")+"\r\n"}function Of(e){return function(e,t,r=!1,n=!1){var i,s;try{const o=An(e);if((null===(i=null==o?void 0:o.ext)||void 0===i?void 0:i.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 i;(r&&"audio"===e.type||n&&"video"===e.type)&&((null===(i=e.ext)||void 0===i?void 0:i.find((e=>e.uri===t)))||(Array.isArray(e.ext)?e.ext.push({value:c,uri:t}):e.ext=[{value:c,uri:t}]))})),Ln(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 If(e,t,r=console){const n=e.getSenders().find((e=>e.track&&"video"===e.track.kind));if(!n)return Promise.resolve();const i=n.getParameters();return i.encodings&&0===i.encodings.length?Promise.resolve():(i.encodings||(i.encodings=[{}]),0===t?delete i.encodings[0].maxBitrate:i.encodings[0].maxBitrate=1e3*t,n.setParameters(i).catch((e=>{r.error("setParameters err: ",e)})))}const Df=400;var xf;const Mf=null!==(xf=hn.default)&&void 0!==xf?xf:hn,jf=new Qh;class Lf{constructor({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:r,deprioritizeH264Encoding:n}){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=n}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:r,shouldAddLocalVideo:n}){return this.peerConnectionConfig=r,this.shouldAddLocalVideo=n,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 tn.splitSections(e).map((e=>{if("video"!==tn.getKind(e))return e;const t=tn.matchPrefix(e,"a=rtpmap:").map((e=>tn.parseRtpMap(e))).filter((e=>/h264/i.test(e.name))).map((e=>""+e.payloadType));if(!t.length)return e;const r=tn.matchPrefix(e,"m=video")[0],n=/(\s\d+)+$/i.exec(r),i=n?n[0]:"",s=[...i.split(" ").filter((e=>e&&!t.includes(e))),...t].join(" "),o=r.replace(i," "+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"!==Tf&&("firefox"!==Tf||kf&&kf>=63||60===kf)?e:tn.splitLines(e.trim()).filter((e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==tn.parseExtmap(e).uri)).join("\r\n")+"\r\n"}(t),t=Ef(t);const r={type:e.type,sdp:t};let n;return this._setRemoteDescription(r).then((()=>this.pc.createAnswer())).then((e=>(n=e,this.pc.setLocalDescription(e)))).then((()=>If(this.pc,this.bandwidth))).then((()=>n))}handleAnswer(e){const t=Ef(e.sdp),r={type:e.type,sdp:t};return this._setRemoteDescription(r).then((()=>If(this.pc,this.bandwidth)),(e=>{jf.warn("Could not set remote description from remote answer: ",e)}))}addIceCandidate(e){this.srdComplete?this.srdComplete.then((()=>{"closed"!==this.pc.signalingState&&("safari"===Mf.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch((t=>{jf.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){jf.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 n=r.getSenders();if(e||(e=(n.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<n.length;r++){const i=n[r].track;if((null==i?void 0:i.id)===t.id)return Promise.resolve(t);if((null==i?void 0:i.id)===e.id)return n[r].replaceTrack(t)}return null};let i=r();if(i)return i;let s=null,o=null;i=new Promise(((e,t)=>{s=e,o=t}));let a=0,c=setInterval((()=>Xh(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 i}const i=this.streams.find((e=>e.getTracks().find((e=>e.id===t.id))))||this.streams[0];return i?r.addTrack(t,i):Promise.reject(new Error("replaceTrack: No stream?"))}if(!this.canModifyPeerConnection())return void this.pending.push((()=>{this.replaceTrack(e,t)}));this.isOperationPending=!0;const i=r.onnegotiationneeded;return r.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout((()=>{r.onnegotiationneeded=i}),0),"offer"===r.localDescription.type?r.createOffer().then((e=>(e.sdp=Pf(r.localDescription.sdp,e.sdp),r.setLocalDescription(e)))).then((()=>this._setRemoteDescription(r.remoteDescription))):this._setRemoteDescription(r.remoteDescription).then((()=>r.createAnswer())).then((e=>(e.sdp=Pf(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((n=>{if("transport"===n.type&&n.selectedCandidatePairId){const i=e.get(n.selectedCandidatePairId);if(!i)return;return t=e.get(i.localCandidateId).candidateType,void(r=e.get(i.remoteCandidateId).candidateType)}"candidate-pair"===n.type&&n.selected&&(t=e.get(n.localCandidateId).candidateType,r=e.get(n.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&&If(this.pc,this.bandwidth)):this.pending.push((()=>this.changeBandwidth(e))))}setAudioOnly(e,t=[]){this.pc.getTransceivers().filter((e=>{var r,n,i,s,o,a;return"recvonly"!==(null==e?void 0:e.direction)&&"video"===(null===(n=null===(r=null==e?void 0:e.receiver)||void 0===r?void 0:r.track)||void 0===n?void 0:n.kind)&&!t.includes(null===(s=null===(i=null==e?void 0:e.receiver)||void 0===i?void 0:i.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 Af;const Nf=null!==(Af=hn.default)&&void 0!==Af?Af:hn;const Bf="fetch_mediaserver_config",Ff="start_screenshare",zf="stop_screenshare",Vf="audio_enabled",Uf="client_left",$f="mediaserver_config",Gf="new_client",qf="screenshare_started",Hf="screenshare_stopped",Wf="room_joined",Kf="video_enabled",Jf="ice_candidate",Qf="ice_endofcandidates",Xf="ready_to_receive_offer",Yf="sdp_answer",Zf="sdp_offer",em="pending_client_left",tm="media_quality_changed",rm="client_connection_status_changed",nm="stream_added",im="rtc_manager_created",sm="rtc_manager_destroyed",om="local_stream_track_added",am="local_stream_track_removed",cm="connecting",dm="connection_failed",lm="connection_successful",um="connection_disconnected",pm="camera",hm="screen_share";const fm=57600,mm=2.6041666666666665,gm=921600,vm=1.0850694444444444;const bm="[a-fA-F\\d:]",ym=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${bm})|(?<=${bm})(?=\\s|$))`:"",wm="(?: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}",_m="[a-fA-F\\d]{1,4}",Sm=`\n(?:\n(?:${_m}:){7}(?:${_m}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${_m}:){6}(?:${wm}|:${_m}|:)| // 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(?:${_m}:){5}(?::${wm}|(?::${_m}){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(?:${_m}:){4}(?:(?::${_m}){0,1}:${wm}|(?::${_m}){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(?:${_m}:){3}(?:(?::${_m}){0,2}:${wm}|(?::${_m}){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(?:${_m}:){2}(?:(?::${_m}){0,3}:${wm}|(?::${_m}){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(?:${_m}:){1}(?:(?::${_m}){0,4}:${wm}|(?::${_m}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${_m}){0,5}:${wm}|(?::${_m}){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(),Cm=new RegExp(`(?:^${wm}$)|(?:^${Sm}$)`),Rm=new RegExp(`^${wm}$`),Tm=new RegExp(`^${Sm}$`),km=e=>e&&e.exact?Cm:new RegExp(`(?:${ym(e)}${wm}${ym(e)})|(?:${ym(e)}${Sm}${ym(e)})`,"g");km.v4=e=>e&&e.exact?Rm:new RegExp(`${ym(e)}${wm}${ym(e)}`,"g"),km.v6=e=>e&&e.exact?Tm:new RegExp(`${ym(e)}${Sm}${ym(e)}`,"g");var Pm,Em,Om="connection_blocked_by_network",Im="ice_ipv6_seen",Dm="ice_mdns_seen",xm="ice_no_public_ip_gathered",Mm="ice_no_public_ip_gathered_3sec",jm="ice_restart",Lm="microphone_not_working",Am="microphone_stopped_working",Nm="camera_stopped_working",Bm="new_pc",Fm="sfu_connection_open",zm="sfu_connection_closed",Vm="dominant_speaker",Um="pc_sld_failure",$m="pc_on_answer_failure",Gm="pc_on_offer_failure";const qm=null!==(Pm=hn.default)&&void 0!==Pm?Pm:hn,Hm=new Qh,Wm=class{constructor(e,t){this.id=""+e,this.type=t,this.isEnabled=!0,this.hasSupportForAutoSuperSize=!1,this.isAudioEnabled=!0,this.isVideoEnabled=!0,this.status=cm,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?pm:hm}}.getCameraId(),Km=qm.browserDetails.browser,Jm=qm.browserDetails.version;"firefox"===Km&&qm.browserShim&&"shimGetDisplayMedia"in qm.browserShim&&(null===(Em=qm.browserShim)||void 0===Em||Em.shimGetDisplayMedia(window,"screen"));let Qm=!1;"chrome"===Km&&window.document.addEventListener("beforeunload",(()=>{Qm=!0}));class Xm{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s}){const{name:o,session:a,iceServers:c,sfuServer:d,mediaserverConfigTtlSeconds:l}=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=n,this._webrtcProvider=i,this._features=s||{},this._isAudioOnlyMode=!1,this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._audioTrackOnEnded=()=>{nf.sendEvent("audio_ended",{unloading:Qm}),this._emit(Am,{})},this._videoTrackOnEnded=()=>{nf.sendEvent("video_ended",{unloading:Qm}),this._emit(Nm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:d,iceServers:c.iceServers||[],mediaserverConfigTtlSeconds:l}),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,n,i=[]){if(t!==this.localStreams[e]){if(this._addLocalStream(e,t),e===Wm){this._addStreamToPeerConnections(t);const e=t.getAudioTracks()[0],r=t.getVideoTracks()[0];if(e){e.effectTrack||this._monitorAudioTrack(e);const t=i.find((e=>"audio"===e.kind));t&&this._monitorAudioTrack(t)}if(r){r.effectTrack||this._monitorVideoTrack(r);const e=i.find((e=>"video"===e.kind));e&&this._monitorVideoTrack(e)}this._localStreamDeregisterFunction&&(this._localStreamDeregisterFunction(),this._localStreamDeregisterFunction=null);const n=e=>{const{enable:t,track:r}=e.detail;this._handleStopOrResumeVideo({enable:t,track:r})};return t.addEventListener("stopresumevideo",n),void(this._localStreamDeregisterFunction=()=>{t.removeEventListener("stopresumevideo",n)})}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"!==Km)return;const t=this._getLocalCameraStream(),r=t.getAudioTracks()[0];return r&&"ended"===r.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then((e=>{const n=e.getAudioTracks()[0];return n.enabled=r.enabled,t.removeTrack(r),t.addTrack(n),this.replaceTrack(r,n)})):void 0}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on($f,(e=>{e.error?Hm.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(Xf,(e=>{this._connect(e.clientId)})),this._serverSocket.on(Jf,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):Hm.warn("No RTCPeerConnection on ICE_CANDIDATE",e)})),this._serverSocket.on(Qf,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):Hm.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)})),this._serverSocket.on(Zf,(e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Hm.warn("No RTCPeerConnection on SDP_OFFER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=(t=n.handleOffer(i).then((t=>{this._emitServerEvent(Yf,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})}))).catch)||void 0===r||r.call(t,(e=>{this._emit(Gm,e)}))})),this._serverSocket.on(Yf,(e=>{var t,r;const n=this._getSession(e.clientId);if(!n)return void Hm.warn("No RTCPeerConnection on SDP_ANSWER",e);const i=this._transformIncomingSdp(e.message,n.pc);null===(r=null===(t=n.handleAnswer(i))||void 0===t?void 0:t.catch)||void 0===r||r.call(t,(e=>{this._emit($m,e)}))})),this._serverSocket.on(Wf,(({room:{sfuServer:e}})=>{if(e||!this._wasScreenSharing)return;const t=Object.keys(this.localStreams).find((e=>e!==Wm));if(!t)return;const r=this.localStreams[t];if(!r)return void Hm.warn("screenshare stream %s not found",t);const n=r.getAudioTracks().length>0;this._emitServerEvent(Ff,{streamId:t,hasAudioTrack:n})}))]}sendAudioMutedStats(e){nf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nf.sendEvent(e,t)}rtcStatsDisconnect(){nf.server.close()}rtcStatsReconnect(){nf.server.connected||nf.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 n=e.connectionStatus;n!==t&&e.peerConnectionId!==this._selfId&&(n===um&&t===cm||(e.connectionStatus=t,setTimeout((()=>{this._emit(rm,{streamIds:e.streamIds,clientId:r,status:t,previous:n})}),0)))}_setJitterBufferTarget(e){try{e.getReceivers().forEach((e=>{e.jitterBufferTarget=Df,e.playoutDelayHint=.4}))}catch(e){Hm.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 n="safari"===Km&&Jm&&Jm>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=r=new Lf({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:this._features.unlimitedBandwidthWhenUsingRelayP2POn?-1:1280,deprioritizeH264Encoding:n}),this.totalSessionsCreated++}return r}_getLocalCameraStream(){return this.localStreams[Wm]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter((e=>e!==Wm))}_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:n,shouldAddLocalVideo:i}){if(!n)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const s=this._getOrCreateSession(n,t),o={optional:[]};"chrome"===Km&&o.optional.push({googCpuOveruseDetection:!0}),o.optional.push({rtcStatsRoomSessionId:this._roomSessionId}),o.optional.push({rtcStatsClientId:this._selfId}),o.optional.push({rtcStatsPeerId:n}),o.optional.push({rtcStatsConferenceId:this._roomName});const a={iceServers:this._iceServers};if(this._features.turnServerOverrideHost){const e=this._features.turnServerOverrideHost,t=e.indexOf(":")>0?"":":443",r=":"+e+t;a.iceServers=a.iceServers.map((e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,r)),t.urls&&(t.urls=t.urls.map((e=>e.replace(/:[^?]*/,r)))),t}))}if(this._features.addGoogleStunServers&&(a.iceServers=[...a.iceServers,{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun2.l.google.com:19302"}]),this._features.addCloudflareStunServers&&(a.iceServers=[...a.iceServers,{urls:"stun:stun.cloudflare.com:3478"},{urls:"stun:stun.cloudflare.com:53"}]),this._features.useOnlyTURN){a.iceTransportPolicy="relay";const e={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[this._features.useOnlyTURN];e&&(a.iceServers=a.iceServers.filter((t=>t.url&&t.url.match(e))))}"chrome"===Km&&(a.sdpSemantics="unified-plan");const c=s.setAndGetPeerConnection({constraints:o,peerConnectionConfig:a,shouldAddLocalVideo:i,clientId:e});setTimeout((()=>this._emit(Bm)),0),c.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(nm,{clientId:e,stream:r}),s.connectionStatus===lm&&setTimeout((()=>{this._emit(rm,{streamIds:s.streamIds,clientId:e,status:s.connectionStatus,previous:cm})}),0))},c.oniceconnectionstatechange=()=>{let t;const r=s.connectionStatus;switch(c.iceConnectionState){case"checking":t=cm;break;case"connected":case"completed":t=lm,s.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach((e=>{"function"==typeof e&&e()})),this._pendingActionsForConnectedPeerConnections=[]),!s.wasEverConnected&&(c.iceConnectionState.match(/connected|completed/)||"chrome"===Km&&c.localDescription&&"answer"===c.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=um,setTimeout((()=>{"disconnected"===c.iceConnectionState&&this._maybeRestartIce(e,s)}),2e3);break;case"failed":t=dm,r!==t&&this._maybeRestartIce(e,s),null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Om);break;default:return}this._setConnectionStatus(s,t,e)},c.onconnectionstate=()=>{switch(c.connectionState){case"connected":setTimeout((()=>{(function(e){if("chrome"!==Nf.browserDetails.browser||Nf.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 n=!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&&(n="inbound"):0===e.bytesSent&&(n="outbound")})),n}))})(s.pc).then((t=>{!1!==t&&this._emit(Lm,{failureDirection:t,clientId:e})}))}),3e3),s.registerConnected();break;case"failed":const t=dm;null!==s.relayCandidateSeen||s.wasEverConnected||this._emit(Om),this._setConnectionStatus(s,t,e)}};const d=this.localStreams[Wm];return i&&d&&s.addStream(d),i&&Object.keys(this.localStreams).forEach((e=>{if(e===Wm)return;const t=this.localStreams[e];r?s.addStream(t):s.afterConnected.then((()=>{this._emitServerEvent(Ff,{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]):Hm.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((n=>{if(!n.hasConnectedPeerConnection()){Hm.info("Session doesn't have a connected PeerConnection, adding pending action!");const i=this._pendingActionsForConnectedPeerConnections;if(!i)return void Hm.warn("No pending action is created to replace track, because the pending actions array is null");const s=new Promise(((r,s)=>{i.push((()=>{const i=n.replaceTrack(e,t);if(!i)return Hm.error("replaceTrack returned false!"),void s("ReplaceTrack returned false");i.then((e=>r(e))).catch((e=>s(e)))}))}));return void r.push(s)}const i=n.replaceTrack(e,t);i?r.push(i):Hm.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,sfuServer:t,mediaserverConfigTtlSeconds:r}){this._iceServers=e,this._sfuServer=t,this._mediaserverConfigTtlSeconds=r,this._clearMediaServersRefresh(),r&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitServerEvent(Bf)),1e3*r))}_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?(Hm.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(jm),this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_setCodecPreferences(e,t,r,n){try{const i=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)}));i.forEach((e=>{if(void 0===RTCRtpSender.getCapabilities)return;const t=RTCRtpSender.getCapabilities("audio");for(let e=0;e<t.codecs.length;e++)if(n&&"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 s=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)}));s.forEach((e=>{if(void 0===RTCRtpSender.getCapabilities)return;const n=RTCRtpSender.getCapabilities("video");for(let e=0;e<n.codecs.length;e++){if(t&&"video/vp9"===n.codecs[e].mimeType.toLowerCase()){n.codecs.unshift(n.codecs.splice(e,1)[0]);break}if(r&&"video/av1"===n.codecs[e].mimeType.toLowerCase()){n.codecs.unshift(n.codecs.splice(e,1)[0]);break}}void 0!==e.setCodecPreferences&&e.setCodecPreferences(n.codecs)}))}catch(e){Hm.error("Error during setting setCodecPreferences:",e)}}_negotiatePeerConnection(e,t,r){if(!t)return void Hm.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const n=t.pc;if(!t.canModifyPeerConnection())return void t.pending.push((()=>{this._negotiatePeerConnection(e,t,r)}));t.isOperationPending=!0;const{vp9On:i,av1On:s,redOn:o,rtpAbsCaptureTimeOn:a,cleanSdpOn:c}=this._features;(i||s||o)&&this._setCodecPreferences(n,i,s,o),n.createOffer(r||this.offerOptions).then((t=>{a&&(t.sdp=Of(t.sdp)),(i||o)&&"firefox"===Km&&(t.sdp=function(e,t,r){var n,i;try{const s=An(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 i=0;i<t.length;i++)if(r&&"red"===t[i].codec){const r=null===(n=e.payloads)||void 0===n?void 0:n.split(" "),s=null==r?void 0:r.indexOf(""+t[i].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===(i=o.payloads)||void 0===i?void 0:i.split(" "),n=null==t?void 0:t.indexOf(""+e[r].payload);n&&-1!==n&&n>=0&&(null==t||t.unshift(t.splice(n,1)[0]),o.payloads=null==t?void 0:t.join(" "))}}}return Ln(s)}catch(e){Rf.error("setCodecPreferenceSDP error:",e)}}(t.sdp,i,o)),c&&(t.sdp=function(e){try{const t=An(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 n={};e.fmtp&&(e.fmtp=e.fmtp.filter((e=>!e.payload||t[e.payload]&&!n[e.payload]&&(n[e.payload]=!0))));const i={};e.rtcpFb&&(e.rtcpFb=e.rtcpFb.filter((e=>!e.payload||t[e.payload]&&!i[e.payload+e.type]&&(i[e.payload+e.type]=!0))))})),Ln(t)}catch(e){}return e}(t.sdp)),n.setLocalDescription(t).catch((e=>{throw Hm.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e),this._emit(Um,e),e})).then((()=>{this._emitServerEvent(Zf,{receiverId:e,message:this._transformOutgoingSdp(t)})}))})).catch((e=>{Hm.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))}_withForcedRenegotiation(e,t){const r=e.pc,n=r.onnegotationneeded;r.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout((()=>r.onnegotiationneeded=n),0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);let r=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:this._features.lowBandwidth?768:0,2:this._features.highP2PBandwidth&&!this._features.lowBandwidth?768:384,3:this._features.highP2PBandwidth&&!this._features.lowBandwidth?512:256,4:192,5:128,6:128,7:64}[t];if(void 0===r)return 0;if(this._features.adjustBitratesFromResolution){const e=this._getLocalCameraStream();if(e){const t=e&&e.getVideoTracks()[0];if(t){const{width:e,height:n,frameRate:i}=t.getSettings();if(e&&n&&i){const t=Math.round(function(e,t,r){let n=e*t;n<fm&&(n=fm),n>gm&&(n=gm);let i=mm;n>gm?i=vm:n>fm&&(i+=-17582143775720163e-22*(n-fm));let s=e*t*i;return r<=15?s*=.7:r<=24&&(s*=.9),s}(e,n,i)/1e3);r=Math.min(t,r||t)}}}}return this._features.higherP2PBitrates&&!this._features.lowBandwidth&&(r*=1.5),this._forEachPeerConnection((e=>{e.changeBandwidth(r)})),r}_createP2pSession({clientId:e,initialBandwidth:t,shouldAddLocalVideo:r=!1,isOfferer:n=!1}){const i=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:r,isOfferer:n}),s=i.pc;this._features.increaseIncomingMediaBufferOn&&this._setJitterBufferTarget(s);const o=this.localStreams[Wm];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((()=>{i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState&&"completed"===s.iceConnectionState||this._emit(Mm)}),3e3);break;case"complete":this.icePublicIPGatheringTimeoutID&&clearTimeout(this.icePublicIPGatheringTimeoutID),this.icePublicIPGatheringTimeoutID=void 0}},s.onicecandidate=t=>{var r,n;if(t.candidate){switch(null===(r=t.candidate)||void 0===r?void 0:r.type){case"host":const e=null===(n=null==t?void 0:t.candidate)||void 0===n?void 0:n.address;try{if(km.v4({exact:!0}).test(e)){Ui(e).isPublicIp&&(i.publicHostCandidateSeen=!0)}else if(km.v6({exact:!0}).test(e.replace(/^\[(.*)\]/,"$1"))){const t=new Nn.Address6(e.replace(/^\[(.*)\]/,"$1"));i.ipv6HostCandidateSeen=!0,"Global"===t.getScope()&&(i.publicHostCandidateSeen=!0),t.isTeredo()&&(i.ipv6HostCandidateTeredoSeen=!0),t.is6to4()&&(i.ipv6HostCandidate6to4Seen=!0)}else{const t=e.replace(/.local/,"");t&&Qi(t,4)&&(i.mdnsHostCandidateSeen=!0)}}catch(e){Hm.info("Error during parsing candidates! Error: ",{error:e})}break;case"srflx":i.serverReflexiveCandidateSeen||(i.serverReflexiveCandidateSeen=!0);break;case"relay":case"relayed":i.relayCandidateSeen||(i.relayCandidateSeen=!0)}this._emitServerEvent(Jf,{receiverId:e,message:t.candidate})}else this._emitServerEvent(Qf,{receiverId:e}),i.publicHostCandidateSeen||i.relayCandidateSeen||i.serverReflexiveCandidateSeen||"connected"===s.iceConnectionState||"completed"===s.iceConnectionState||this._emit(xm),i.ipv6HostCandidateSeen&&this._emit(Im,{teredoSeen:i.ipv6HostCandidateTeredoSeen,sixtofourSeen:i.ipv6HostCandidate6to4Seen}),i.mdnsHostCandidateSeen&&this._emit(Dm)},s.onnegotiationneeded=()=>{"new"!==s.iceConnectionState&&i.connectionStatus&&this._negotiatePeerConnection(e,i)},i}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:r}){let n=this._getSession(t);if(n&&e!==t)return n;let i=n&&n.bandwidth||0;return n?(Hm.warn("Replacing peer session",t),this._cleanup(t)):i=this._changeBandwidthForAllClients(!0),n=this._createP2pSession({clientId:t,initialBandwidth:i,shouldAddLocalVideo:!!r,isOfferer:!1}),this._emitServerEvent(Xf,{receiverId:t}),n}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(Km))if(!1===t){const n="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(am,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),n)}else if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;if(!r)return;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emit(om,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})}))}}_shareScreen(e,t){this._emitServerEvent(Ff,{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(zf,{streamId:e,requestedByClientId:r})}hasClient(e){return Object.keys(this.peerConnections).includes(e)}}class Ym{static parse(e){let t;try{t=JSON.parse(e)}catch(e){return}if("object"==typeof t&&!Array.isArray(t))return t.request?Ym._handleRequest(t):t.response?Ym._handleResponse(t):t.message?Ym._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 Zm=new Qh;class eg extends _p{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(){Zm.info("Connected"),this.emit("open")}_onMessage(e){const t=Ym.parse(e.data);Zm.info("Received message",t),(null==t?void 0:t.response)?this._handleResponse(t):(null==t?void 0:t.message)&&this.emit("message",t)}_onClose(){Zm.info("Disconnected"),this._tearDown()}_onError(e){Zm.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=Ym.createMessage(e,t);this.send(r)}request(e,t={},r=1500*(15+.1*this.sents.size)){const n=Ym.createRequest(e,t);return this.send(n),new Promise(((e,t)=>{const i={id:n.id,method:n.method,resolve:t=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),e(t))},reject:e=>{this.sents.delete(n.id)&&(clearTimeout(i.timer),t(e))},timer:setTimeout((()=>{this.sents.delete(n.id)&&t(new Error("request timeout"))}),r),close:()=>{clearTimeout(i.timer),t(new Error("transport closed"))}};this.sents.set(n.id,i)}))}}var tg=Object.freeze({__proto__:null,KalmanFilter:class{constructor({R:e=.01,Q:t=2,A:r=1.1,B:n=1,C:i=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=i,this.B=n,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),n=this.uncertainty(),i=n*this.C*(1/(this.C*n*this.C+this.Q));this.x=r+i*(e-this.C*r),this.cov=n-i*this.C*n}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 n=>{const i=n.reduce(((e,t)=>e+t),0)/n.length;if(e=e<0?i:.95*e+.05*i,++r<2)return t=i,0;const s=(i-e)*(t-e);return t=i,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"},ng=new Qh;const ig=new Qh,sg=Object.freeze({ok:"ok",warning:"warning",critical:"critical"});class og extends _p{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:sg.ok,trend:[]},video:{currentQuality:sg.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 n=t.reduce(((e,t)=>e+t.score),0)/t.length,i=this._evaluateScore(n);this._updateTrend(i,this._clients[e][r])&&this.emit(tm,{clientId:e,kind:r,quality:i})}_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]={}):ig.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]={}):ig.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,n){Array.isArray(n)&&0!==n.length&&!n.some((e=>!e||!e.hasOwnProperty("score")||"number"!=typeof e.score||isNaN(e.score)))?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.map((e=>e.score)))}:ig.warn("Unexpected producer score format")}addConsumerScore(e,t,r,n){n&&n.hasOwnProperty("producerScores")&&Array.isArray(n.producerScores)?this._producers[e][t]={kind:r,score:this._calcAvgProducerScore(n.producerScores)}:ig.warn("Unexpected consumer score format")}_evaluateScore(e){return e<=9&&e>7?sg.warning:e<=7&&e>0?sg.critical:sg.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 ig.error(e),0}}}const ag={codecOptions:{opusDtx:!0,opusFec:!0},encodings:[{dtx:!0}]},cg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:4,maxBitrate:15e4},{scaleResolutionDownBy:2,maxBitrate:5e5},{scaleResolutionDownBy:1,maxBitrate:1e6}]},dg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scaleResolutionDownBy:2,maxBitrate:15e4},{scaleResolutionDownBy:1,maxBitrate:5e5}]},lg={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L3T2_KEY"}]},ug={codecOptions:{videoGoogleStartBitrate:500},encodings:[{scalabilityMode:"L2T2_KEY",maxBitrate:8e5}]},pg={encodings:[{}]},hg={encodings:[{maxBitrate:6e5,maxFramerate:2}]},fg={encodings:[{scaleResolutionDownBy:2,dtx:!0,maxBitrate:5e5},{scaleResolutionDownBy:1,dtx:!0,maxBitrate:15e5}]},mg={encodings:[{dtx:!0}]},gg=(e,t,r)=>{const{lowDataModeEnabled:n,simulcastScreenshareOn:i,vp9On:s,lowBandwidth:o}=r;return"audio"===e?ag:t?o&&!s?hg:s?mg:i?fg:pg:o?s?ug:dg:s?lg:n?dg:cg},vg=()=>{let e=Xi.detectDevice()||(/applecoremedia|applewebkit|safari/i.test(navigator.userAgent)?"Safari12":void 0);return/iphone|ipad/i.test(navigator.userAgent)&&(e="Safari12"),e};var bg;const yg=null!==(bg=hn.default)&&void 0!==bg?bg:hn,wg=new Qh,_g=yg.browserDetails.browser;let Sg=!1;const Cg=Sn(),Rg=Sn();"chrome"===_g&&window.document.addEventListener("beforeunload",(()=>Sg=!0));class Tg{constructor({selfId:e,room:t,emitter:r,serverSocket:n,webrtcProvider:i,features:s,eventClaim:o,deviceHandlerFactory:a}){const{session:c,iceServers:d,sfuServer:l,mediaserverConfigTtlSeconds:u}=t;this._selfId=e,this._room=t,this._roomSessionId=null==c?void 0:c.id,this._emitter=r,this._serverSocket=n,this._webrtcProvider=i,this._features=s||{},this._eventClaim=o,this._vegaConnection=null,this._micAnalyser=null,this._micAnalyserDebugger=null,this._mediasoupDevice=a?new Xi.Device({handlerFactory:a}):new Xi.Device({handlerName:vg()}),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=()=>{nf.sendEvent("audio_ended",{unloading:Sg}),this._emitToPWA(Am,{})},this._videoTrackOnEnded=()=>{nf.sendEvent("video_ended",{unloading:Sg}),this._emitToPWA(Nm,{})},this._updateAndScheduleMediaServersRefresh({sfuServer:l,iceServers:d.iceServers||[],mediaserverConfigTtlSeconds:u}),this._socketListenerDeregisterFunctions=[],this._reconnect=!0,this._reconnectTimeOut=null,this._hasVegaConnection=!1,this._qualityMonitor=new og,this._qualityMonitor.on(tm,(e=>{this._emitToPWA(tm,e)}))}_updateAndScheduleMediaServersRefresh({iceServers:e,sfuServer:t,mediaserverConfigTtlSeconds:r}){var n,i;this._iceServers=e,this._sfuServer=t,this._mediaserverConfigTtlSeconds=r,null===(n=this._sendTransport)||void 0===n||n.updateIceServers({iceServers:this._iceServers}),null===(i=this._receiveTransport)||void 0===i||i.updateIceServers({iceServers:this._iceServers}),this._clearMediaServersRefresh(),r&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitToSignal(Bf)),1e3*r))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}setupSocketListeners(){this._socketListenerDeregisterFunctions.push((()=>this._clearMediaServersRefresh()),this._serverSocket.on($f,(e=>{e.error?wg.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(Wf,(()=>{this._screenVideoTrack&&this._emitScreenshareStarted(),this._features.sfuReconnectV2On&&!this._hasVegaConnection&&this._reconnect&&this._connect()}))),this._connect()}_emitScreenshareStarted(){this._emitToSignal(Ff,{streamId:Rg,hasAudioTrack:Boolean(this._screenAudioTrack)})}_connect(){if(this._features.sfuReconnectV2On){if(this._hasVegaConnection)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)}const e=this._features.sfuServerOverrideHost||[this._sfuServer.url],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]})),{}))),r=`wss://${e}?${t.toString()}`;this._vegaConnection=new eg(r),this._hasVegaConnection=!0,this._vegaConnection.on("open",(()=>this._join())),this._vegaConnection.on("close",(()=>this._onClose())),this._vegaConnection.on("message",(e=>this._onMessage(e)))}_onClose(){var e,t;wg.info("_onClose()"),this._hasVegaConnection=!1,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(zm)}_join(){return Xh(this,void 0,void 0,(function*(){wg.info("join()"),this._emitToPWA(Fm);try{const{routerRtpCapabilities:e}=yield this._vegaConnection.request("getCapabilities");this._routerRtpCapabilities||(((e,t)=>{const{vp9On:r,h264On:n}=t;if(r){const{preferredPayloadType:t}=e.codecs.find((e=>"video/vp9"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}else if(n){const{preferredPayloadType:t}=e.codecs.find((e=>"video/h264"===e.mimeType.toLowerCase())),{preferredPayloadType:r}=e.codecs.find((e=>"video/rtx"===e.mimeType.toLowerCase()&&e.parameters.apt===t));e.codecs=e.codecs.filter((e=>"audio"===e.kind||e.preferredPayloadType===t||e.preferredPayloadType===r))}})(e,this._features),this._routerRtpCapabilities=e,yield this._mediasoupDevice.load({routerRtpCapabilities:e})),this._vegaConnection.message("setCapabilities",{rtpCapabilities:this._mediasoupDevice.rtpCapabilities}),this._colocation&&this._vegaConnection.message("setColocation",{colocation:this._colocation}),yield Promise.all([this._createTransport(!0),this._createTransport(!1)]);const t=[];!this._micTrack||this._micProducer||this._micProducerPromise||t.push(this._internalSendMic()),!this._webcamTrack||this._webcamProducer||this._webcamProducerPromise||t.push(this._internalSendWebcam()),!this._screenVideoTrack||this._screenVideoProducer||this._screenVideoProducerPromise||t.push(this._internalSendScreenVideo()),!this._screenAudioTrack||this._screenAudioProducer||this._screenAudioProducerPromise||t.push(this._internalSendScreenAudio()),yield Promise.all(t)}catch(e){wg.error("_join() [error:%o]",e)}}))}_createTransport(e){return Xh(this,void 0,void 0,(function*(){const t=e?"createSendTransport":"createRecvTransport",r=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}});r.iceServers=this._iceServers,((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))))})(r,this._features);const n=this._mediasoupDevice[t](r),i=t=>Xh(this,void 0,void 0,(function*(){if(wg.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}))}}));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",i),n.observer.once("close",(()=>{n.removeListener(i)})),e?(n.on("produce",(({kind:e,rtpParameters:t,appData:r},i,s)=>Xh(this,void 0,void 0,(function*(){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)}})))),n.on("producedata",(({appData:e,sctpStreamParameters:t},r,i)=>Xh(this,void 0,void 0,(function*(){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,t=0){return Xh(this,void 0,void 0,(function*(){if(!e||!("closed"in e)||!("connectionState"in e))return void wg.info("_restartIce: No transport or property closed or connectionState!");if(e.closed)return void wg.info("_restartIce: Transport is closed!");if("disconnected"!==e.connectionState&&"failed"!==e.connectionState)return void wg.info("_restartIce: Connection is healthy ICE restart no loneger needed!");const{iceRestartStarted:r}=e.appData,n=Date.now();if(Number.isFinite(r)&&n-r<3500)return;if(e.appData.iceRestartStarted=n,5<=t)return void wg.info("_restartIce: Reached restart ICE maximum retry count!");if(!this._vegaConnection)return void wg.info("_restartIce: Connection is undefined");const{iceParameters:i}=yield this._vegaConnection.request("restartIce",{transportId:e.id});wg.info("_restartIce: ICE restart iceParameters received from SFU: ",i);const s=yield e.restartIce({iceParameters:i}).then((()=>null)).catch((e=>e));if(s)switch(wg.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 Xh(this,void 0,void 0,(function*(){wg.info("_internalSendMic()"),this._micProducerPromise=(()=>Xh(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},gg("audio",!1,this._features)),{appData:{streamId:Cg,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;wg.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){wg.error("micProducer failed:%o",e)}finally{this._micProducerPromise=null,this._micTrack||(this._stopProducer(this._micProducer),this._micProducer=null)}})))()}))}_internalSetupMicScore(){return Xh(this,void 0,void 0,(function*(){wg.info("_internalSetupMicScore()"),this._micScoreProducerPromise=(()=>Xh(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;wg.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){wg.error("micScoreProducer failed:%o",e)}finally{this._micScoreProducerPromise=null,this._micProducer&&this._colocation||this._stopMicScoreProducer()}})))()}))}_stopMicScoreProducer(){this._stopProducer(this._micScoreProducer),this._micScoreProducer=null}_replaceMicTrack(){var e;return Xh(this,void 0,void 0,(function*(){wg.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;wg.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 Xh(this,void 0,void 0,(function*(){return wg.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){wg.error("_sendMicScore failed [error:%o]",e)}}else!this._micScoreProducerPromise&&this._micProducer&&this._colocation&&0!==e&&this._internalSetupMicScore()}_internalSendWebcam(){var e;return Xh(this,void 0,void 0,(function*(){wg.info("_internalSendWebcam()"),!this._sendTransport||this._webcamProducer||this._webcamProducerPromise||"live"!==(null===(e=this._webcamTrack)||void 0===e?void 0:e.readyState)||(this._webcamProducerPromise=(()=>Xh(this,void 0,void 0,(function*(){var e,t;try{const t=this._webcamPaused,r=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._webcamTrack,disableTrackOnPause:!1,stopTracks:!1},gg("video",!1,this._features)),{appData:{streamId:Cg,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;wg.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){wg.error("webcamProducer failed:%o",e)}finally{this._webcamProducerPromise=null,this._webcamTrack||(this._stopProducer(this._webcamProducer),this._webcamProducer=null),this._features.lowBandwidth&&this._screenVideoTrack&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(0))}})))())}))}_replaceWebcamTrack(){return Xh(this,void 0,void 0,(function*(){wg.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;wg.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 Xh(this,void 0,void 0,(function*(){return wg.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 Xh(this,void 0,void 0,(function*(){wg.info("_internalSendScreenVideo()"),this._screenVideoProducerPromise=(()=>Xh(this,void 0,void 0,(function*(){var e,t;try{if(!this._screenVideoTrack||!this._sendTransport||this._screenVideoProducer)return void(this._screenVideoProducerPromise=null);const t=yield this._sendTransport.produce(Object.assign(Object.assign({track:this._screenVideoTrack,disableTrackOnPause:!1,stopTracks:!1},gg("video",!0,this._features)),{appData:{streamId:Rg,sourceClientId:this._selfId,screenShare:!0,source:"screenvideo",paused:!1}}));this._screenVideoProducer=t,this._qualityMonitor.addProducer(this._selfId,t.id),t.observer.once("close",(()=>{var e;wg.info('screenVideoProducer "close" event'),t.appData.localClosed&&(null===(e=this._vegaConnection)||void 0===e||e.message("closeProducers",{producerIds:[t.id]})),this._screenVideoProducer=null,this._screenVideoProducerPromise=null,this._qualityMonitor.removeProducer(this._selfId,t.id)})),this._screenVideoTrack!==this._screenVideoProducer.track&&(yield this._replaceScreenVideoTrack()),this._features.lowBandwidth&&(null===(e=this._webcamProducer)||void 0===e||e.setMaxSpatialLayer(0))}catch(e){wg.error("screenVideoProducer failed:%o",e)}finally{this._screenVideoProducerPromise=null,this._screenVideoTrack||(yield this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._features.lowBandwidth&&(null===(t=this._webcamProducer)||void 0===t||t.setMaxSpatialLayer(Number.MAX_VALUE)))}})))()}))}_replaceScreenVideoTrack(){return Xh(this,void 0,void 0,(function*(){wg.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 Xh(this,void 0,void 0,(function*(){return wg.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 Xh(this,void 0,void 0,(function*(){wg.info("_internalSendScreenAudio()"),this._screenAudioProducerPromise=(()=>Xh(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},gg("audio",!0,this._features)),{appData:{streamId:Rg,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;wg.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){wg.error("screenAudioProducer failed:%o",e)}finally{this._screenAudioProducerPromise=null,this._screenAudioTrack||(yield this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null)}})))()}))}_replaceScreenAudioTrack(){return Xh(this,void 0,void 0,(function*(){wg.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 Xh(this,void 0,void 0,(function*(){return wg.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){wg.info("_stopProducer()"),e&&!e.closed&&(e.appData.localClosed=!0,e.close())}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(),nf.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 n;if(wg.info("disconnect() [clientIdOrStreamId:%s, eventClaim:%s]",e,r),this._clientStates.has(e)){const t=this._clientStates.get(e);t.hasAcceptedWebcamStream=!1,t.hasAcceptedScreenStream=!1,this._syncIncomingStreamsWithPWA(e)}r&&(this._eventClaim=r,null===(n=this._vegaConnection)||void 0===n||n.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){var n;wg.info("removeStream() [streamId:%s, requestedByClientId:%s]",e,r),this._emitToSignal(zf,{streamId:Rg,requestedByClientId:r}),this._stopProducer(this._screenVideoProducer),this._screenVideoProducer=null,this._screenVideoTrack=null,this._stopProducer(this._screenAudioProducer),this._screenAudioProducer=null,this._screenAudioTrack=null,this._features.lowBandwidth&&(null===(n=this._webcamProducer)||void 0===n||n.setMaxSpatialLayer(Number.MAX_VALUE))}_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,n,i=[]){if("0"===e){this._micPaused=r,this._webcamPaused=n;const e=t.getVideoTracks()[0],s=t.getAudioTracks()[0];if(e){this._sendWebcam(e),e.effectTrack||this._monitorVideoTrack(e);const t=i.find((e=>"video"===e.kind));t&&this._monitorVideoTrack(t)}if(s){this._sendMic(s),this._syncMicAnalyser(),s.effectTrack||this._monitorAudioTrack(s);const e=i.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 n=new AudioContext;let i=null,s=null,o=null,a=!1;const c=e=>Xh(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){ng.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=n.createMediaStreamSource(t),s.connect(i)}}));let d;const l=e=>{if(clearInterval(d),t=Object.assign(Object.assign({},rg),e),!i||i.fftSize!==2*t.bins){let e=null;i&&(e=o,c(null)),i=n.createAnalyser(),i.fftSize=2*t.bins,e&&c(e)}const s=new Uint8Array(i.frequencyBinCount),a=[];i.minDecibels=t.minDecibels,i.maxDecibels=t.maxDecibels,i.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(tg,c,o);d=setInterval((()=>{i.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,tg),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),n=a.reduce(((e,t)=>e+t),0)/a.length,i=h(e,n,t,a);r({bins:s,score:e,max:t,avg:n,out:i})}}),1e3/t.sampleRate)};return l(t),c(e),{setParams:l,setTrack:c,close(){c(null),clearInterval(d),n.close()}}}({micTrack:this._micTrack,onScoreUpdated:this._onMicAnalyserScoreUpdated.bind(this)})}stopOrResumeAudio(e,t){wg.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(wg.info("stopOrResumeVideo() [enable:%s]",t),this._webcamPaused=!t,this._pauseResumeWebcam(),["chrome","safari"].includes(_g))if(t){if(0===e.getVideoTracks().length){const r=this._webrtcProvider.getMediaConstraints().video;navigator.mediaDevices.getUserMedia({video:r}).then((r=>{const n=r.getVideoTracks()[0];e.addTrack(n),this._monitorVideoTrack(n),this._emitToPWA(om,{streamId:e.id,tracks:[n],screenShare:!1}),this._handleStopOrResumeVideo({enable:t,track:n})}))}}else{clearTimeout(this._stopCameraTimeout);const n="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(am,{stream:e,track:r}),this._handleStopOrResumeVideo({enable:t,track:r}))}))}),n)}}supportsScreenShareAudio(){return!0}acceptNewStream({streamId:e,clientId:t}){wg.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:n}){var i,s;wg.info("updateStreamResolution()",{streamId:e,width:r,height:n});const o=this._streamIdToVideoConsumerId.get(e),a=this._consumers.get(o);if(!a)return void this._streamIdToVideoResolution.set(e,{width:r,height:n});const c=function(e){let t=0;return e.forEach((e=>{var r,n;e._closed||e._paused||"webcam"!==(null===(r=e._appData)||void 0===r?void 0:r.source)&&"screenvideo"!==(null===(n=e._appData)||void 0===n?void 0:n.source)||t++})),t}(this._consumers),d=function(e){var t,r,n;return/T3/.test((null===(n=null===(r=null===(t=e._rtpParameters)||void 0===t?void 0:t.encodings)||void 0===r?void 0:r[0])||void 0===n?void 0:n.scalabilityMode)||"")?3:2}(a),{spatialLayer:l,temporalLayer:u}=function({width:e,height:t},{numberOfActiveVideos:r,numberOfTemporalLayers:n,uncappedSingleRemoteVideoOn:i}){const s=Math.max(e,t);let o=s>=480?s>=960?2:1:0,a=n-1;return s<100&&(a=Math.max(n-2,0)),r>8&&0===o&&(a=Math.max(n-2,0)),r<4&&s>300&&0===o&&(o=1),i&&1===r&&(o=2,a=n-1),{spatialLayer:o,temporalLayer:a}}({width:r,height:n},{numberOfActiveVideos:c,numberOfTemporalLayers:d,uncappedSingleRemoteVideoOn:null===(i=this._features)||void 0===i?void 0:i.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,n;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===(n=this._receiveTransport)||void 0===n||n.close(),this._micTrack=null,this._webcamTrack=null,this._screenVideoTrack=null,this._screenAudioTrack=null,this._streamIdToVideoConsumerId.clear(),this._mediasoupDevice=null}sendAudioMutedStats(e){nf.sendEvent("audio_muted",{muted:e})}sendVideoMutedStats(e){nf.sendEvent("video_muted",{muted:e})}sendStatsCustomEvent(e,t){nf.sendEvent(e,t)}rtcStatsDisconnect(){nf.server.close()}rtcStatsReconnect(){nf.server.connected||nf.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 Xh(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 wg.info(`unknown message method "${t}"`)}})).catch((e=>{wg.error('"message" failed [error:%o]',e)}))}))}_onConsumerReady(e){return Xh(this,void 0,void 0,(function*(){wg.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=Df,t.rtpReceiver.playoutDelayHint=.4}catch(e){wg.error("Error during setting jitter buffer target:",e)}const{sourceClientId:r,screenShare:n,streamId:i}=t.appData,s=this._getOrCreateClientState(r);n?(s.hasEmittedScreenStream=!1,s.screenShareStreamId=i):(s.hasEmittedWebcamStream=!1,s.camStreamId=i);let o=n?s.screenStream:s.webcamStream;o&&o.inboundId===i||(o=new MediaStream,o.inboundId=i,n?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({consumerId:e,reason:t}){var r;return Xh(this,void 0,void 0,(function*(){wg.info("_onConsumerClosed()",{consumerId:e,reason:t}),null===(r=this._consumers.get(e))||void 0===r||r.close()}))}_onConsumerPaused({consumerId:e}){wg.info("_onConsumerPaused()",{consumerId:e});const t=this._consumers.get(e);t&&(t.appData.remotePaused=!0,t.pause())}_onConsumerResumed({consumerId:e}){wg.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}){wg.info("_onConsumerScore()",{consumerId:e,kind:t,score:r});const{appData:{sourceClientId:n}}=this._consumers.get(e)||{appData:{}};n&&this._qualityMonitor.addConsumerScore(n,e,t,r)}_onProducerScore({producerId:e,kind:t,score:r}){wg.info("_onProducerScore()",{producerId:e,kind:t,score:r}),[this._micProducer,this._webcamProducer,this._screenVideoProducer,this._screenAudioProducer].forEach((n=>{(null==n?void 0:n.id)===e&&this._qualityMonitor.addProducerScore(this._selfId,e,t,r)}))}_onDataConsumerReady(e){return Xh(this,void 0,void 0,(function*(){wg.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:n}=JSON.parse(e);n&&(null===(r=this._micAnalyserDebugger)||void 0===r||r.onConsumerScore(t.appData.clientId,n))})),this._syncIncomingStreamsWithPWA(r)}))}_onDataConsumerClosed({dataConsumerId:e,reason:t}){return Xh(this,void 0,void 0,(function*(){wg.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(Vm,{clientId:r})}_consumerClosedCleanup(e){const{sourceClientId:t,screenShare:r}=e.appData,n=this._getOrCreateClientState(t),i=r?n.screenStream:n.webcamStream;i&&(i.removeTrack(e.track),0===i.getTracks().length&&(this._streamIdToVideoConsumerId.delete(i.id),this._streamIdToVideoResolution.delete(i.id),r?(n.screenStream=null,n.hasEmittedScreenStream=!1,n.screenShareStreamId=null):(n.hasEmittedWebcamStream=!1,n.camStreamId=null)))}_syncIncomingStreamsWithPWA(e){var t,r;const n=this._getOrCreateClientState(e),{webcamStream:i,screenStream:s,hasEmittedWebcamStream:o,hasEmittedScreenStream:a,hasAcceptedWebcamStream:c,hasAcceptedScreenStream:d,screenShareStreamId:l,camStreamId:u}=n,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})),i&&!o&&c&&(this._emitToPWA(nm,{clientId:e,stream:i,streamId:u,streamType:"webcam"}),n.hasEmittedWebcamStream=!0),s&&!a&&d&&(this._emitToPWA(nm,{clientId:e,stream:s,streamId:l,streamType:"screenshare"}),n.hasEmittedScreenStream=!0)}_getOrCreateClientState(e){let t=this._clientStates.get(e);return t||(t={hasAcceptedWebcamStream:!1,hasAcceptedScreenStream:!1,hasEmittedWebcamStream:!1,hasEmittedScreenStream:!1,webcamStream:null,screenStream:null,screenShareStreamId:null,camStreamId:null},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 kg{constructor({emitter:e,serverSocket:t,webrtcProvider:r,features:n}){this.emitter=e,this.currentManager=null,t.on(Wf,(({room:i,selfId:s,error:o,eventClaim:a})=>{if(o)return;const c={selfId:s,room:i,emitter:e,serverSocket:t,webrtcProvider:r,features:n,eventClaim:a,deviceHandlerFactory:null==n?void 0:n.deviceHandlerFactory},d=!!i.sfuServer;if(Pg=d?"group":"normal",this.currentManager){if(this.currentManager.isInitializedWith({selfId:s,roomName:i.name,isSfu:d}))return void(this.currentManager.setEventClaim&&a&&this.currentManager.setEventClaim(a));this.currentManager.disconnectAll(),e.emit(sm)}let l=null;l=d?new Tg(c):new Xm(c),l.rtcStatsReconnect(),l.setupSocketListeners(),e.emit(im,{rtcManager:l}),this.currentManager=l,t.setRtcManager(l)}))}stopRtcManager(){this.currentManager&&(this.currentManager.disconnectAll(),this.emitter.emit(sm))}}let Pg="";const Eg=()=>Pg;class Og 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 Ig(e){if(e.message instanceof Error)throw e.message;throw new Og(e)}function Dg(...e){!function(e,t,r,n){if(!r){let i=!1;if(0===t)i=!0,n="No value argument passed to `assert.ok()`";else if(n instanceof Error)throw n;const s=new Og({actual:r,expected:!0,message:n,operator:"==",stackStartFn:e});throw s.generatedMessage=i,s}}(Dg,e.length,...e)}const xg={fail:e=>{Ig({actual:"fail()",expected:"fail() should not be called",message:e,operator:"fail",stackStartFn:xg.fail})},ok:Dg,notEqual:function e(t,r,n){if(arguments.length<2)throw new Error("'actual' and 'expected' arguments are required");t==r&&Ig({actual:t,expected:r,message:n,operator:"!=",stackStartFn:e})}};xg.ok=Dg;const Mg=new Qh;class jg extends _p{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(Wf,(e=>this._onRoomJoined(e))),e.on(Gf,(e=>this._onNewClient(e))),e.on(Uf,(e=>this._onClientLeft(e))),e.on(em,(e=>this._onPendingClientLeft(e))),e.on(Vf,(e=>this._onAudioEnabled(e))),e.on(Kf,(e=>this._onVideoEnabled(e))),e.on(qf,(e=>this._onScreenshareChanged(e,!0))),e.on(Hf,(e=>this._onScreenshareChanged(e,!1)))}_onRoomJoined(e){var t,r;return Xh(this,void 0,void 0,(function*(){if(this.reconnectThresholdInMs=.8*(e.disconnectTimeout||0),!(null===(t=e.room)||void 0===t?void 0:t.clients))return void this.emit(Wf,e);if(!e.selfId)return void this.emit(Wf,e);const n=null===(r=e.room.clients.find((t=>e.selfId===t.id)))||void 0===r?void 0:r.deviceId;if(!n)return void this.emit(Wf,e);if(!this._signalDisconnectTime)return this._resetClientState(e),e.room.clients=e.room.clients.filter((e=>!(e.deviceId===n&&e.isPendingToLeave))),void this.emit(Wf,e);const i=.8*e.disconnectTimeout;if(Date.now()-this._signalDisconnectTime>i)return this._resetClientState(e),this.emit(Wf,e),void this.metrics.roomJoinedLate++;e.room.clients=e.room.clients.filter((e=>!(e.deviceId===n&&e.isPendingToLeave)));const s=yield wf();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(s,t.id))return;t.mergeWithOldClientState=!0}catch(e){Mg.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(Wf,e)}))}_onClientLeft(e){var t;const{clientId:r}=e,n=this._clients[r];n&&(clearTimeout(n.timeout),delete this._clients[r]),null===(t=this.rtcManager)||void 0===t||t.disconnect(r,null,e.eventClaim),this.emit(Uf,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))):Mg.warn(`client ${t} not found`)}_onNewClient(e){const{client:{id:t,deviceId:r}}=e,n=this._clients[t];if(n&&n.isPendingToLeave)return clearTimeout(n.timeoutHandler),n.isPendingToLeave=!1,void this.metrics.pendingClientCanceled++;this._getPendingClientsByDeviceId(r).forEach((e=>{clearTimeout(e.timeoutHandler),e.isPendingToLeave=void 0,this.emit(Uf,{clientId:e.clientId})})),this._addClientToState(e.client),this.emit(Gf,e)}_abortIfNotActive(e){return Xh(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(Uf,e)))}))}_checkIsActive(e){return Xh(this,void 0,void 0,(function*(){const t=yield wf();return this._isClientMediaActive(t,e)}))}_isClientMediaActive(e,t){const r=null==e?void 0:e[t];let n=!1;return r&&Object.entries(r.tracks).forEach((([e,t])=>{"probator"!==e&&Object.values(t.ssrcs).forEach((e=>{(e.bitrate||0)>0&&(n=!0)}))})),n}_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:n}){const i=this._clients[e];if(!i)throw new Error(`Client ${e} not found in ReconnectManager state`);return t!==i.isVideoEnabled||(r!==i.isAudioEnabled||n!==i.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 Lg;const Ag=null!==(Lg=hn.default)&&void 0!==Lg?Lg:hn;class Ng{constructor(e,t,r=!1){this._wasConnectedUsingWebsocket=!1,this._reconnectManager=null,this._socket=Kh(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"!==Ag.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["websocket","polling"]})),r&&(this._reconnectManager=new jg(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=[Wf,Uf,Gf];return this._reconnectManager&&r.includes(e)?this._interceptEvent(e,t):(this._socket.on(e,t),()=>{this._socket.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 Bg=[{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 Fg({host:e="whereby.com",protocol:t="https:"}={}){let r="",n=e,i=".";for(const{separator:t,pattern:s}of Bg){const o=s.exec(e);if(o){r=o[1]||"",n=o[2],i=t;break}}const s=r?`${r}${i}${n}`:n;return{domain:n,domainWithSeparator:`${i}${n}`,organizationDomain:s,organization:`${t}//${s}`,service:`${t}//${n}`,subdomain:r}}Fg(window&&window.location);const zg=new Qh,Vg={print:(...e)=>console.debug(e[0],...e.slice(1))};zg.withDebugLogger(Vg);const Ug=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 n=t>this.BEGIN_PACKET_LOSS_PERIOD_THRESHOLD;let i=this.ssrcsHistory.get(e);if(!i)return i={id:e,hasActivePacketLoss:n,currPeriod:n?{begin:r}:void 0,hasPeriodicPacketLoss:!1},void this.ssrcsHistory.set(e,i);i.hasActivePacketLoss?t<this.END_PACKET_LOSS_PERIOD_THRESHOLD&&(this.endPacketLossPeriod(i,r),i.prevIntervalInMs&&i.prevIntervalInMs<this.MINIMUM_INTERVAL_MS&&this.ssrcsHistory.delete(e)):n&&(i.hasActivePacketLoss=!0,i.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((()=>{zg.debug("handleStaleMeasurements() [measurements invalid for ssrc: %s]",e),this.ssrcsHistory.delete(e)}),this.STALE_MEASUREMENT_TIMEOUT_MS))}endPacketLossPeriod(e,t){if(zg.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(zg.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,zg.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}},$g=[{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:n})=>{if(!n&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return!n}},{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:n})=>{if(0===n.length&&!e.isLocalClient&&"video"===r){const e=t.find((e=>e.isLocalClient));if(e)return!e.isAudioOnlyModeEnabled}return 0===n.length}},{id:"dry-track",enabled:({hasLiveTrack:e,ssrcs:t})=>!(!e||!t),check:({client:e,clients:t,ssrcs:r})=>{let n=!1;if(r.forEach((e=>{n=n||((null==e?void 0:e.bitrate)||0)>0})),!n&&e.isLocalClient){const e=t.filter((e=>!e.isLocalClient));if(e.length>0)return!e.every((e=>e.isAudioOnlyModeEnabled))}return!n}},{id:"low-layer0-bitrate",enabled:({hasLiveTrack:e,ssrc0:t,kind:r,client:n})=>e&&"video"===r&&!!t&&!!(null==t?void 0:t.height)&&!n.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:n,kind:i})=>{if("normal"===Eg()){if(n.filter((e=>!e.isLocalClient)).some((e=>e.isAudioOnlyModeEnabled)))return!1}return e&&r.isLocalClient&&"video"===i&&!!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:n})=>e&&r.isLocalClient&&"video"===n&&!!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:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.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:n})=>e&&!!t&&!!t.height&&"video"===r&&!n.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:n})=>{if(!n.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 i=n[0];return!!i&&(0===i.bitrate||(i.lossRatio||0)>.03||(i.fractionLost||0)>.03||!e.isPresentation&&"video"===r&&!!(null==i?void 0:i.bitrate)&&i.bitrate<3e4||"in"===i.direction&&!!i.pliRate&&i.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)&&(Ug.addPacketLossMeasurement(e.ssrc,e.fractionLost||0,Date.now()),Ug.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 Gg=[],qg=null;const Hg=[{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:n})=>e&&"video"===n&&!!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:n,kind:i})=>e&&"video"===i&&!!r&&!!t&&!!n&&!!n.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:n})=>e&&"video"===n&&!!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:n})=>e&&"video"===n&&!!t&&!!r&&!!r.height,value:({trackStats:e})=>Object.values((null==e?void 0:e.ssrcs)||{}).reduce(((e,t)=>e+(t.qpf||0)),0)}];let Wg,Kg,Jg;const Qg=()=>{Wg={},Kg={},Jg={aggregated:{issues:Kg,metrics:Wg}}};function Xg(e,t){Object.values(Wg).forEach((e=>{e.curTicks=0,e.curSum=0,e.curMax=0,e.curMin=0,e.curAvg=0})),Object.values(Kg).forEach((e=>{e.curTicks=0,e.curRegistered=0,e.active=!1})),t.find((e=>!e.isLocalClient))&&(t.forEach((r=>{const n=e[r.id];["video","audio","global"].forEach((e=>{var i,s;if(("global"!==e||r.isPresentation)&&!(null===(i=r[e])||void 0===i?void 0:i.enabled))return;if("global"===e&&!r.isLocalClient)return;let o=Jg[r.id];o||(o={issues:{},metrics:{}},Jg[r.id]=o);const a=null===(s=r[e])||void 0===s?void 0:s.track,c=!!a&&"ended"!==a.readyState,d=a&&n&&n.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:n,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}`;Hg.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 n=t.value(p);r||(r={ticks:0,sum:0,avg:0,min:n,max:n},o.metrics[e]=r),r.ticks++,r.sum+=n,r.min=Math.min(r.min,n),r.max=Math.max(r.max,n),r.avg=r.sum/r.ticks;let i=Wg[e];i||(i={ticks:0,sum:0,min:n,max:n,avg:0,curTicks:0,curMin:0,curMax:0,curAvg:0,curSum:0,totTicks:0,totMin:0,totMax:0,totAvg:0,totSum:0},Wg[e]=i),i.ticks++,i.sum+=n,i.min=Math.min(i.min,n),i.max=Math.max(i.max,n),i.avg=i.sum/i.ticks,0===i.curTicks?(i.curMax=n,i.curMin=n,i.curSum=n):(i.curMax=Math.max(i.curMax,n),i.curMin=Math.min(i.curMin,n),i.curSum+=n),i.curTicks++}})),$g.forEach((t=>{if(t.global&&"global"!==e)return;if(!t.global&&"global"===e)return;const r=`${h}-${t.id}`,n=t.enabled(p);let i=o.issues[r],s=Kg[r];if(n){i||(i={active:!1,ticks:0,registered:0,initial:0,periods:0,current:0,longest:0},o.issues[r]=i),i.ticks++,s||(s={active:!1,ticks:0,registered:0,initial:0,curTicks:0,curRegistered:0},Kg[r]=s),s.ticks++,s.curTicks++;t.check(p)?(i.registered++,i.current++,i.active||(i.active=!0,i.periods++),i.ticks===i.initial+1&&(i.initial++,s.initial++),i.current>i.longest&&(i.longest=i.current),s.active=!0,s.registered++,s.curRegistered++):(i.active=!1,i.current=0)}else i&&(i.active=!1,i.current=0)}))}))})),Object.values(Wg).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(Kg).forEach((e=>{e.curTicks})),Gg.forEach((r=>{var n;return null===(n=r.onUpdatedIssues)||void 0===n?void 0:n.call(r,Jg,e,t)})))}function Yg(e){return Gg.push(e),qg||(qg=function(e,t=yf,r=bf){return r.subscriptions.push(e),r.currentMonitor||(r.currentMonitor=_f(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:Xg}).stop),{stop(){Gg=Gg.filter((t=>t!==e)),Gg.length||(null==qg||qg(),qg=null,Qg())}}}var Zg;Qg();const ev="safari"===(null!==(Zg=hn.default)&&void 0!==Zg?Zg:hn).browserDetails.browser,tv=e=>e.split(/[^\d]/g).map((e=>parseInt(e,10)));function rv({devices:e,videoId:t,audioId:r,options:n,type:i="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=function({disableAEC:e,disableAGC:t,hd:r,lax:n,lowDataMode:i,preferredDeviceIds:s,resolution:o,simulcast:a,widescreen:c}){var d,l;let u=480,p=240;r&&(u=n||ev?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:i?p:u,frameRate:i&&!a?15:24})};if(n)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]=tv(o);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}(Object.assign({preferredDeviceIds:{audioId:a?null:{[i]:r},videoId:c?null:{[i]:t}}},n));return!1!==r&&s.length||delete d.audio,!1!==t&&o.length||delete d.video,d}const nv=new Qh,iv=/mobi/i.test(navigator.userAgent);class sv extends Error{constructor(...e){super(...e),this.name="nodevices"}}function ov(e){return e.audio||e.video?navigator.mediaDevices.getUserMedia(e).catch((t=>{const r=`${t}, ${JSON.stringify(e,null,2)}`;throw nv.error(`getUserMedia ${r}`),t})):Promise.reject(new sv("No provided devices"))}function av(e,t,r,n){var i,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))):(n&&r&&(a.deviceId=null===(i=r.find((t=>t.deviceId===n&&t.kind===e)))||void 0===i?void 0:i.deviceId),a)}function cv(e,t){t&&"audio"!==t||e.getAudioTracks().forEach((e=>e.stop())),t&&"video"!==t||e.getVideoTracks().forEach((e=>e.stop()))}function dv(e,{replaceStream:t,fallback:r=!0}={}){var n;return Xh(this,void 0,void 0,(function*(){let i,s,o,a=null;const c=!1===e.audioId?"video":!1===e.videoId&&"audio",d=iv||"video"!==c,l=rv(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!==i&&{error:String(i)}),e);d&&t&&cv(t,c);try{a=yield ov(l)}catch(s){if(i=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){if(l.audio&&l.video){try{a=yield ov(rv(Object.assign(Object.assign({},e),{audioId:!1})))}catch(e){if("NotFoundError"!==e.name)throw u(e,s)}try{a||(a=yield ov(rv(Object.assign(Object.assign({},e),{videoId:!1}))))}catch(e){throw u(e,s)}}}else if("NotAllowedError"===s.name||"NotReadableError"===s.name||"AbortError"===s.name)if(t&&!d)cv(t,c),o=e;else if("NotAllowedError"!==s.name){try{a=yield ov(rv(Object.assign(Object.assign({},e),{options:Object.assign(Object.assign({},e.options),{lax:!0})})))}catch(e){nv.warn("Tried getting stream again with laxer constraints, but failed: "+(""+e))}const t=(""+s).toLowerCase(),r={audio:"audioId",video:"videoId"}[(null===(n=/(video|audio)/.exec(t))||void 0===n?void 0:n[0])||c||""];if(!a&&r)try{a=yield ov(rv(Object.assign(Object.assign({},e),{[r]:null})))}catch(e){nv.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 ov(rv(Object.assign(Object.assign({},e),{[r]:!1})))}catch(e){nv.warn(`Re-tried without ${r}, but failed: ${""+e}`)}if(a)break}}}}if(o){const t=c?{audio:{videoId:!1},video:{audioId:!1}}[c]:{};s=rv(Object.assign(Object.assign(Object.assign(Object.assign({},e),o),{options:Object.assign(Object.assign({},e.options),{lax:o.lax})}),t));try{a=yield ov(s)}catch(e){throw u(e,i)}}if(!a)throw u(i);let p;return t&&(d||cv(t,c),p=function(e,t,r){const n=[];return r&&"audio"!==r||(n.push(...e.getAudioTracks()),t.getAudioTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),r&&"video"!==r||(n.push(...e.getVideoTracks()),t.getVideoTracks().forEach((t=>{t.replacement=!0,e.addTrack(t)}))),n.forEach((t=>{t.replaced=!0,e.removeTrack(t)})),n}(t,a,c),a=t),{error:i&&u(i),stream:a,replacedTracks:p}}))}function lv({oldDevices:e,newDevices:t,currentAudioId:r,currentVideoId:n,currentSpeakerId:i}){const s=function(e,t){const[r,n]=[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})})),{}))),i={};return e.forEach((e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[e.kind]={added:{},removed:{},changed:{}}),n[e.kind]&&n[e.kind][e.deviceId]||(i[e.kind].removed[e.deviceId]=e))})),t.forEach((e=>{e.kind&&e.deviceId&&(i[e.kind]||(i[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&&(i[e.kind].changed[e.deviceId]=e):i[e.kind].added[e.deviceId]=e)})),i}(e,t),o={},a={},c={};return[["audioinput",r],["videoinput",n],["audiooutput",i]].forEach((([e,r])=>{const n=s[e];if(n){if(r){if(n.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}}n.changed[r]&&(a[e]={deviceId:r})}if(Object.keys(n.added).length>0){const[t]=Object.keys(n.added).slice(0,1),r=n.added[t];c[e]={deviceId:r.deviceId,label:r.label,kind:r.kind}}if(Object.keys(n.removed).length>0){const[t]=Object.keys(n.removed).slice(0,1);o[e]=n.removed[t]}}})),{addedDevices:c,changedDevices:a,removedDevices:o}}var uv;!function(e){e.rtc_manager_created="rtc_manager_created",e.stream_added="stream_added"}(uv||(uv={}));var pv={exports:{}};pv.exports=function(e){return(e instanceof Buffer?e:Buffer.from(e.toString(),"binary")).toString("base64")};var hv=c(pv.exports);function fv(e,t){return function(){return e.apply(t,arguments)}}const{toString:mv}=Object.prototype,{getPrototypeOf:gv}=Object,vv=(e=>t=>{const r=mv.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),bv=e=>(e=e.toLowerCase(),t=>vv(t)===e),yv=e=>t=>typeof t===e,{isArray:wv}=Array,_v=yv("undefined");const Sv=bv("ArrayBuffer");const Cv=yv("string"),Rv=yv("function"),Tv=yv("number"),kv=e=>null!==e&&"object"==typeof e,Pv=e=>{if("object"!==vv(e))return!1;const t=gv(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},Ev=bv("Date"),Ov=bv("File"),Iv=bv("Blob"),Dv=bv("FileList"),xv=bv("URLSearchParams");function Mv(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),wv(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{const i=r?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(n=0;n<s;n++)o=i[n],t.call(null,e[o],o,e)}}function jv(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,i=r.length;for(;i-- >0;)if(n=r[i],t===n.toLowerCase())return n;return null}const Lv="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Av=e=>!_v(e)&&e!==Lv;const Nv=(Bv="undefined"!=typeof Uint8Array&&gv(Uint8Array),e=>Bv&&e instanceof Bv);var Bv;const Fv=bv("HTMLFormElement"),zv=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Vv=bv("RegExp"),Uv=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};Mv(r,((r,i)=>{let s;!1!==(s=t(r,i,e))&&(n[i]=s||r)})),Object.defineProperties(e,n)},$v="abcdefghijklmnopqrstuvwxyz",Gv="0123456789",qv={DIGIT:Gv,ALPHA:$v,ALPHA_DIGIT:$v+$v.toUpperCase()+Gv};const Hv=bv("AsyncFunction");var Wv={isArray:wv,isArrayBuffer:Sv,isBuffer:function(e){return null!==e&&!_v(e)&&null!==e.constructor&&!_v(e.constructor)&&Rv(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Rv(e.append)&&("formdata"===(t=vv(e))||"object"===t&&Rv(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Sv(e.buffer),t},isString:Cv,isNumber:Tv,isBoolean:e=>!0===e||!1===e,isObject:kv,isPlainObject:Pv,isUndefined:_v,isDate:Ev,isFile:Ov,isBlob:Iv,isRegExp:Vv,isFunction:Rv,isStream:e=>kv(e)&&Rv(e.pipe),isURLSearchParams:xv,isTypedArray:Nv,isFileList:Dv,forEach:Mv,merge:function e(){const{caseless:t}=Av(this)&&this||{},r={},n=(n,i)=>{const s=t&&jv(r,i)||i;Pv(r[s])&&Pv(n)?r[s]=e(r[s],n):Pv(n)?r[s]=e({},n):wv(n)?r[s]=n.slice():r[s]=n};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&Mv(arguments[e],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(Mv(t,((t,n)=>{r&&Rv(t)?e[n]=fv(t,r):e[n]=t}),{allOwnKeys:n}),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,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&gv(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:vv,kindOfTest:bv,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(wv(e))return e;let t=e.length;if(!Tv(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:Fv,hasOwnProperty:zv,hasOwnProp:zv,reduceDescriptors:Uv,freezeMethods:e=>{Uv(e,((t,r)=>{if(Rv(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Rv(n)&&(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={},n=e=>{e.forEach((e=>{r[e]=!0}))};return wv(e)?n(e):n(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)=>(e=+e,Number.isFinite(e)?e:t),findKey:jv,global:Lv,isContextDefined:Av,ALPHABET:qv,generateString:(e=16,t=qv.ALPHA_DIGIT)=>{let r="";const{length:n}=t;for(;e--;)r+=t[Math.random()*n|0];return r},isSpecCompliantForm:function(e){return!!(e&&Rv(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(kv(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const i=wv(e)?[]:{};return Mv(e,((e,t)=>{const s=r(e,n+1);!_v(s)&&(i[t]=s)})),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn:Hv,isThenable:e=>e&&(kv(e)||Rv(e))&&Rv(e.then)&&Rv(e.catch)};function Kv(e,t,r,n,i){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),n&&(this.request=n),i&&(this.response=i)}Wv.inherits(Kv,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:Wv.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const Jv=Kv.prototype,Qv={};["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=>{Qv[e]={value:e}})),Object.defineProperties(Kv,Qv),Object.defineProperty(Jv,"isAxiosError",{value:!0}),Kv.from=(e,t,r,n,i,s)=>{const o=Object.create(Jv);return Wv.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),Kv.call(o,e.message,t,r,n,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Xv(e){return Wv.isPlainObject(e)||Wv.isArray(e)}function Yv(e){return Wv.endsWith(e,"[]")?e.slice(0,-2):e}function Zv(e,t,r){return e?e.concat(t).map((function(e,t){return e=Yv(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const eb=Wv.toFlatObject(Wv,{},null,(function(e){return/^is[A-Z]/.test(e)}));function tb(e,t,r){if(!Wv.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=Wv.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Wv.isUndefined(t[e])}))).metaTokens,i=r.visitor||d,s=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Wv.isSpecCompliantForm(t);if(!Wv.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Wv.isDate(e))return e.toISOString();if(!a&&Wv.isBlob(e))throw new Kv("Blob is not supported. Use a Buffer instead.");return Wv.isArrayBuffer(e)||Wv.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(Wv.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(Wv.isArray(e)&&function(e){return Wv.isArray(e)&&!e.some(Xv)}(e)||(Wv.isFileList(e)||Wv.endsWith(r,"[]"))&&(a=Wv.toArray(e)))return r=Yv(r),a.forEach((function(e,n){!Wv.isUndefined(e)&&null!==e&&t.append(!0===o?Zv([r],n,s):null===o?r:r+"[]",c(e))})),!1;return!!Xv(e)||(t.append(Zv(i,r,s),c(e)),!1)}const l=[],u=Object.assign(eb,{defaultVisitor:d,convertValue:c,isVisitable:Xv});if(!Wv.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!Wv.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),Wv.forEach(r,(function(r,s){!0===(!(Wv.isUndefined(r)||null===r)&&i.call(t,r,Wv.isString(s)?s.trim():s,n,u))&&e(r,n?n.concat(s):[s])})),l.pop()}}(e),t}function rb(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function nb(e,t){this._pairs=[],e&&tb(e,this,t)}const ib=nb.prototype;function sb(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ob(e,t,r){if(!t)return e;const n=r&&r.encode||sb,i=r&&r.serialize;let s;if(s=i?i(t,r):Wv.isURLSearchParams(t)?t.toString():new nb(t,r).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}ib.append=function(e,t){this._pairs.push([e,t])},ib.toString=function(e){const t=e?function(t){return e.call(this,t,rb)}:rb;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class ab{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){Wv.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var cb={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},db={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:nb,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const lb="undefined"!=typeof window&&"undefined"!=typeof document,ub=(pb="undefined"!=typeof navigator&&navigator.product,lb&&["ReactNative","NativeScript","NS"].indexOf(pb)<0);var pb;const hb="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts;var fb={...Object.freeze({__proto__:null,hasBrowserEnv:lb,hasStandardBrowserEnv:ub,hasStandardBrowserWebWorkerEnv:hb}),...db};function mb(e){function t(e,r,n,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&Wv.isArray(n)?n.length:s,a)return Wv.hasOwnProp(n,s)?n[s]=[n[s],r]:n[s]=r,!o;n[s]&&Wv.isObject(n[s])||(n[s]=[]);return t(e,r,n[s],i)&&Wv.isArray(n[s])&&(n[s]=function(e){const t={},r=Object.keys(e);let n;const i=r.length;let s;for(n=0;n<i;n++)s=r[n],t[s]=e[s];return t}(n[s])),!o}if(Wv.isFormData(e)&&Wv.isFunction(e.entries)){const r={};return Wv.forEachEntry(e,((e,n)=>{t(function(e){return Wv.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const gb={transitional:cb,adapter:["xhr","http"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=Wv.isObject(e);i&&Wv.isHTMLForm(e)&&(e=new FormData(e));if(Wv.isFormData(e))return n?JSON.stringify(mb(e)):e;if(Wv.isArrayBuffer(e)||Wv.isBuffer(e)||Wv.isStream(e)||Wv.isFile(e)||Wv.isBlob(e))return e;if(Wv.isArrayBufferView(e))return e.buffer;if(Wv.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return tb(e,new fb.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return fb.isNode&&Wv.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=Wv.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return tb(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),function(e,t,r){if(Wv.isString(e))try{return(t||JSON.parse)(e),Wv.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||gb.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&Wv.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw Kv.from(e,Kv.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:fb.classes.FormData,Blob:fb.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Wv.forEach(["delete","get","head","post","put","patch"],(e=>{gb.headers[e]={}}));var vb=gb;const bb=Wv.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 yb=Symbol("internals");function wb(e){return e&&String(e).trim().toLowerCase()}function _b(e){return!1===e||null==e?e:Wv.isArray(e)?e.map(_b):String(e)}function Sb(e,t,r,n,i){return Wv.isFunction(n)?n.call(this,t,r):(i&&(t=r),Wv.isString(t)?Wv.isString(n)?-1!==t.indexOf(n):Wv.isRegExp(n)?n.test(t):void 0:void 0)}class Cb{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=wb(t);if(!i)throw new Error("header name must be a non-empty string");const s=Wv.findKey(n,i);(!s||void 0===n[s]||!0===r||void 0===r&&!1!==n[s])&&(n[s||t]=_b(e))}const s=(e,t)=>Wv.forEach(e,((e,r)=>i(e,r,t)));return Wv.isPlainObject(e)||e instanceof this.constructor?s(e,t):Wv.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim())?s((e=>{const t={};let r,n,i;return e&&e.split("\n").forEach((function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&bb[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t):null!=e&&i(t,e,r),this}get(e,t){if(e=wb(e)){const r=Wv.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 n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(Wv.isFunction(t))return t.call(this,e,r);if(Wv.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=wb(e)){const r=Wv.findKey(this,e);return!(!r||void 0===this[r]||t&&!Sb(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=wb(e)){const i=Wv.findKey(r,e);!i||t&&!Sb(0,r[i],i,t)||(delete r[i],n=!0)}}return Wv.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!Sb(0,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return Wv.forEach(this,((n,i)=>{const s=Wv.findKey(r,i);if(s)return t[s]=_b(n),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(i):String(i).trim();o!==i&&delete t[i],t[o]=_b(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Wv.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&Wv.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")}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[yb]=this[yb]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=wb(e);t[n]||(!function(e,t){const r=Wv.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})}))}(r,e),t[n]=!0)}return Wv.isArray(e)?e.forEach(n):n(e),this}}Cb.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Wv.reduceDescriptors(Cb.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),Wv.freezeMethods(Cb);var Rb=Cb;function Tb(e,t){const r=this||vb,n=t||r,i=Rb.from(n.headers);let s=n.data;return Wv.forEach(e,(function(e){s=e.call(r,s,i.normalize(),t?t.status:void 0)})),i.normalize(),s}function kb(e){return!(!e||!e.__CANCEL__)}function Pb(e,t,r){Kv.call(this,null==e?"canceled":e,Kv.ERR_CANCELED,t,r),this.name="CanceledError"}Wv.inherits(Pb,Kv,{__CANCEL__:!0});var Eb=fb.hasStandardBrowserEnv?{write(e,t,r,n,i,s){const o=[e+"="+encodeURIComponent(t)];Wv.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),Wv.isString(n)&&o.push("path="+n),Wv.isString(i)&&o.push("domain="+i),!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 Ob(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}var Ib=fb.hasStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let r;function n(r){let n=r;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return r=n(window.location.href),function(e){const t=Wv.isString(e)?n(e):e;return t.protocol===r.protocol&&t.host===r.host}}():function(){return!0};function Db(e,t){let r=0;const n=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=n[o];i||(i=c),r[s]=a,n[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-i<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return i=>{const s=i.loaded,o=i.lengthComputable?i.total:void 0,a=s-r,c=n(a);r=s;const d={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:i};d[t?"download":"upload"]=!0,e(d)}}var xb="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){let n=e.data;const i=Rb.from(e.headers).normalize();let s,o,{responseType:a,withXSRFToken:c}=e;function d(){e.cancelToken&&e.cancelToken.unsubscribe(s),e.signal&&e.signal.removeEventListener("abort",s)}if(Wv.isFormData(n))if(fb.hasStandardBrowserEnv||fb.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if(!1!==(o=i.getContentType())){const[e,...t]=o?o.split(";").map((e=>e.trim())).filter(Boolean):[];i.setContentType([e||"multipart/form-data",...t].join("; "))}let l=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",r=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(t+":"+r))}const u=Ob(e.baseURL,e.url);function p(){if(!l)return;const n=Rb.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders());!function(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new Kv("Request failed with status code "+r.status,[Kv.ERR_BAD_REQUEST,Kv.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}((function(e){t(e),d()}),(function(e){r(e),d()}),{data:a&&"text"!==a&&"json"!==a?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null}if(l.open(e.method.toUpperCase(),ob(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=p:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(p)},l.onabort=function(){l&&(r(new Kv("Request aborted",Kv.ECONNABORTED,e,l)),l=null)},l.onerror=function(){r(new Kv("Network Error",Kv.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||cb;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(new Kv(t,n.clarifyTimeoutError?Kv.ETIMEDOUT:Kv.ECONNABORTED,e,l)),l=null},fb.hasStandardBrowserEnv&&(c&&Wv.isFunction(c)&&(c=c(e)),c||!1!==c&&Ib(u))){const t=e.xsrfHeaderName&&e.xsrfCookieName&&Eb.read(e.xsrfCookieName);t&&i.set(e.xsrfHeaderName,t)}void 0===n&&i.setContentType(null),"setRequestHeader"in l&&Wv.forEach(i.toJSON(),(function(e,t){l.setRequestHeader(t,e)})),Wv.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),a&&"json"!==a&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",Db(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",Db(e.onUploadProgress)),(e.cancelToken||e.signal)&&(s=t=>{l&&(r(!t||t.type?new Pb(null,e,l):t),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(s),e.signal&&(e.signal.aborted?s():e.signal.addEventListener("abort",s)));const h=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);h&&-1===fb.protocols.indexOf(h)?r(new Kv("Unsupported protocol "+h+":",Kv.ERR_BAD_REQUEST,e)):l.send(n||null)}))};const Mb={http:null,xhr:xb};Wv.forEach(Mb,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));const jb=e=>`- ${e}`,Lb=e=>Wv.isFunction(e)||null===e||!1===e;var Ab=e=>{e=Wv.isArray(e)?e:[e];const{length:t}=e;let r,n;const i={};for(let s=0;s<t;s++){let t;if(r=e[s],n=r,!Lb(r)&&(n=Mb[(t=String(r)).toLowerCase()],void 0===n))throw new Kv(`Unknown adapter '${t}'`);if(n)break;i[t||"#"+s]=n}if(!n){const e=Object.entries(i).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new Kv("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(jb).join("\n"):" "+jb(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Nb(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Pb(null,e)}function Bb(e){Nb(e),e.headers=Rb.from(e.headers),e.data=Tb.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Ab(e.adapter||vb.adapter)(e).then((function(t){return Nb(e),t.data=Tb.call(e,e.transformResponse,t),t.headers=Rb.from(t.headers),t}),(function(t){return kb(t)||(Nb(e),t&&t.response&&(t.response.data=Tb.call(e,e.transformResponse,t.response),t.response.headers=Rb.from(t.response.headers))),Promise.reject(t)}))}const Fb=e=>e instanceof Rb?e.toJSON():e;function zb(e,t){t=t||{};const r={};function n(e,t,r){return Wv.isPlainObject(e)&&Wv.isPlainObject(t)?Wv.merge.call({caseless:r},e,t):Wv.isPlainObject(t)?Wv.merge({},t):Wv.isArray(t)?t.slice():t}function i(e,t,r){return Wv.isUndefined(t)?Wv.isUndefined(e)?void 0:n(void 0,e,r):n(e,t,r)}function s(e,t){if(!Wv.isUndefined(t))return n(void 0,t)}function o(e,t){return Wv.isUndefined(t)?Wv.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,s){return s in t?n(r,i):s in e?n(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)=>i(Fb(e),Fb(t),!0)};return Wv.forEach(Object.keys(Object.assign({},e,t)),(function(n){const s=c[n]||i,o=s(e[n],t[n],n);Wv.isUndefined(o)&&s!==a||(r[n]=o)})),r}const Vb="1.6.7",Ub={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ub[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const $b={};Ub.transitional=function(e,t,r){function n(e,t){return"[Axios v1.6.7] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,s)=>{if(!1===e)throw new Kv(n(i," has been removed"+(t?" in "+t:"")),Kv.ERR_DEPRECATED);return t&&!$b[i]&&($b[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,s)}};var Gb={assertOptions:function(e,t,r){if("object"!=typeof e)throw new Kv("options must be an object",Kv.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const s=n[i],o=t[s];if(o){const t=e[s],r=void 0===t||o(t,s,e);if(!0!==r)throw new Kv("option "+s+" must be "+r,Kv.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new Kv("Unknown option "+s,Kv.ERR_BAD_OPTION)}},validators:Ub};const qb=Gb.validators;class Hb{constructor(e){this.defaults=e,this.interceptors={request:new ab,response:new ab}}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/,""):"";e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=zb(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&Gb.assertOptions(r,{silentJSONParsing:qb.transitional(qb.boolean),forcedJSONParsing:qb.transitional(qb.boolean),clarifyTimeoutError:qb.transitional(qb.boolean)},!1),null!=n&&(Wv.isFunction(n)?t.paramsSerializer={serialize:n}:Gb.assertOptions(n,{encode:qb.function,serialize:qb.function},!0)),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&Wv.merge(i.common,i[t.method]);i&&Wv.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete i[e]})),t.headers=Rb.concat(s,i);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=[Bb.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=Bb.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 ob(Ob((e=zb(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}Wv.forEach(["delete","get","head","options"],(function(e){Hb.prototype[e]=function(t,r){return this.request(zb(r||{},{method:e,url:t,data:(r||{}).data}))}})),Wv.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,i){return this.request(zb(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Hb.prototype[e]=t(),Hb.prototype[e+"Form"]=t(!0)}));var Wb=Hb;class Kb{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 n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,i){r.reason||(r.reason=new Pb(e,n,i),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)}static source(){let e;return{token:new Kb((function(t){e=t})),cancel:e}}}var Jb=Kb;const Qb={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(Qb).forEach((([e,t])=>{Qb[t]=e}));var Xb=Qb;const Yb=function e(t){const r=new Wb(t),n=fv(Wb.prototype.request,r);return Wv.extend(n,Wb.prototype,r,{allOwnKeys:!0}),Wv.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(zb(t,r))},n}(vb);function Zb(e,t){return Rt(e,t)}function ey(e,t){return r=>(n,i,s)=>e(i())?t(r)(n,i,s):(console.warn("Not authorized to perform this action"),!1)}function ty(e){return t=>(r,n,i)=>"connected"!==n().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):e(t)(r,n,i)}function ry(e,t){return Zb(e,((e,r)=>{const{getState:n}=r;return"connected"!==n().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 ny(e,t){return r=>(n,i,s)=>"connected"!==i().roomConnection.status?(console.warn("Action cannot be performed outside of a connected room"),!1):ey(e,t)(r)(n,i,s)}Yb.Axios=Wb,Yb.CanceledError=Pb,Yb.CancelToken=Jb,Yb.isCancel=kb,Yb.VERSION=Vb,Yb.toFormData=tb,Yb.AxiosError=Kv,Yb.Cancel=Yb.CanceledError,Yb.all=function(e){return Promise.all(e)},Yb.spread=function(e){return function(t){return e.apply(null,t)}},Yb.isAxiosError=function(e){return Wv.isObject(e)&&!0===e.isAxiosError},Yb.mergeConfig=zb,Yb.AxiosHeaders=Rb,Yb.formToJSON=e=>mb(Wv.isHTMLForm(e)?new FormData(e):e),Yb.getAdapter=Ab,Yb.HttpStatusCode=Xb,Yb.default=Yb;const iy=((e={})=>{const t=new Map,{extra:r,onError:n=ar}=e;zt(n,"onError");const i=e=>{let r=et(Array.from(t.values()),(t=>t.effect===e.effect));return r||(r=tr(e)),(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&rr(e)}))(r)};Object.assign(i,{withTypes:()=>i});const s=e=>{const{type:r,effect:n,predicate:i}=er(e),s=et(Array.from(t.values()),(e=>("string"==typeof r?e.type===r:e.predicate===i)&&e.effect===n));return s&&(s.unsubscribe(),e.cancelActive&&rr(s)),!!s};Object.assign(s,{withTypes:()=>s});const o=async(e,s,o,a)=>{const c=new AbortController,d=Zt(i,c.signal),l=[];try{e.pending.add(c),await Promise.resolve(e.effect(s,Jt({},o,{getOriginalState:a,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:Kt(c.signal),pause:Wt(c.signal),extra:r,signal:c.signal,fork:Yt(c.signal,l),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach(((e,t,r)=>{e!==c&&(Gt(e,Nt),r.delete(e))}))},cancel:()=>{Gt(c,Nt),e.pending.delete(c)},throwIfCancelled:()=>{qt(c.signal)}})))}catch(e){e instanceof Ft||nr(n,e,{raisedBy:"effect"})}finally{await Promise.all(l),Gt(c,Bt),e.pending.delete(c)}},a=(e=>()=>{e.forEach(rr),e.clear()})(t);return{middleware:e=>r=>c=>{if(!z(c))return r(c);if(ir.match(c))return i(c.payload);if(sr.match(c))return void a();if(or.match(c))return s(c.payload);let d=e.getState();const l=()=>{if(d===Qt)throw new Error(`${Xt}: getOriginalState can only be called synchronously`);return d};let u;try{if(u=r(c),t.size>0){const r=e.getState(),i=Array.from(t.values());for(const t of i){let i=!1;try{i=t.predicate(c,r,d)}catch(e){i=!1,nr(n,e,{raisedBy:"predicate"})}i&&o(t,c,e,l)}}}finally{d=Qt}return u},startListening:i,stopListening:s,clearListeners:a}})(),sy=iy.startListening,oy=(e,t)=>sy({predicate:(t,r,n)=>{const i=e.map((e=>e(n))),s=e.map((e=>e(r)));return i.some(((e,t)=>e!==s[t]))},effect:(r,{dispatch:n,getState:i,extra:s})=>{const o=e.map((e=>e(i())));t({dispatch:n,getState:i,extra:s},...o)}}),ay=It({name:"app",initialState:{isNodeSdk:!1,isActive:!1,isDialIn:!1,roomName:null,roomUrl:null,displayName:null,userAgent:"core:0.30.3",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:cy,doAppStart:dy}=ay.actions,ly=e=>e.app.isActive,uy=e=>e.app.isDialIn,py=e=>e.app.roomName,hy=e=>e.app.displayName,fy=e=>e.app.userAgent,my=e=>e.app.externalId;function gy(e){return Xe(`signalConnection/event/${e}`)}const vy={audioEnabled:gy("audioEnabled"),audioEnableRequested:gy("audioEnableRequested"),breakoutGroupJoined:gy("breakoutGroupJoined"),chatMessage:gy("chatMessage"),clientLeft:gy("clientLeft"),clientKicked:gy("clientKicked"),clientMetadataReceived:gy("clientMetadataReceived"),clientUnableToJoin:gy("clientUnableToJoin"),cloudRecordingStarted:gy("cloudRecordingStarted"),cloudRecordingStopped:gy("cloudRecordingStopped"),disconnect:gy("disconnect"),knockerLeft:gy("knockerLeft"),knockHandled:gy("knockHandled"),newClient:gy("newClient"),roomJoined:gy("roomJoined"),roomKnocked:gy("roomKnocked"),roomLeft:gy("roomLeft"),roomLocked:gy("roomLocked"),roomSessionEnded:gy("roomSessionEnded"),screenshareStarted:gy("screenshareStarted"),screenshareStopped:gy("screenshareStopped"),spotlightAdded:gy("spotlightAdded"),spotlightRemoved:gy("spotlightRemoved"),streamingStopped:gy("streamingStopped"),videoEnabled:gy("videoEnabled"),videoEnableRequested:gy("videoEnableRequested"),liveTranscriptionStarted:gy("liveTranscriptionStarted"),liveTranscriptionStopped:gy("liveTranscriptionStopped")},by={canLockRoom:["host"],canRequestAudioEnable:["host"],canRequestVideoEnable:["host"],canKickClient:["host"],canEndMeeting:["host"],canAskToSpeak:["host"],canSpotlight:["host"]},yy=It({name:"authorization",initialState:{roomKey:null,roleName:"none"},reducers:{setRoomKey:(e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload})},extraReducers:e=>{e.addCase(dy,((e,t)=>Object.assign(Object.assign({},e),{roomKey:t.payload.roomKey}))),e.addCase(vy.roomJoined,((e,t)=>{var r,n;const i=null===(n=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===n?void 0:n.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{roleName:(null==i?void 0:i.role.roleName)||"none"})}))}}),{setRoomKey:wy}=yy.actions,_y=e=>e.authorization.roomKey,Sy=e=>e.authorization.roleName,Cy=Ge(Sy,(e=>by.canLockRoom.includes(e))),Ry=Ge(Sy,(e=>by.canRequestAudioEnable.includes(e))),Ty=Ge(Sy,(e=>by.canRequestVideoEnable.includes(e))),ky=Ge(Sy,(e=>by.canKickClient.includes(e))),Py=Ge(Sy,(e=>by.canEndMeeting.includes(e))),Ey=Ge(Sy,(e=>by.canAskToSpeak.includes(e))),Oy=Ge(Sy,(e=>by.canSpotlight.includes(e)));function Iy(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}function Dy(e,t,r,n){return new(r||(r=Promise))((function(i,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){e.done?i(e.value):function(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(o,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const xy=It({name:"deviceCredentials",initialState:{isFetching:!1,data:null},reducers:{},extraReducers:e=>{e.addCase(My.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(My.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}))),e.addCase(My.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!0})))}}),My=Zb("deviceCredentials/doGetDeviceCredentials",((e,{extra:t})=>Dy(void 0,void 0,void 0,(function*(){try{return yield t.services.credentialsService.getCredentials()}catch(e){console.error(e)}})))),jy=e=>e.deviceCredentials;oy([Ge(ly,jy,((e,t)=>!(!e||t.isFetching||t.data)))],(({dispatch:e},t)=>{t&&e(My())}));const Ly=It({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(vy.disconnect,(e=>Object.assign(Object.assign({},e),{deviceIdentified:!1,status:"disconnected"})))}}),{deviceIdentifying:Ay,deviceIdentified:Ny,socketConnected:By,socketConnecting:Fy,socketDisconnected:zy,socketReconnecting:Vy}=Ly.actions,Uy=()=>(e,t)=>{if(Ky(t()))return;e(Fy());const r=function(){const e=new URL("wss://signal.appearin.net").origin;return new Ng(e,{autoConnect:!1})}();r.on("connect",(()=>e(By(r)))),r.on("device_identified",(()=>e(Ny()))),r.getManager().on("reconnect",(()=>e(Vy()))),function(e,t){e.on("room_joined",(e=>t(vy.roomJoined(e)))),e.on("new_client",(e=>t(vy.newClient(e)))),e.on("client_left",(e=>t(vy.clientLeft(e)))),e.on("client_kicked",(e=>t(vy.clientKicked(e)))),e.on("client_unable_to_join",(e=>t(vy.clientUnableToJoin(e)))),e.on("audio_enabled",(e=>t(vy.audioEnabled(e)))),e.on("video_enabled",(e=>t(vy.videoEnabled(e)))),e.on("audio_enable_requested",(e=>t(vy.audioEnableRequested(e)))),e.on("client_metadata_received",(e=>t(vy.clientMetadataReceived(e)))),e.on("chat_message",(e=>t(vy.chatMessage(e)))),e.on("disconnect",(()=>t(vy.disconnect()))),e.on("room_knocked",(e=>t(vy.roomKnocked(e)))),e.on("room_left",(()=>t(vy.roomLeft()))),e.on("room_locked",(e=>t(vy.roomLocked(e)))),e.on("room_session_ended",(e=>t(vy.roomSessionEnded(e)))),e.on("knocker_left",(e=>t(vy.knockerLeft(e)))),e.on("knock_handled",(e=>t(vy.knockHandled(e)))),e.on("screenshare_started",(e=>t(vy.screenshareStarted(e)))),e.on("screenshare_stopped",(e=>t(vy.screenshareStopped(e)))),e.on("cloud_recording_started",(e=>t(vy.cloudRecordingStarted(e)))),e.on("cloud_recording_stopped",(()=>t(vy.cloudRecordingStopped()))),e.on("streaming_stopped",(()=>t(vy.streamingStopped()))),e.on("spotlight_added",(e=>t(vy.spotlightAdded(e)))),e.on("spotlight_removed",(e=>t(vy.spotlightRemoved(e)))),e.on("live_transcription_started",(e=>t(vy.liveTranscriptionStarted(e)))),e.on("live_transcription_stopped",(e=>t(vy.liveTranscriptionStopped(e)))),e.on("video_enable_requested",(e=>t(vy.videoEnableRequested(e)))),e.on("breakout_group_joined",(e=>t(vy.breakoutGroupJoined(e))))}(r,e),r.connect()},$y=({deviceCredentials:e})=>(t,r)=>{const n=r(),i=Ky(n),s=Hy(n);i&&(s||(i.emit("identify_device",{deviceCredentials:e}),t(Ay())))},Gy=()=>(e,t)=>{const r=t();if("connected"===Wy(r)){const t=qy(r).socket;null==t||t.disconnect(),e(zy())}},qy=e=>e.signalConnection,Hy=e=>e.signalConnection.deviceIdentified,Wy=e=>e.signalConnection.status,Ky=e=>e.signalConnection.socket;oy([Ge(ly,Wy,((e,t)=>!(!e||!["ready","reconnecting"].includes(t))))],(({dispatch:e},t)=>{t&&e(Uy())}));const Jy=Ge(jy,Wy,Hy,(e=>e.signalConnection.isIdentifyingDevice),((e,t,r,n)=>!(!e.data||"connected"!==t||r||n)));oy([Jy,jy],(({dispatch:e},t,r)=>{t&&r.data&&e($y({deviceCredentials:r.data}))})),sy({actionCreator:vy.roomLeft,effect:(e,{dispatch:t})=>{t(Gy())}}),sy({actionCreator:vy.clientKicked,effect:(e,{dispatch:t})=>{t(Gy())}});const Qy=It({name:"chat",initialState:{chatMessages:[]},reducers:{},extraReducers(e){e.addCase(vy.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]})}))}}),Xy=ty((e=>(t,r)=>{const n=r(),i=qy(n).socket;null==i||i.emit("chat_message",{text:e.text})})),Yy=It({name:"cloudRecording",initialState:{isRecording:!1,error:null,startedAt:void 0},reducers:{recordingRequestStarted:e=>Object.assign(Object.assign({},e),{status:"requested"})},extraReducers:e=>{e.addCase(vy.cloudRecordingStopped,(e=>Object.assign(Object.assign({},e),{isRecording:!1,status:void 0}))),e.addCase(vy.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(vy.newClient,((e,{payload:t})=>{var r;const{client:n}=t;return"recorder"===(null===(r=n.role)||void 0===r?void 0:r.roleName)?Object.assign(Object.assign({},e),{isRecording:!0,status:"recording",startedAt:n.startedCloudRecordingAt?new Date(n.startedCloudRecordingAt).getTime():(new Date).getTime()}):e}))}}),{recordingRequestStarted:Zy}=Yy.actions,ew=ty((()=>(e,t)=>{const r=t(),n=qy(r).socket,i=rw(r);i&&["recording","requested"].includes(i)||(null==n||n.emit("start_recording",{recording:"cloud"}),e(Zy()))})),tw=ty((()=>(e,t)=>{const r=t(),n=qy(r).socket;null==n||n.emit("stop_recording")})),rw=e=>e.cloudRecording.status,nw=It({initialState:{data:null,isFetching:!1,error:null},name:"organization",reducers:{},extraReducers:e=>{e.addCase(iw.pending,(e=>Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(iw.fulfilled,((e,t)=>t.payload?Object.assign(Object.assign({},e),{isFetching:!1,data:t.payload}):Object.assign(Object.assign({},e),{isFetching:!0}))),e.addCase(iw.rejected,(e=>Object.assign(Object.assign({},e),{isFetching:!1,error:!0})))}}),iw=Zb("organization/doOrganizationFetch",((e,{extra:t,getState:r})=>Dy(void 0,void 0,void 0,(function*(){try{const e=r().app.roomUrl,n=yield t.services.fetchOrganizationFromRoomUrl(e||"");if(!n)throw new Error("Invalid room url");return n}catch(e){console.error(e)}})))),sw=e=>{var t;return null===(t=e.organization.data)||void 0===t?void 0:t.organizationId};function ow(e,{delay:t=500,edges:r}={}){let n,i=0;return(...s)=>{i+=1,r&&1===i&&e(...s),clearTimeout(n),n=setTimeout((()=>{(!r||i>1)&&e(...s),n=void 0,i=0}),t)}}oy([Ge(ly,(e=>e.organization),jy,((e,t,r)=>!(!e||t.data||t.isFetching||t.error||r.isFetching)))],(({dispatch:e},t)=>{t&&e(iw())}));const aw=It({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:n}=t.payload;return Object.assign(Object.assign({},e),{currentCameraDeviceId:n.deviceId,currentMicrophoneDeviceId:r.deviceId,busyDeviceIds:e.busyDeviceIds.filter((e=>e!==r.deviceId&&e!==n.deviceId))})}},extraReducers:e=>{e.addCase(dy,((e,t)=>Object.assign(Object.assign({},e),{options:t.payload.localMediaOptions}))),e.addCase(Sw.pending,((e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:n,isSettingMicrophoneDevice:r})})),e.addCase(Sw.fulfilled,((e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice})})),e.addCase(Sw.rejected,((e,t)=>{const{audio:r,video:n}=t.meta.arg;return Object.assign(Object.assign({},e),{isSettingCameraDevice:!n&&e.isSettingCameraDevice,isSettingMicrophoneDevice:!r&&e.isSettingMicrophoneDevice,cameraDeviceError:n?t.error:e.cameraDeviceError,microphoneDeviceError:r?t.error:e.microphoneDeviceError})})),e.addCase(yw.pending,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!0}))),e.addCase(yw.fulfilled,(e=>Object.assign(Object.assign({},e),{isTogglingCamera:!1}))),e.addCase(Cw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{devices:t.payload.devices}))),e.addCase(Tw.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(Tw.fulfilled,((e,{payload:{stream:t,onDeviceChange:r}})=>{let n,i,s=!1,o=!1;const a=t.getAudioTracks()[0],c=t.getVideoTracks()[0];return a&&(i=a.getSettings().deviceId,o=a.enabled),c&&(s=c.enabled,n=c.getSettings().deviceId),Object.assign(Object.assign({},e),{stream:t,status:"started",currentCameraDeviceId:n,currentMicrophoneDeviceId:i,cameraEnabled:s,microphoneEnabled:o,onDeviceChange:r})})),e.addCase(Tw.rejected,((e,t)=>Object.assign(Object.assign({},e),{status:"error",startError:t.error}))),e.addCase(Rw.pending,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!0}))),e.addCase(Rw.fulfilled,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1}))),e.addCase(Rw.rejected,(e=>Object.assign(Object.assign({},e),{isSwitchingStream:!1})))}}),{deviceBusy:cw,setCurrentCameraDeviceId:dw,setCurrentMicrophoneDeviceId:lw,setCurrentSpeakerDeviceId:uw,toggleCameraEnabled:pw,toggleMicrophoneEnabled:hw,toggleLowDataModeEnabled:fw,setLocalMediaOptions:mw,setLocalMediaStream:gw,localMediaStopped:vw,localStreamMetadataUpdated:bw}=aw.actions,yw=Zb("localMedia/doToggleCamera",((e,{getState:t,rejectWithValue:r})=>Dy(void 0,void 0,void 0,(function*(){const e=t(),n=Bw(e);if(!n)return;let i=n.getVideoTracks()[0];const s=Dw(e);try{if(s)if(i)i.enabled=!0;else{const t=zw(e),r=Ew(e);yield dv(Object.assign(Object.assign({},t),{audioId:!1,videoId:r,type:"exact"}),{replaceStream:n}),i=n.getVideoTracks()[0]}else{if(!i)return;i.enabled=!1,i.stop(),n.removeTrack(i)}n.dispatchEvent(new CustomEvent("stopresumevideo",{detail:{track:i,enable:s}}))}catch(e){return r(e)}})))),ww=Zb("localMedia/doToggleMicrophone",((e,{getState:t})=>{var r;const n=t(),i=Bw(n);if(!i)return;const s=xw(n),o=null===(r=i.getAudioTracks())||void 0===r?void 0:r[0];o&&(o.enabled=s)})),_w=()=>(e,t)=>{const r=t();if(!Bw(r))return;const n=Ew(r),i=Ow(r);e(Rw({audioId:i,videoId:n}))},Sw=Zb("localMedia/reactSetDevice",(({audio:e,video:t},{getState:r,rejectWithValue:n})=>Dy(void 0,void 0,void 0,(function*(){try{const n=r(),i=Bw(n);if(!i)throw new Error("No stream");const s=!!e&&Ow(n),o=!!t&&Ew(n),a=zw(n),{replacedTracks:c}=yield dv(Object.assign(Object.assign({},a),{audioId:s,videoId:o,type:"exact"}),{replaceStream:i}),d=xw(n);i.getAudioTracks().forEach((e=>e.enabled=d));const l=Dw(n);return i.getVideoTracks().forEach((e=>e.enabled=l)),{replacedTracks:c}}catch(e){return n(e)}})))),Cw=Zb("localMedia/doUpdateDeviceList",((e,{getState:t,dispatch:r,rejectWithValue:n})=>Dy(void 0,void 0,void 0,(function*(){var e,i,s,o;const a=t();let c=[],d=[];const l=Bw(a);try{c=yield navigator.mediaDevices.enumerateDevices(),d=jw(a);if(!(l&&!Fw(a)&&c&&d&&d.find((e=>e.deviceId))))return{devices:c};const{changedDevices:t,addedDevices:n}=lv({oldDevices:d,newDevices:c});let u=null===(e=t.audioinput)||void 0===e?void 0:e.deviceId,p=null===(i=t.videoinput)||void 0===i?void 0:i.deviceId;return void 0===u&&(u=null===(s=n.audioinput)||void 0===s?void 0:s.deviceId),void 0===p&&(p=null===(o=n.videoinput)||void 0===o?void 0:o.deviceId),void 0===u&&void 0===p||r(Rw({audioId:u,videoId:p})),{devices:c}}catch(e){return n(e)}})))),Rw=Zb("localMedia/doSwitchLocalStream",(({audioId:e,videoId:t},{dispatch:r,getState:n,rejectWithValue:i})=>Dy(void 0,void 0,void 0,(function*(){const s=n(),o=Bw(s),a=zw(s),c=!(!t||e)||!(t||!e);if(o)try{const{replacedTracks:n}=yield dv(Object.assign(Object.assign({},a),{audioId:void 0!==e&&e,videoId:void 0!==t&&t,type:"exact"}),{replaceStream:o}),i=e||t;return c&&i&&r(cw({deviceId:i})),{replacedTracks:n}}catch(n){console.error(n);const s=e||t;return c&&s&&r(cw({deviceId:s})),i(n)}})))),Tw=Zb("localMedia/doStartLocalMedia",((e,{getState:t,dispatch:r,rejectWithValue:n})=>Dy(void 0,void 0,void 0,(function*(){const i=ow((()=>{r(Cw())}),{delay:500});if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",i),"getTracks"in e)return Promise.resolve({stream:e,onDeviceChange:i});if(!e.audio&&!e.video)return{stream:new MediaStream,onDeviceChange:i};r(mw({options:e}));try{yield r(Cw());const n=t(),s=zw(n),{stream:o}=yield dv(Object.assign(Object.assign({},s),{audioId:e.audio,videoId:e.video}));return{stream:o,onDeviceChange:i}}catch(e){return n(e)}})))),kw=()=>(e,t)=>{const r=Bw(t()),n=Aw(t()).onDeviceChange;null==r||r.getTracks().forEach((e=>{e.stop()})),navigator.mediaDevices&&n&&navigator.mediaDevices.removeEventListener("devicechange",n),e(vw())},Pw=e=>e.localMedia.busyDeviceIds,Ew=e=>e.localMedia.currentCameraDeviceId,Ow=e=>e.localMedia.currentMicrophoneDeviceId,Iw=e=>e.localMedia.currentSpeakerDeviceId,Dw=e=>e.localMedia.cameraEnabled,xw=e=>e.localMedia.microphoneEnabled,Mw=e=>e.localMedia.lowDataMode,jw=e=>e.localMedia.devices,Lw=e=>e.localMedia.options;Ge(Lw,(e=>!!e));const Aw=e=>e.localMedia,Nw=e=>e.localMedia.status,Bw=e=>e.localMedia.stream,Fw=e=>e.localMedia.isSwitchingStream,zw=Ge(jw,Ew,Ow,Mw,((e,t,r,n)=>({devices:e,videoId:t,audioId:r,options:{disableAEC:!1,disableAGC:!1,hd:!0,lax:!1,lowDataMode:n,simulcast:!0,widescreen:!0}}))),Vw=Ge(Nw,(e=>"starting"===e)),Uw=Ge(jw,Pw,((e,t)=>e.filter((e=>"videoinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),$w=Ge(jw,Pw,((e,t)=>e.filter((e=>"audioinput"===e.kind)).filter((e=>!t.includes(e.deviceId))))),Gw=Ge(jw,(e=>e.filter((e=>"audiooutput"===e.kind))));oy([Ge(ly,Nw,Lw,((e,t,r)=>{if(e&&["inactive","stopped"].includes(t)&&r)return r}))],(({dispatch:e},t)=>{t&&e(Tw(t))}));oy([Ge(ly,Nw,Lw,((e,t,r)=>!e&&"inactive"!==t&&!!r))],(({dispatch:e},t)=>{t&&e(kw())})),sy({predicate:(e,t,r)=>{const n=xw(r),i=xw(t);return"started"===Nw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(ww())}}),sy({predicate:(e,t,r)=>{const n=Mw(r),i=Mw(t);return"started"===Nw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(_w())}}),sy({predicate:(e,t,r)=>{if(t.localMedia.isTogglingCamera)return!1;const n=Dw(r),i=Dw(t);return"started"===Nw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(yw())}}),sy({predicate:(e,t,r)=>{const n=Ew(r),i=Ew(t);return"started"===Nw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Sw({audio:!1,video:!0}))}}),sy({predicate:(e,t,r)=>{const n=Ow(r),i=Ow(t);return"started"===Nw(r)&&n!==i},effect:(e,{dispatch:t})=>{t(Sw({audio:!0,video:!1}))}}),sy({matcher:yt(Tw.fulfilled,Cw.fulfilled,Rw.fulfilled,Rw.rejected),effect:(e,{dispatch:t,getState:r})=>{const n=r(),i=Bw(n),s=jw(n);if(!i)return;const o=function({audioTrack:e,videoTrack:t,devices:r,stoppedVideoTrack:n,lastAudioId:i,lastVideoId:s}){const o=e=>"live"===(null==e?void 0:e.readyState)?e:null;return t=o(t)||n,e=o(e),{video:av("videoinput",t,r,s),audio:av("audioinput",e,r,i)}}({audioTrack:i.getAudioTracks()[0],videoTrack:i.getVideoTracks()[0],devices:s});t(bw(o))}}),sy({actionCreator:vy.audioEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(hw({enabled:!1}))}}),sy({actionCreator:vy.videoEnableRequested,effect:({payload:e},{dispatch:t})=>{const{enable:r}=e;r||t(pw({enabled:!1}))}});const qw=["recorder","streamer"],Hw=It({name:"localParticipant",initialState:{displayName:"",id:"",breakoutGroup:null,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})},extraReducers:e=>{e.addCase(dy,((e,t)=>Object.assign(Object.assign({},e),{displayName:t.payload.displayName}))),e.addCase(Jw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isAudioEnabled:t.payload}))),e.addCase(Qw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{isVideoEnabled:t.payload}))),e.addCase(Xw.fulfilled,((e,t)=>Object.assign(Object.assign({},e),{stickyReaction:t.payload}))),e.addCase(vy.roomJoined,((e,t)=>{var r,n;const i=null===(n=null===(r=t.payload)||void 0===r?void 0:r.room)||void 0===n?void 0:n.clients.find((e=>{var r;return e.id===(null===(r=t.payload)||void 0===r?void 0:r.selfId)}));return Object.assign(Object.assign({},e),{id:t.payload.selfId,roleName:(null==i?void 0:i.role.roleName)||"none",clientClaim:t.payload.clientClaim,breakoutGroup:(null==i?void 0:i.breakoutGroup)||null})})),e.addCase(vy.breakoutGroupJoined,((e,t)=>{var r,n;return(null===(r=t.payload)||void 0===r?void 0:r.clientId)!==e.id?e:Object.assign(Object.assign({},e),{breakoutGroup:null===(n=t.payload)||void 0===n?void 0:n.group})}))}}),{setDisplayName:Ww}=Hw.actions,Kw=ty((e=>(t,r)=>{const n=r(),i=qy(n).socket;null==i||i.emit("send_client_metadata",{type:"UserData",payload:{displayName:e.displayName}}),t(Ww({displayName:e.displayName}))})),Jw=ry("localParticipant/doEnableAudio",((e,{dispatch:t,getState:r})=>Dy(void 0,void 0,void 0,(function*(){const n=r(),i=qy(n).socket;return null==i||i.emit("enable_audio",{enabled:e.enabled}),e.enabled&&t(Xw({enabled:!1})),e.enabled})))),Qw=ry("localParticipant/doEnableVideo",((e,{getState:t})=>Dy(void 0,void 0,void 0,(function*(){const r=t(),n=qy(r).socket;return null==n||n.emit("enable_video",{enabled:e.enabled}),e.enabled})))),Xw=ry("localParticipant/doSetLocalStickyReaction",((e,{getState:t,rejectWithValue:r})=>Dy(void 0,void 0,void 0,(function*(){var n;const i=t(),s=r_(i),o=Boolean(s),a=null!==(n=e.enabled)&&void 0!==n?n:!o;if(a===o)return r(s);return a?{reaction:"✋",timestamp:(new Date).toISOString()}:null})))),Yw=ty((()=>(e,t)=>{const r=t(),n=qy(r).socket,i={displayName:t_(r),stickyReaction:r_(r)};null==n||n.emit("send_client_metadata",{type:"UserData",payload:i})})),Zw=e=>e.localParticipant,e_=e=>e.localParticipant.id,t_=e=>e.localParticipant.displayName,r_=e=>e.localParticipant.stickyReaction,n_=Ge(Zw,Bw,((e,t)=>{const r={id:e.id,clientId:e.id,displayName:e.displayName,stream:t,isLocalClient:!0,isAudioEnabled:e.isAudioEnabled,isVideoEnabled:e.isVideoEnabled};return qw.includes(e.roleName)?null:r}));sy({actionCreator:pw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isVideoEnabled:i}=Zw(r());t(Qw({enabled:n||!i}))}}),sy({actionCreator:hw,effect:({payload:e},{dispatch:t,getState:r})=>{const{enabled:n}=e,{isAudioEnabled:i}=Zw(r());t(Jw({enabled:n||!i}))}}),oy([t_,r_],(({dispatch:e})=>{e(Yw())}));const i_=It({initialState:{session:null,status:"ready",error:null},name:"roomConnection",reducers:{connectionStatusChanged:(e,t)=>Object.assign(Object.assign({},e),{status:t.payload})},extraReducers:e=>{e.addCase(vy.roomJoined,((e,t)=>{var r,n;const{error:i,isLocked:s}=t.payload;return"room_locked"===i&&s?Object.assign(Object.assign({},e),{status:"room_locked"}):i?Object.assign(Object.assign({},e),{status:"disconnected",error:i}):Object.assign(Object.assign({},e),{status:"connected",session:null!==(n=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==n?n:null})})),e.addCase(vy.disconnect,(e=>["kicked","left"].includes(e.status)?Object.assign({},e):Object.assign(Object.assign({},e),{status:"disconnected"}))),e.addCase(vy.newClient,((e,t)=>{var r,n;return Object.assign(Object.assign({},e),{session:null!==(n=null===(r=t.payload.room)||void 0===r?void 0:r.session)&&void 0!==n?n:null})})),e.addCase(vy.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(vy.clientKicked,(e=>Object.assign(Object.assign({},e),{status:"kicked"}))),e.addCase(vy.roomLeft,(e=>Object.assign(Object.assign({},e),{status:"left"}))),e.addCase(Vy,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"})))}}),{connectionStatusChanged:s_}=i_.actions,o_=()=>(e,t)=>{const r=t(),n=qy(r).socket,i=py(r),s=_y(r),o=hy(r),a=uy(r),c=fy(r),d=my(r),l=sw(r);"room_locked"===c_(r)?(null==n||n.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:i,userAgent:c,externalId:d}),e(s_("knocking"))):console.warn("Room is not locked, knock aborted")},a_=()=>(e,t)=>{const r=t(),n=qy(r).socket,i=py(r),s=_y(r),o=hy(r),a=fy(r),c=my(r),d=uy(r),l=sw(r),u=Dw(t()),p=xw(t()),h=(e=>e.localParticipant.clientClaim)(t());null==n||n.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:i,userAgent:a,externalId:c},h&&{clientClaim:h})),e(s_("connecting"))},c_=e=>e.roomConnection.status;function d_(e){return Xe(`rtcConnection/event/${e}`)}oy([Ge([ly,sw,c_,Hy,Nw,e=>e.roomConnection.error],((e,t,r,n,i,s)=>!(!(e&&"started"===i&&n&&t&&["ready","reconnecting","disconnected"].includes(r))||s)))],(({dispatch:e},t)=>{t&&e(a_())})),sy({actionCreator:vy.knockHandled,effect:({payload:e},{dispatch:t,getState:r})=>{const{clientId:n,resolution:i}=e,s=r();n===e_(s)&&("accepted"===i?(t(wy(e.metadata.roomKey)),t(a_())):"rejected"===i&&t(s_("knock_rejected")))}}),sy({actionCreator:cy,effect:(e,{dispatch:t,getState:r})=>{const n=r();if("connected"===c_(n)){const e=qy(n).socket;null==e||e.emit("leave_room"),t(s_("leaving"))}else Gy()}});const l_={rtcManagerCreated:d_("rtcManagerCreated"),rtcManagerDestroyed:d_("rtcManagerDestroyed"),streamAdded:d_("streamAdded")};function u_(e,t=!1){const{streams:r,role:n,breakoutGroup:i}=e,s=Iy(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==n?void 0:n.roleName)||"none",presentationStream:null,breakoutGroup:i||null,newJoiner:t})}function p_(e,t){const r=e.remoteParticipants.findIndex((e=>e.id===t));return{index:r,participant:e.remoteParticipants[r]}}function h_(e,t,r){const{participant:n,index:i}=p_(e,t);return n?Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.slice(0,i),Object.assign(Object.assign({},n),r),...e.remoteParticipants.slice(i+1)]}):(console.error(`Did not find client for update ${t}`),e)}function f_(e,t,r,n){const{participant:i}=p_(e,t);if(!i)return console.error(`No client ${t} found to update stream ${r} ${n}`),e;const s=i.streams.findIndex((e=>e.id===r)),o=[...i.streams];return o[s]=Object.assign(Object.assign({},o[s]),{state:n}),h_(e,t,{streams:o})}function m_(e,t,r){const{participant:n}=p_(e,t);return!n||n.streams.find((e=>e.id===r))?(console.warn(`No participant ${t} or stream ${r} already exists`),e):h_(e,t,{streams:[...n.streams,{id:r,state:"to_accept"}]})}const g_=It({name:"remoteParticipants",initialState:{remoteParticipants:[]},reducers:{streamStatusUpdated:(e,t)=>{let r=e;for(const{clientId:e,streamId:n,state:i}of t.payload)r=f_(r,e,n,i);return r},participantStreamAdded:(e,t)=>{const{clientId:r,stream:n}=t.payload;return h_(e,r,{stream:n})},participantStreamIdAdded:(e,t)=>{const{clientId:r,streamId:n}=t.payload;return m_(e,r,n)}},extraReducers:e=>{e.addCase(vy.roomJoined,((e,t)=>{var r;if(!(null===(r=t.payload)||void 0===r?void 0:r.room))return e;const n=t.payload.selfId,{clients:i}=t.payload.room;return Object.assign(Object.assign({},e),{remoteParticipants:i.filter((e=>e.id!==n)).map((e=>u_(e)))})})),e.addCase(l_.streamAdded,((e,t)=>function(e,t){const{clientId:r,stream:n,streamType:i}=t;let{streamId:s}=t;const{participant:o}=p_(e,r);if(!o)return console.error(`Did not find client ${r} for adding stream`),e;const a=e.remoteParticipants;s||(s=n.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"===i||!c.stream&&!i&&!d?h_(e,r,{stream:n}):h_(e,r,{presentationStream:n})}(e,t.payload))),e.addCase(vy.newClient,((e,t)=>{const{client:r}=t.payload;return function(e,t){const{participant:r}=p_(e,t.id);return r?(console.warn(`Client already existing ${t.id}. Ignoring`),e):Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t]})}(e,u_(r,!0))})),e.addCase(vy.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(vy.audioEnabled,((e,t)=>{const{clientId:r,isAudioEnabled:n}=t.payload;return h_(e,r,{isAudioEnabled:n})})),e.addCase(vy.videoEnabled,((e,t)=>{const{clientId:r,isVideoEnabled:n}=t.payload;return h_(e,r,{isVideoEnabled:n})})),e.addCase(vy.clientMetadataReceived,((e,t)=>{const{error:r,payload:n}=t.payload;if(r||!n)return console.warn(r||"Client metadata error received"),e;const{clientId:i,displayName:s,stickyReaction:o}=n;return h_(e,i,{displayName:s,stickyReaction:o})})),e.addCase(vy.breakoutGroupJoined,((e,t)=>{const{clientId:r,group:n}=t.payload;return h_(e,r,{breakoutGroup:n||null})})),e.addCase(vy.screenshareStarted,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return m_(e,r,n)})),e.addCase(vy.screenshareStopped,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return function(e,t,r){var n,i;const{participant:s}=p_(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===(n=s.presentationStream)||void 0===n?void 0:n.inboundId)||(null===(i=s.presentationStream)||void 0===i?void 0:i.id),c=s.streams.findIndex((e=>e.id===r));return h_(e,t,Object.assign(Object.assign({streams:s.streams.filter(((e,t)=>t!==c))},o===r&&{stream:null}),a===r&&{presentationStream:null}))}(e,r,n)}))}}),{participantStreamAdded:v_,participantStreamIdAdded:b_,streamStatusUpdated:y_}=g_.actions,w_=ny((e=>Ry(e)),(e=>(t,r)=>{const n=r(),i=Ey(n);if(e.enable&&!i)return void console.warn("Not authorized to perform this action");const s=qy(n).socket;null==s||s.emit("request_audio_enable",e)})),__=ny((e=>Ty(e)),(e=>(t,r)=>{const n=r(),i=qy(n).socket;null==i||i.emit("request_video_enable",e)})),S_=e=>e.remoteParticipants.remoteParticipants,C_=Ge(S_,(e=>e.filter((e=>!qw.includes(e.roleName)))));Ge(S_,(e=>e.length+1));const R_=Ge(C_,Zw,((e,t)=>qw.includes(t.roleName)?e.length:e.length+1)),T_=It({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(P_.pending,(e=>Object.assign(Object.assign({},e),{status:"starting"}))),e.addCase(P_.fulfilled,((e,{payload:{stream:t}})=>Object.assign(Object.assign({},e),{status:"active",stream:t}))),e.addCase(P_.rejected,((e,{payload:t})=>Object.assign(Object.assign({},e),{error:t,status:"inactive",stream:null})))}}),{stopScreenshare:k_}=T_.actions,P_=ry("localScreenshare/doStartScreenshare",((e,{dispatch:t,getState:r,rejectWithValue:n})=>Dy(void 0,void 0,void 0,(function*(){var e;try{const n=r(),i=O_(n);if(i)return{stream:i};const s=yield navigator.mediaDevices.getDisplayMedia(),o=()=>{t(E_())};return"oninactive"in s?s.addEventListener("inactive",o):null===(e=s.getVideoTracks()[0])||void 0===e||e.addEventListener("ended",o),{stream:s}}catch(e){return n(e)}})))),E_=ty((()=>(e,t)=>{const r=t(),n=O_(r);n&&(n.getTracks().forEach((e=>e.stop())),e(k_({stream:n})))})),O_=e=>e.localScreenshare.stream;sy({actionCreator:vw,effect:(e,{getState:t})=>{const r=t(),n=O_(r);n&&(null==n||n.getTracks().forEach((e=>{e.stop()})))}});const I_=e=>({emit:(t,r)=>{"rtc_manager_created"===t?e(G_(r)):"stream_added"===t?e(l_.streamAdded(r)):"rtc_manager_destroyed"===t&&e(N_())}}),D_={dispatcherCreated:!1,error:null,isCreatingDispatcher:!1,reportedStreamResolutions:{},rtcManager:null,rtcManagerDispatcher:null,rtcManagerInitialized:!1,status:"inactive",isAcceptingStreams:!1},x_=It({name:"rtcConnection",initialState:D_,reducers:{isAcceptingStreams:(e,t)=>Object.assign(Object.assign({},e),{isAcceptingStreams:t.payload}),resolutionReported:(e,t)=>{const{streamId:r,width:n,height:i}=t.payload;return Object.assign(Object.assign({},e),{reportedStreamResolutions:Object.assign(Object.assign({},e.reportedStreamResolutions),{[r]:{width:n,height:i}})})},rtcDisconnected:()=>Object.assign({},D_),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})},extraReducers:e=>{e.addCase(Vy,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"}))),e.addCase(vy.roomJoined,(e=>Object.assign(Object.assign({},e),{status:"reconnecting"===e.status?"ready":e.status})))}}),{resolutionReported:M_,rtcDispatcherCreated:j_,rtcDisconnected:L_,rtcManagerCreated:A_,rtcManagerDestroyed:N_,rtcManagerInitialized:B_,isAcceptingStreams:F_}=x_.actions,z_=()=>(e,t)=>{const r=t(),n=qy(r).socket,i=H_(r).rtcManagerDispatcher,s=Dw(r),o=xw(r),a=(e=>e.app.isNodeSdk)(r);if(i||!n)return;const c={getMediaConstraints:()=>({audio:o,video:s}),deferrable:e=>!e},d=new kg({emitter:I_(e),serverSocket:n,webrtcProvider:c,features:{isNodeSdk:a,lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,vp9On:!1,h264On:!1,simulcastScreenshareOn:!1,deviceHandlerFactory:a?wl.createFactory():void 0}});e(j_(d))},V_=()=>(e,t)=>{const{rtcManager:r}=H_(t());r&&r.disconnectAll(),e(L_())},U_=e=>(t,r)=>{var n;t(F_(!0));const i=r(),s=H_(i).rtcManager,o=S_(i);if(!s)throw new Error("No rtc manager");const a=null===(n=s.shouldAcceptStreamsFromBothSides)||void 0===n?void 0:n.call(s),c=[];for(const{clientId:t,streamId:r,state:n}of e){if(o.find((e=>e.id===t))){if("to_accept"===n||"new_accept"===n&&a||"old_accept"===n&&!a)s.acceptNewStream({streamId:"0"===r?t:r,clientId:t,shouldAddLocalVideo:"0"===r,activeBreakout:false});else if("new_accept"===n||"old_accept"===n);else if("to_unaccept"===n)null==s||s.disconnect("0"===r?t:r,false);else if("done_accept"!==n)continue;c.push({clientId:t,streamId:r,state:n.replace(/to_|new_|old_/,"done_")})}}t(y_(c)),t(F_(!1))},$_=({streamId:e,width:t,height:r})=>(n,i)=>{const{reportedStreamResolutions:s,rtcManager:o}=H_(i()),a=Bw(i());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}),n(M_({streamId:e,width:t,height:r}))},G_=e=>t=>{const{rtcManager:r}=e;t(A_(r))},q_=()=>(e,t)=>{const r=Bw(t()),n=H_(t()).rtcManager,i=Dw(t()),s=xw(t());r&&n&&n.addNewStream("0",r,!s,!i),e(B_())},H_=e=>e.rtcConnection,W_=e=>e.rtcConnection.rtcManagerInitialized,K_=e=>e.rtcConnection.rtcManager,J_=e=>e.rtcConnection.status;sy({actionCreator:Sw.fulfilled,effect:({payload:e},{getState:t})=>{const{replacedTracks:r}=e,{rtcManager:n}=H_(t()),i=Bw(t());null==r||r.forEach((e=>{((e,t)=>{const r=null==i?void 0:i.getTracks().find((t=>t.kind===e));r&&(null==n||n.replaceTrack(t,r))})(e.kind,e)}))}}),sy({actionCreator:P_.fulfilled,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=H_(t());null==n||n.addNewStream(r.id,r,!1,!0)}}),sy({actionCreator:cy,effect:(e,{getState:t})=>{const r=K_(t());null==r||r.rtcStatsDisconnect()}}),sy({actionCreator:k_,effect:({payload:e},{getState:t})=>{const{stream:r}=e,{rtcManager:n}=H_(t());null==n||n.removeStream(r.id,r,null)}}),sy({actionCreator:Rw.fulfilled,effect:({payload:e},{getState:t})=>{var r;const n=Bw(t()),{rtcManager:i}=H_(t());if(n&&i){const t=(e,t)=>{const r=n.getTracks().find((t=>t.kind===e));return r&&i.replaceTrack(t,r)};null===(r=null==e?void 0:e.replacedTracks)||void 0===r||r.forEach((e=>{t(e.kind,e)}))}}});oy([Ge(J_,ly,(e=>e.rtcConnection.dispatcherCreated),(e=>e.rtcConnection.isCreatingDispatcher),Ky,((e,t,r,n,i)=>!(!t||"inactive"!==e||r||n||!i)))],(({dispatch:e},t)=>{t&&e(z_())}));const Q_=Ge(K_,W_,Nw,((e,t,r)=>!("started"!==r||!e||t)));oy([Q_],(({dispatch:e},t)=>{t&&e(q_())}));oy([Ge(J_,ly,((e,t)=>!t&&!["inactive","disconnected"].includes(e)))],(({dispatch:e},t)=>{t&&e(V_())}));const X_=Ge(J_,S_,((e,t)=>{if("ready"!==e)return[];const r=[];for(const e of t){const{streams:t,id:n,newJoiner:i}=e;for(let e=0;e<t.length;e++){let s=t[e].id,o=t[e].state;(null==t?void 0:t.length)>1&&"0"===t[1].id&&(0===e?(s=t[1].id,o=t[1].state):1===e&&(s=t[0].id,o=t[0].state)),"done_accept"!==o&&r.push({clientId:n,streamId:s,state:(i&&"0"===s?"new":"to")+"_accept"})}}return r}));function Y_(e){return"recorder"===e.roleName}oy([X_,e=>e.rtcConnection.isAcceptingStreams],(({dispatch:e},t,r)=>{0<t.length&&!r&&e(U_(t))}));const Z_=It({name:"room",initialState:{isLocked:!1},reducers:{},extraReducers:e=>{e.addCase(vy.roomJoined,((e,t)=>{const{error:r,isLocked:n}=t.payload;return r?e:Object.assign(Object.assign({},e),{isLocked:Boolean(n)})})),e.addCase(vy.roomLocked,((e,t)=>{const{isLocked:r}=t.payload;return Object.assign(Object.assign({},e),{isLocked:Boolean(r)})}))}}),eS=ey((e=>Cy(e)),(e=>(t,r)=>{const n=r(),{socket:i}=qy(n);null==i||i.emit("set_lock",{locked:e.locked})})),tS=ey((e=>ky(e)),(e=>(t,r)=>{const n=r(),{socket:i}=qy(n);null==i||i.emit("kick_client",{clientId:e.clientId,reasonId:"kick"})})),rS=ey((e=>Py(e)),(e=>(t,r)=>{const n=r(),i=S_(n).map((e=>e.id));if(i.length){const{socket:e}=qy(n);null==e||e.emit("kick_client",{clientIds:i,reasonId:"end-meeting"})}e.stayBehind||t(cy())})),nS=Ge(O_,Zw,C_,((e,t,r)=>{const n=[];e&&n.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&&n.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 n})),iS=Ge(O_,Zw,C_,((e,t,r)=>{const n=[];if(e){const r=!!e.getAudioTracks().length;n.push({clientId:t.id,displayName:"Your screenshare",id:"local-screenshare",isAudioEnabled:r,isLocalClient:!0,isPresentation:!0,isVideoEnabled:!0,stream:e})}for(const e of r){if("streamer"===e.roleName||Y_(e))continue;const{presentationStream:t}=e,r=Iy(e,["presentationStream"]),i=e.displayName||"Guest",s=t&&t.active,o="pres-"+e.id,a=e.stream&&e.stream.active,c=e.isVideoEnabled;n.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,displayName:i,hasActivePresentation:!!s}),e.isVideoEnabled?{isVideoEnabled:c}:{})),s&&n.push(Object.assign(Object.assign(Object.assign({},r),{clientId:e.id,stream:e.presentationStream,displayName:`Screenshare (${i})`,id:o,isPresentation:!0,isVideoEnabled:!0}),a&&{isRecording:null}))}return n})),sS=Ge(n_,iS,((e,t)=>[...e?[e]:[],...t])),oS={running:!1},aS=It({name:"connectionMonitor",initialState:oS,reducers:{connectionMonitorStarted:(e,t)=>Object.assign(Object.assign({},e),{running:!0,stopCallbackFunction:t.payload.stopIssueSubscription}),connectionMonitorStopped:()=>Object.assign({},oS)}}),{connectionMonitorStarted:cS,connectionMonitorStopped:dS}=aS.actions,lS=()=>(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},bf.getClients=r;const n=Yg({onUpdatedIssues:e=>{var r;const n=t(),i=K_(n);if(!i)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)})),i.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(cS({stopIssueSubscription:n.stop}))},uS=()=>(e,t)=>{const r=t(),n=hS(r);n&&n(),e(dS())},pS=e=>e.connectionMonitor.running,hS=e=>e.connectionMonitor.stopCallbackFunction,fS=Ge(c_,pS,((e,t)=>!t&&"connected"===e)),mS=Ge(c_,pS,((e,t)=>!(!t||!["kicked","left"].includes(e))));oy([fS],(({dispatch:e},t)=>{t&&e(lS())})),oy([mS],(({dispatch:e},t)=>{t&&e(uS())}));function gS(e){return Object.assign(Object.assign({},e),{timestamp:Date.now()})}const vS=It({name:"notifications",initialState:{emitter:new _p,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:[]})}});vS.actions;const bS=e=>(t,r)=>{t(vS.actions.addNotification(e));const n=r(),i=yS(n);i.emit(e.type,e),i.emit("*",e)},yS=e=>e.notifications.emitter;sy({actionCreator:vy.chatMessage,effect:({payload:e},{dispatch:t,getState:r})=>{const n=r(),i=C_(n).find((({id:t})=>t===e.senderId));i?t(bS(gS({type:"chatMessageReceived",message:`${i.displayName} says: ${e.text}`,props:{client:i,chatMessage:{senderId:e.senderId,timestamp:e.timestamp,text:e.text}}}))):console.warn("Could not find remote client that sent chat message")}}),sy({actionCreator:vy.audioEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=C_(s).find((({id:e})=>e===i));o?t(bS(gS({type:n?"requestAudioEnable":"requestAudioDisable",message:n?`${o.displayName} has requested for you to speak`:`${o.displayName} has muted your microphone`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local audio change")}}),sy({actionCreator:vy.videoEnableRequested,effect:({payload:e},{dispatch:t,getState:r})=>{const{enable:n,requestedByClientId:i}=e,s=r(),o=C_(s).find((({id:e})=>e===i));o?t(bS(gS({type:n?"requestVideoEnable":"requestVideoDisable",message:n?`${o.displayName} has requested for you to start video`:`${o.displayName} has stopped your video`,props:{client:o,enable:n}}))):console.warn("Could not find remote client that requested a local video change")}}),sy({actionCreator:vy.clientMetadataReceived,effect:(e,{dispatch:t,getOriginalState:r,getState:n})=>{var i;const{error:s,payload:o}=e.payload;if(s||!o)return;const{clientId:a,stickyReaction:c}=o,d=n();if(!Ey(d))return;const l=C_(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=C_(u).find((({id:e})=>e===a));(c||(null==p?void 0:p.stickyReaction))&&(null==c?void 0:c.timestamp)!==(null===(i=null==p?void 0:p.stickyReaction)||void 0===i?void 0:i.timestamp)&&t(bS(gS({type:c?"remoteHandRaised":"remoteHandLowered",message:`${l.displayName} ${c?"raised":"lowered"} their hand`,props:{client:l,stickyReaction:c}})))}}),oy([Wy],(({dispatch:e,getState:t},r)=>{const n=t(),i=c_(n);["left","kicked"].includes(i)||("disconnected"===r?e(bS(gS({type:"signalTrouble",message:"Network connection lost. Trying to reconnect you...",props:{}}))):"connected"===r&&e(bS(gS({type:"signalOk",message:"Network connection available",props:{}}))))})),sy({actionCreator:vy.clientUnableToJoin,effect:(e,{dispatch:t})=>{var r;"room_full"===(null===(r=e.payload)||void 0===r?void 0:r.error)&&t(bS(gS({type:"clientUnableToJoinFullRoom",message:"Someone tried to join but the room is full and at capacity.",props:{}})))}});const wS={audioEnabled:{actions:[Jw.fulfilled],rtcEventName:"audioEnabled",getValue:e=>xw(e),getOutput:e=>({enabled:e})},videoEnabled:{actions:[Qw.fulfilled],rtcEventName:"videoEnabled",getValue:e=>Dw(e),getOutput:e=>({enabled:e})},localStream:{actions:[Sw.fulfilled],rtcEventName:"localStream",getValue:e=>{var t;return null===(t=Bw(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:[P_.fulfilled],rtcEventName:"localScreenshareStream",getValue:e=>{var t;return null===(t=O_(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:[k_],rtcEventName:"localScreenshareStream",getValue:()=>()=>null,getOutput:()=>({})},displayName:{actions:[Ww],rtcEventName:"displayName",getValue:e=>hy(e),getOutput:e=>({displayName:e})},clientId:{actions:null,rtcEventName:"clientId",getValue:e=>e_(e),getOutput:e=>({clientId:e})},deviceId:{actions:null,rtcEventName:"deviceId",getValue:e=>(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})(e),getOutput:e=>({deviceId:e})},externalId:{actions:null,rtcEventName:"externalId",getValue:e=>my(e),getOutput:e=>({externalId:e})},organizationId:{actions:null,rtcEventName:"organizationId",getValue:e=>sw(e),getOutput:e=>({organizationId:e})},signalConnectionStatus:{actions:null,rtcEventName:"signalConnectionStatus",getValue:e=>Wy(e),getOutput:e=>({status:e})},roomSessionId:{actions:[vy.newClient,vy.roomJoined,vy.roomSessionEnded,vy.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=>J_(e),getOutput:e=>({status:e})},userRole:{actions:null,rtcEventName:"userRole",getValue:e=>Sy(e),getOutput:e=>({userRole:e})}},_S=Object.values(wS).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)),SS=e=>"object"==typeof e?JSON.stringify(e):e,CS=It({initialState:{reportedValues:{}},name:"rtcAnalytics",reducers:{updateReportedValues:(e,t)=>Object.assign(Object.assign({},e),{reportedValues:Object.assign(Object.assign({},e.reportedValues),{[t.payload.rtcEventName]:t.payload.value})})}}),RS=()=>(e,t)=>{const r=t(),n=H_(r).rtcManager;n&&(n.sendStatsCustomEvent("insightsStats",{_time:Date.now(),ls:0,lr:0,bs:0,br:0,cpu:0}),Object.values(wS).forEach((({rtcEventName:t,getValue:i,getOutput:s})=>{var o;const a=i(r),c=Object.assign(Object.assign({},s(a)),{_time:Date.now()}),d=SS(a);(null===(o=r.rtcAnalytics.reportedValues)||void 0===o?void 0:o[t])!==d&&(n.sendStatsCustomEvent(t,c),e(TS({rtcEventName:t,value:a})))})))},{updateReportedValues:TS}=CS.actions;function kS({isPresentation:e,stream:t}){var r,n;return e?null!==(n=null!==(r=null==t?void 0:t.outboundId)&&void 0!==r?r:null==t?void 0:t.inboundId)&&void 0!==n?n:null==t?void 0:t.id:"0"}function PS(e,t){return e.find((e=>e.clientId===t.clientId&&e.streamId===t.streamId))?e:e.concat(t)}sy({matcher:yt(..._S),effect:({type:e},{getState:t,dispatch:r})=>{var n;const i=t(),s=H_(i).rtcManager;if(!s)return;const o=Object.values(wS).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(i),u=SS(l),p=Object.assign(Object.assign({},c(l)),{_time:Date.now()});(null===(n=i.rtcAnalytics.reportedValues)||void 0===n?void 0:n[d])!==u&&(s.sendStatsCustomEvent(d,p),r(TS({rtcEventName:d,value:l})))}}),oy([W_],(({dispatch:e},t)=>{t&&e(RS())}));const ES=It({name:"spotlights",initialState:{sorted:[]},reducers:{addSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:PS(e.sorted,{clientId:r,streamId:n})})},removeSpotlight(e,t){const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===n)))})}},extraReducers:e=>{e.addCase(vy.roomJoined,((e,t)=>{if(!t.payload.room)return e;const{spotlights:r}=t.payload.room;return Object.assign(Object.assign({},e),{sorted:r})})),e.addCase(vy.spotlightAdded,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:PS(e.sorted,{clientId:r,streamId:n})})})),e.addCase(vy.spotlightRemoved,((e,t)=>{const{clientId:r,streamId:n}=t.payload;return Object.assign(Object.assign({},e),{sorted:e.sorted.filter((e=>!(e.clientId===r&&e.streamId===n)))})})),e.addMatcher(yt(vy.clientKicked,vy.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:IS}=ES.actions,DS=ey((e=>Oy(e)),(({id:e})=>(t,r)=>{const n=r(),i=sS(n).find((t=>t.clientId===e));if(!i)return;const{socket:s}=qy(n),o=kS(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("add_spotlight",a)})),xS=ey((e=>Oy(e)),(({id:e})=>(t,r)=>{const n=r(),i=sS(n).find((t=>t.clientId===e));if(!i)return;const{socket:s}=qy(n),o=kS(i),a={clientId:i.id,streamId:null!=o?o:"0"};null==s||s.emit("remove_spotlight",a)})),MS=e=>e.spotlights.sorted;Ge(Zw,MS,((e,t)=>function({spotlights:e,isPresentation:t,clientId:r,stream:n}){return!!e.find((e=>{const i=kS({isPresentation:t,stream:n});return e.clientId===r&&e.streamId===i}))}({clientId:e.id,stream:e.stream,spotlights:t})));const jS=Ge(sS,MS,((e,t)=>function(e,t){return e.reduce(((e,r)=>{const n=t.find((e=>r.clientId===e.clientId&&r.streamId===kS(e)));return n&&!e.includes(n)&&e.push(n),e}),[])}(t,e)));sy({actionCreator:P_.fulfilled,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=Zw(i);s&&r(OS({clientId:s.id,streamId:n.id}))}}),sy({actionCreator:k_,effect:({payload:e},{getState:t,dispatch:r})=>{const{stream:n}=e,i=t(),s=Zw(i);s&&r(IS({clientId:s.id,streamId:n.id}))}});const LS=It({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})}});LS.actions;const AS=It({name:"waitingParticipants",initialState:{waitingParticipants:[]},reducers:{},extraReducers:e=>{e.addCase(vy.roomJoined,((e,{payload:t})=>{var r;return(null===(r=t.room)||void 0===r?void 0:r.knockers.length)?Object.assign(Object.assign({},e),{waitingParticipants:t.room.knockers.map((e=>({id:e.clientId,displayName:e.displayName})))}):e})),e.addCase(vy.roomKnocked,((e,t)=>{const{clientId:r,displayName:n}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:r,displayName:n}]})})),e.addCase(vy.knockerLeft,((e,t)=>{const{clientId:r}=t.payload;return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter((e=>e.id!==r))})}))}}),NS=ty((e=>(t,r)=>{const{participantId:n}=e,i=r(),s=Ky(i);null==s||s.emit("handle_knock",{action:"accept",clientId:n,response:{}})})),BS=ty((e=>(t,r)=>{const{participantId:n}=e,i=r(),s=Ky(i);null==s||s.emit("handle_knock",{action:"reject",clientId:n,response:{}})}));const FS=null===!1&&!1,zS=B({app:ay.reducer,authorization:yy.reducer,chat:Qy.reducer,cloudRecording:Yy.reducer,connectionMonitor:aS.reducer,deviceCredentials:xy.reducer,localMedia:aw.reducer,localParticipant:Hw.reducer,localScreenshare:T_.reducer,notifications:vS.reducer,organization:nw.reducer,remoteParticipants:g_.reducer,room:Z_.reducer,roomConnection:i_.reducer,rtcAnalytics:CS.reducer,rtcConnection:x_.reducer,signalConnection:Ly.reducer,spotlights:ES.reducer,streaming:LS.reducer,waitingParticipants:AS.reducer}),VS=(e,t)=>{var r;if(dy.match(t)){const n={app:Object.assign(Object.assign({},ay.getInitialState()),{initialConfig:null===(r=null==e?void 0:e.app)||void 0===r?void 0:r.initialConfig}),localMedia:Object.assign(Object.assign({},aw.getInitialState()),null==e?void 0:e.localMedia)};return zS(n,t)}return zS(e,t)};class US{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 $S(e,t){return xg.ok(e,`${t} is required`),e}function GS(e,t){return xg.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function qS(e,t){return xg.ok("number"==typeof e,`${t}<number> is required`),e}function HS(e,t){return xg.ok("string"==typeof e,`${t}<string> is required`),e}function WS(e,t,r){const n=r||t.name[0].toLowerCase()+t.name.substring(1);return xg.ok(e instanceof t,`${n}<${t.name}> is required`),e}function KS(e,t){return xg.ok(Array.isArray(e),`${t}<array> is required`),e}function JS(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 QS(e,t,r){HS(t,"name"),function(e,t,r,n){HS(r,"name");const i=n||`${r} must be null or of type ${t}`;xg.ok(null===e||typeof e===t,i)}(e,"string",t,r)}function XS({baseUrl:e,url:t}){return e?e+t:t}class YS{constructor({baseUrl:e}){HS(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const r=Object.assign({},t,{url:e,baseURL:this._baseUrl});return Yb.request(r)}request(e,t){return HS(e,"url"),xg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),xg.ok(t,"options are required"),this._requestAxios(e,t).then((e=>{const{data:t,headers:r,status:n,statusText:i,config:s}=e,o=s&&s.url?XS({baseUrl:s.baseURL,url:s.url}):null;return new US({data:t,headers:r,status:n,statusText:i,url:o})})).catch((e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:r,headers:n,status:i,statusText:s,config:o}=t,a=o&&o.url?XS({baseUrl:o.baseURL,url:o.url}):null;return Promise.reject(new US({data:r,headers:n,status:i,statusText:s,url:a}))}))}}class ZS{constructor({httpClient:e}){xg.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){xg.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach((r=>{const n=e[r];t.append(r,n)})),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:ZS.dataToFormData}))}}let eC;eC="object"==typeof window?window.btoa||hv:"object"==typeof global&&global.btoa||hv;const tC=()=>Promise.resolve(null);class rC{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then((r=>{const n=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${eC(t)}`}}return{}}(r),{"X-Appearin-Device-Platform":"web"}),i=Object.assign({},t,{headers:n});return this._httpClient.request(e,i)}))}}class nC{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=tC}={}){this.authenticatedHttpClient=new rC({httpClient:new YS({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new ZS({httpClient:this.authenticatedHttpClient})}request(e,t){return HS(e,"url"),xg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),xg.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return HS(e,"url"),xg.ok("/"===e[0],'url<String> only accepts relative URLs beginning with "/".'),xg.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function iC(e,t){return HS(JS(e,"data")[t],t)}const sC=(oC=iC,(e,t)=>{const r=JS(e,"data")[t];return null==r?null:oC(e,t)});var oC;function aC(e,t,r){return function(e,t){return KS(JS(e,"data")[t],t)}(e,t).map((e=>r(e)))}class cC{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 cC(iC(function(e,t){const r=JS(e,"data")[t];return void 0===r?null:r}(e,"credentials"),"uuid"),iC(e,"hmac"),sC(e,"userId")||void 0)}}class dC{constructor({apiClient:e}){this._apiClient=e}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then((({data:e})=>cC.fromJson(e))).catch((e=>{if(e.response&&404===e.response.status)return null;throw e}))}}class lC{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 uC{constructor(e,t){$S(t,"localStorage"),this._key=HS(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 pC;try{pC=self.localStorage}catch(uO){pC={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var hC=pC;const fC="credentials_saved";class mC extends _p{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=e,this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:r="localStorage"}){const n=new dC({apiClient:new nC({baseUrl:e})});let i=null;if("localStorage"===r)i=new uC(t,hC);else{if("chromeStorage"!==r)throw new Error(`Unknown store type: ${r}`);i=new lC(t,window.chrome.storage.local)}return new mC({deviceService:n,credentialsStore:i})}_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?cC.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(fC,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 gC{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:r,totalMinutesUsed:n}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=r,this.totalMinutesUsed=n}static fromJson(e){return new gC({isExhausted:GS(e.isExhausted,"isExhausted"),renewsAt:new Date(HS(e.renewsAt,"renewsAt")),totalMinutesLimit:qS(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:qS(e.totalMinutesUsed,"totalMinutesUsed")})}}class vC{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:r,isOnTrial:n,onTrialUntil:i,trialStatus:s}){this.basePlanId=e,this.isDeactivated=r,this.isOnTrial=n,this.onTrialUntil=i||null,this.trialStatus=s||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new vC({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:GS(e.isDeactivated,"isDeactivated"),isOnTrial:GS(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?gC.fromJson(e.embeddedFreeTierStatus):null})}}function bC(e){return null!=e}function yC(e={}){return{maxNumberOfInvitationsAndUsers:bC(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:bC(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:bC(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:bC(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:bC(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class wC{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,WS(e,Object,"properties"),HS(e.organizationId,"organizationId"),HS(e.organizationName,"organizationName"),HS(e.subdomain,"subdomain"),WS(e.permissions,Object,"permissions"),WS(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 vC(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=WS(e,Object,"data"),r=(null==t?void 0:t.preferences)||{},n=(null==t?void 0:t.onboardingSurvey)||null,i=WS(t.permissions,Object,"permissions");return new wC({organizationId:HS(t.organizationId,"organizationId"),organizationName:HS(t.organizationName,"organizationName"),subdomain:HS(t.subdomain,"subdomain"),permissions:i,limits:yC(WS(t.limits,Object,"limits")),account:t.account?vC.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:n,type:"string"==typeof t.type?t.type:null})}}wC.GLOBAL_ORGANIZATION_ID="1";class _C{constructor({apiClient:e}){this._apiClient=e}createOrganization({organizationName:e,subdomain:t,owner:r}){const{displayName:n,consents:i}=r||{},s="email"in r?{value:r.email,verificationCode:HS(r.verificationCode,"owner.verificationCode")}:null,o="idToken"in r?r.idToken:null;if(HS(t,"subdomain"),HS(e,"organizationName"),HS(n,"owner.displayName"),xg.ok(s||o,"owner.email or owner.idToken is required"),i){KS(i,"consents");for(const{consentRevisionId:e,action:t}of i)HS(e,"consentRevisionId"),QS(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}),i&&{consents:i}),{displayName:n})}}).then((({data:e})=>iC(e,"organizationId")))}getOrganizationBySubdomain(e){return HS(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then((({data:e})=>wC.fromJson(e))).catch((e=>{if(e instanceof US){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationByOrganizationId(e){return HS(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then((({data:e})=>wC.fromJson(e))).catch((e=>{if(e instanceof US){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,n="phoneNumber"in e?e.phoneNumber:null;xg.ok((r||n)&&!(r&&n),"either email or phoneNumber is required"),HS(t,"code");const i=r?{type:"email",value:r}:{type:"phoneNumber",value:n};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:i,code:t}}).then((({data:e})=>aC(e,"organizations",(e=>wC.fromJson(e)))))}getOrganizationsByIdToken({idToken:e}){return HS(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then((({data:e})=>aC(e,"organizations",(e=>wC.fromJson(Object.assign({permissions:{},limits:{}},JS(e,"organization")))))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then((({data:e})=>aC(e,"organizations",(e=>wC.fromJson(Object.assign({permissions:{},limits:{}},JS(e,"organization")))))))}getSubdomainAvailability(e){return HS(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then((({data:e})=>(WS(e,Object,"data"),{status:iC(e,"status")})))}updatePreferences({organizationId:e,preferences:t}){return $S(e,"organizationId"),$S(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}deleteOrganization({organizationId:e}){return $S(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then((()=>{}))}}class SC{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 CC="https://api.whereby.dev";const RC=s.createContext(null);P(RC);const TC=function(e=v){const t=e===v?O:P(e),r=()=>t().dispatch;return Object.assign(r,{withTypes:()=>r}),r}(RC),kC=function(e=v){const t=e===v?y:b(e),r=(e,r={})=>{const{equalityFn:n=_,devModeChecks:i={}}="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 n)throw new Error("You must pass a function as an equality function to useSelector");const{store:s,subscription:o,getServerState:a,stabilityCheck:c,identityFunctionCheck:d}=t(),l=h.useRef(!0),u=h.useCallback({[e.name](t){const r=e(t);{const{identityFunctionCheck:s,stabilityCheck:o}={stabilityCheck:c,identityFunctionCheck:d,...i};if("always"===o||"once"===o&&l.current){const i=e(t);if(!n(r,i)){let n;try{throw new Error}catch(e){({stack:n}=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:r,selected2:i,stack:n})}}if(("always"===s||"once"===s&&l.current)&&r===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})}l.current&&(l.current=!1)}return r}}[e.name],[e,c,i.stabilityCheck]),p=w(o.addNestedSub,s.getState,a||s.getState,u,n);return h.useDebugValue(p),p};return Object.assign(r,{withTypes:()=>r}),r}(RC);var PC=function(){return PC=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},PC.apply(this,arguments)};function EC(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}"function"==typeof SuppressedError&&SuppressedError;const OC=TC.withTypes(),IC=kC.withTypes(),DC=s.forwardRef(((e,t)=>{var{muted:r,mirror:n=!1,stream:i,onVideoResize:o}=e,a=EC(e,["muted","mirror","stream","onVideoResize"]);const c=OC(),d=IC(Iw),l=s.useRef(null),u=s.useRef(null);return s.useImperativeHandle(t,(()=>Object.assign(l.current,{captureAspectRatio:()=>{if(!l.current)return null;const e=l.current.videoHeight,t=l.current.videoWidth;return t&&e&&t+e>20?t/e:null}}))),s.useEffect((()=>{if(!l.current)return;const e=new ResizeObserver(ow((()=>{if(l.current&&(null==i?void 0:i.id)){const e=l.current.clientWidth,t=l.current.clientHeight;c($_({streamId:i.id,width:e,height:t})),o&&o({width:e,height:t,stream:i})}}),{delay:1e3,edges:!0}));return e.observe(l.current),()=>{e.disconnect()}}),[i]),s.useEffect((()=>{l.current&&(l.current.srcObject!==i&&(l.current.srcObject=i),l.current.muted!==r&&(l.current.muted=Boolean(r)))}),[r,i,l]),s.useEffect((()=>{u.current&&!r&&i&&d&&(u.current.srcObject!==i&&(u.current.srcObject=i),u.current.setSinkId&&u.current.setSinkId(d))}),[i,u,d,r]),s.createElement(s.Fragment,null,s.createElement("video",Object.assign({ref:l,autoPlay:!0,playsInline:!0},a,{style:Object.assign({transform:n?"scaleX(-1)":"none",width:"100%",height:"100%"},a.style)})),s.createElement("audio",{ref:u,autoPlay:!0,playsInline:!0}))}));DC.displayName="VideoView";const xC=Ge((e=>e.chat.chatMessages),(e=>e.cloudRecording),Zw,Bw,C_,nS,c_,(e=>e.streaming),(e=>e.waitingParticipants.waitingParticipants),yS,jS,((e,t,r,n,i,s,o,a,c,d,l)=>({chatMessages:e,cloudRecording:t.isRecording?{status:"recording"}:void 0,connectionStatus:o,events:d,liveStream:a.isStreaming?{status:"streaming",startedAt:a.startedAt}:void 0,localScreenshareStatus:r.isScreenSharing?"active":void 0,localParticipant:Object.assign(Object.assign({},r),{stream:n}),remoteParticipants:i,screenshares:s,waitingParticipants:c,spotlightedParticipants:l}))),MC={localMediaOptions:{audio:!0,video:!0}};const jC=Ge((e=>e.localMedia.cameraDeviceError),Uw,Ew,Ow,Iw,(e=>e.localMedia.isSettingCameraDevice),(e=>e.localMedia.isSettingMicrophoneDevice),Vw,Bw,(e=>e.localMedia.microphoneDeviceError),$w,Gw,(e=>e.localMedia.startError),((e,t,r,n,i,s,o,a,c,d,l,u,p)=>({cameraDeviceError:e,cameraDevices:t,currentCameraDeviceId:r,currentMicrophoneDeviceId:n,currentSpeakerDeviceId:i,isSettingCameraDevice:s,isSettingMicrophoneDevice:o,isStarting:a,localStream:c,microphoneDeviceError:d,microphoneDevices:l,speakerDevices:u,startError:p})));var LC={MIN_WINDOW_HEIGHT:320,MIN_WINDOW_WIDTH:320,DESKTOP_BREAKPOINT:1025,TABLET_BREAKPOINT:750,PHONE_BREAKPOINT:500,TOP_TOOLBAR_HEIGHT:56,BOTTOM_TOOLBAR_HEIGHT:82,SIDEBAR_WIDTH:375,VIDEO_CONTROLS_MIN_WIDTH:420,ROOM_FOOTER_MIN_WIDTH:600,FLOATING_VIDEO_CONTROLS_BOTTOM_MARGIN:20,WATERMARK_BAR_HEIGHT:32,BREAKOUT_STAGE_BACKDROP_HEADER_HEIGHT:28,BREAKOUT_STAGE_BACKDROP_FOOTER_HEIGHT:56,SUBGRID_EMPTY_STAGE_MAX_WIDTH:800,GROUPS_CELL_MARGIN:8,GROUPS_CELL_PADDING:12,GROUPS_CELL_NAV_HEIGHT:56,GROUPS_CELL_AVATAR_WRAPPER_BOTTOM_MARGIN:8,GROUPS_CELL_AVATAR_GRID_GAP:8,GROUPS_CELL_MIN_WIDTH:360,GROUPS_CELL_MAX_WIDTH:600,GROUPS_ROW_HEIGHT:72,GROUPS_ROW_GAP:1,FOLDABLE_SCREEN_STAGE_PADDING:8};function AC({top:e=0,left:t=0}={}){return{top:e,left:t}}function NC({width:e=0,height:t=0}={}){return{width:Math.max(e,0),height:Math.max(t,0)}}function BC({top:e=0,left:t=0,width:r=0,height:n=0}={}){return{bounds:NC({width:r,height:n}),origin:AC({top:e,left:t})}}function FC({top:e=0,left:t=0,bottom:r=0,right:n=0}={}){return{top:e,left:t,bottom:r,right:n}}function zC(e){return!!e&&!(e.width<=0||e.height<=0)}function VC(e,t){const{width:r,height:n}=t,i=n,s=i*e,o=Math.min(r/s,n/i);return{width:s*o,height:i*o}}const UC=({vertical:e,width:t,height:r,count:n,aspectRatio:i})=>{const s=[1,2,3].map((s=>(({width:e,height:t,rows:r,cols:n,aspectRatio:i})=>{const s=VC(i,{width:e/n,height:t/r});return Math.round(s.width*s.height)})({width:t,height:r,rows:e?Math.ceil(n/s):s,cols:e?s:Math.ceil(n/s),aspectRatio:i}))),o=Math.max(...s);return{splits:s.indexOf(o)+1,weight:o}},$C=({width:e,height:t,count:r,aspectRatio:n})=>{const i=UC({vertical:!0,width:e,height:t,count:r,aspectRatio:n}),s=UC({vertical:!1,width:e,height:t,count:r,aspectRatio:n});return i.weight>s.weight?{splits:i.splits,vertical:!0}:{splits:s.splits,vertical:!1}};function GC(e){var{aspectRatio:t,children:r,className:n,height:i,style:o,width:a,withRoundedCorners:c=!1,withShadow:d=!0}=e,l=EC(e,["aspectRatio","children","className","height","style","width","withRoundedCorners","withShadow"]);let u=a,p=i,h=0,f=0;t&&(({width:u,height:p}=VC(t,{width:a,height:i})),h=(a-u)/2,f=(i-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:n,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 qC({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 HC({cell:e,child:t,clientId:r,style:n={},withRoundedCorners:i=!1,withShadow:o=!1}){const a=!zC(e.bounds);return s.createElement(GC,{width:e.bounds.width,height:e.bounds.height,aspectRatio:e.aspectRatio,style:a?{width:0,height:0}:n,withRoundedCorners:i,withShadow:o,key:r},t)}function WC({containerFrame:e,debug:t=!1,featureRoundedCornersOff:r=!1,floatingContent:n,gridContent:i=[],isConstrained:o=!1,layoutOverflowBackdropFrame:a=BC(),layoutVideoStage:c,presentationGridContent:d=[],subgridContent:l=[]}){const u=!r&&!o,p=[];return i.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){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 HC({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:n,style:p,withShadow:i})}));return c}({content:i,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),d.length&&p.push(...function({content:e,isConstrained:t,stageLayout:r,withRoundedCorners:n,withShadow:i}){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 HC({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:n,withShadow:i})}))}({content:d,isConstrained:o,stageLayout:c,withRoundedCorners:u,withShadow:!o})),n&&p.push(function({content:e,containerFrame:t,stageLayout:r,withRoundedCorners:n}){var i;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===(i=e.props.client)||void 0===i?void 0:i.id)||"floating";return HC({cell:o,child:s.cloneElement(e,{isSmallCell:o.isSmallCell,isZoomedByDefault:!1,canZoom:!1,key:l,isDraggable:!1}),clientId:l,style:d,withRoundedCorners:n,withShadow:!1})}({content:n,containerFrame:e,stageLayout:c,withRoundedCorners:!r})),l.length&&p.push(...function({content:e,stageLayout:t,withRoundedCorners:r,withShadow:n}){const i=t.subgrid.cells;return e.map(((e,o)=>{var a,c,d,l;const u=i[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 HC({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:n})}))}({content:l,stageLayout:c,withRoundedCorners:!r,withShadow:!0})),s.createElement("div",{key:"video-stage-layout",style:{width:"100%",height:"100%",position:"relative"}},zC(a.bounds)&&s.createElement("div",{style:qC(a)}),p,t&&s.createElement(s.Fragment,null))}const KC=16/9,JC=4/3,QC=({value:e,min:t,max:r})=>Math.min(Math.max(e,t),r);function XC({choices:e=[]}){const t=Math.min(...e),r=Math.max(...e);let n=null;if(t===r)n=t;else{const t=function(...e){return new Set(e).size!==e.length}(e)?(i=e).sort(((e,t)=>i.filter((t=>t===e)).length-i.filter((e=>e===t)).length)).pop():r;n=QC({value:t||r,min:JC,max:KC})}var i;return{minAr:t,maxAr:r,chosenAr:n}}function YC({width:e,height:t,cellCount:r,gridGap:n,cellAspectRatios:i=[JC],paddings:s=FC()}){if(!r)return{cellCount:r,cellHeight:0,cellWidth:0,cols:0,rows:0,extraHorizontalPadding:0,extraVerticalPadding:0,gridGap:n,paddings:s};const o=e-(s.left+s.right),a=t-(s.top+s.bottom),c=XC({choices:i});let d=c.chosenAr;const{rows:l,cols:u}=function({count:e,width:t,height:r,aspectRatio:n}){if(e<=1)return{rows:1,cols:1};const{splits:i,vertical:s}=$C({width:t,height:r,count:e,aspectRatio:n});return s?{rows:Math.ceil(e/i),cols:i}:{rows:i,cols:Math.ceil(e/i)}}({count:r,width:o,height:a,aspectRatio:d});1===l?d=QC({value:o/u/a,min:Math.min(c.chosenAr,c.maxAr),max:Math.max(c.chosenAr,c.maxAr)}):1===u&&(d=QC({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:n,gridGap:i,aspectRatio:s}){const o=(e-(n-1)*i)/n,a=(t-(r-1)*i)/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*n/2,extraVerticalPadding:l*r/2}}({width:o,height:a,rows:l,cols:u,gridGap:n,aspectRatio:d});return{cellCount:r,cellHeight:h,cellWidth:p,cols:u,rows:l,extraHorizontalPadding:f,extraVerticalPadding:m,gridGap:n,paddings:s}}const ZC="rows",eR="columns";function tR({layoutGrid:e,dim:t,secDim:r,index:n,count:i,gridGap:s}){const o=(t-s*(i-1))*(e.fractions?e.fractions[n]:1/i),a=e.lines[n];return[o,(r-s*(a-1))/a]}function rR({isHorizontal:e,layoutGrid:t,width:r,height:n,gridGap:i}){const s=[],o=0,a=0,c={x:0,y:0},d=t.lines.length,l=e?n:r,u=e?r:n;for(let r=0;r<d;r++){const n=tR({layoutGrid:t,dim:l,secDim:u,index:r,count:d,gridGap:i}),p={width:e?n[1]:n[0],height:e?n[0]:n[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+i:c.y+=p.height+i;e?(c.y+=p.height+i,c.x=o):(c.x+=p.width+i,c.y=a)}return s}function nR({layoutGrid:e,width:t,height:r,gridGap:n}){switch(e.type){case ZC:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return rR({isHorizontal:!0,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n});case eR:return function({layoutGrid:e,width:t,height:r,gridGap:n}){return rR({isHorizontal:!1,layoutGrid:e,width:t,height:r,gridGap:n})}({layoutGrid:e,width:t,height:r,gridGap:n})}}function iR({width:e,height:t,cellCount:r,gridGap:n=0,paddings:i=FC()}){const s=e-(i.left+i.right),o=t-(i.top+i.bottom);return{cellRects:nR({layoutGrid:Math.round(s/o*10)/10<=1?{1:{type:ZC,lines:[1]},2:{type:ZC,lines:[1,1]},3:{type:ZC,lines:[2,1]},4:{type:ZC,lines:[2,2]},5:{type:ZC,lines:[2,2,1]},6:{type:ZC,lines:[2,2,2]},7:{type:ZC,lines:[3,2,2]},8:{type:ZC,lines:[2,2,2,2]},9:{type:ZC,lines:[3,2,2,2]},10:{type:ZC,lines:[3,3,2,2]},11:{type:ZC,lines:[3,3,3,2]},12:{type:ZC,lines:[3,3,3,3]},13:{type:ZC,lines:[2,2,3,3,3]},14:{type:ZC,lines:[2,3,3,3,3]},15:{type:ZC,lines:[3,3,3,3,3]},16:{type:ZC,lines:[2,2,3,3,3,3]},17:{type:ZC,lines:[2,3,3,3,3,3]},18:{type:ZC,lines:[3,3,3,3,3,3]},19:{type:ZC,lines:[2,2,3,3,3,3,3]},20:{type:ZC,lines:[2,3,3,3,3,3,3]},21:{type:ZC,lines:[3,3,3,3,3,3,3]},22:{type:ZC,lines:[2,2,3,3,3,3,3,3]},23:{type:ZC,lines:[2,3,3,3,3,3,3,3]},24:{type:ZC,lines:[3,3,3,3,3,3,3,3]}}[r]||{type:ZC,lines:[3,3,3,3,3,3,3,3]}:function(e){return{1:{type:eR,lines:[1]},2:{type:eR,lines:[1,1]},3:{type:eR,lines:[2,1]},4:{type:eR,lines:[2,2]},5:{type:ZC,lines:[3,2],fractions:[.45,.55]},6:{type:eR,lines:[2,2,2]},7:{type:ZC,lines:[4,3],fractions:[.45,.55]},8:{type:eR,lines:[2,2,2,2]},9:{type:eR,lines:[3,2,2,2]},10:{type:eR,lines:[3,3,2,2]},11:{type:eR,lines:[3,3,3,2]},12:{type:eR,lines:[3,3,3,3]},13:{type:eR,lines:[4,3,3,3]},14:{type:eR,lines:[4,4,3,3]},15:{type:eR,lines:[3,3,3,3,3]},16:{type:eR,lines:[4,3,3,3,3]},17:{type:eR,lines:[4,4,3,3,3]},18:{type:eR,lines:[4,4,4,3,3]},19:{type:eR,lines:[4,4,4,4,3]},20:{type:eR,lines:[4,4,4,4,4]},21:{type:eR,lines:[5,4,4,4,4]},22:{type:eR,lines:[5,5,4,4,4]},23:{type:eR,lines:[5,5,5,4,4]},24:{type:eR,lines:[5,5,5,5,4]}}[e]||{type:eR,lines:[5,5,5,5,5]}}(r),width:s,height:o,gridGap:n})||[],cellCount:r,gridGap:n,extraHorizontalPadding:0,extraVerticalPadding:0,paddings:i}}function sR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:n,paddings:i=FC()}){let s=0,o=0,a=0,c=0,d=0,l=0;const u=e.width-i.left-i.right,p=e.height-i.top-i.bottom;return r&&(t?(c=Math.floor(u/n.width),a=Math.ceil(r/c),s=u,o=a*n.height,d=(u-c*n.width)/2):(a=Math.floor(p/n.height),c=Math.ceil(r/a),s=c*n.width,o=p,l=(p-a*n.height)/2)),{isPortrait:t,width:s+i.left+i.right,height:o+i.top+i.bottom,cellBounds:n,cellCount:r,rows:a,cols:c,extraHorizontalPadding:d,extraVerticalPadding:l,paddings:i}}const{BOTTOM_TOOLBAR_HEIGHT:oR,VIDEO_CONTROLS_MIN_WIDTH:aR,TABLET_BREAKPOINT:cR,SUBGRID_EMPTY_STAGE_MAX_WIDTH:dR}=LC,lR=200,uR=300,pR=200,hR=20,fR=12,mR=FC({top:4,bottom:28,left:8,right:8});function gR({hasOverflow:e,hasStage:t}){return e&&t?[80]:[80,60]}function vR({cellCount:e}){const t=e<=6;return NC({width:t?uR-50:uR,height:t?lR-50:lR})}function bR({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){const o=function({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}){let o;for(let a=0;a<n.length;a++){const c=n[a];if(o=sR({containerBounds:e,isPortrait:t,cellCount:r,cellBounds:NC({width:c+i.left+i.right,height:c+i.top+i.bottom}),paddings:s}),o.width<=e.width&&o.height<=e.height)return o}return o}({containerBounds:e,isPortrait:t,cellCount:r,cellSizeOptions:n,cellPaddings:i,paddings:s}),a=o.cellBounds.width-i.left-i.right===n[n.length-1],c=NC({width:Math.min(o.width,e.width),height:Math.min(o.height,e.height)}),d=NC({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:n,width:s,height:c}=function({index:e,layout:t}){const{isPortrait:r,rows:n,cols:i,cellCount:s,cellBounds:o,extraHorizontalPadding:a,extraVerticalPadding:c,paddings:d}=t,l=r?Math.floor(e/i):Math.floor(e%n),u=r?Math.floor(e%i):Math.floor(e/n),p=function({index:e,isPortrait:t,rows:r,cols:n,cellBounds:i,cellCount:s}){const o=r*n,a=o-s;if(!a)return 0;const c=o-a-1;return e<c-((t?n:r)-a)+1||e>c?0:a*(t?i.width:i.height)/2}({index:e,isPortrait:r,rows:n,cols:i,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:AC({top:r,left:n}),bounds:NC({width:s,height:c}),paddings:i,isSmallCell:a}}))}}function yR({cellPaddings:e,cellSizeOptions:t,containerBounds:r,containerOrigin:n,gridGap:i,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:BC(),subgrid:Object.assign(Object.assign({},BC()),{contentBounds:NC(),cells:[]}),hasOverflow:!1};if(!b)return{isPortrait:l,videosContainer:BC(Object.assign(Object.assign({},r),n)),subgrid:Object.assign(Object.assign({},BC()),{contentBounds:NC(),cells:[]}),hasOverflow:s};const y=h?hR:0;let w=null;if(v)if(h){const n=t[0];let i=d?oR:oR+e.top+(c||u?n/2:n)+e.bottom;r.height-i<lR&&(i=0),w=NC({width:r.width,height:i})}else w=NC(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=NC({width:Math.min(dR,r.width),height:r.height});let _=0;w.width>p&&(_=(w.width-p)/2);const S=bR({containerBounds:w,isPortrait:l,cellCount:f.length,cellSizeOptions:t,cellPaddings:e,paddings:FC({top:y,left:_,right:_})}),C=NC({width:S.contentBounds.width-w.width,height:S.contentBounds.height-w.height}),R=C.width>0||C.height>0;let T,k=null;k=!v||h||R?S.contentBounds:S.bounds;let P=k;v?(P=NC(h?{width:0,height:w.height+y+i}:l?{width:0,height:S.bounds.height+i}:{width:S.bounds.width+i,height:0}),T=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})):T=NC();const E=Object.assign({},n);let O;return O=AC(v?{top:l?Math.max(n.top+g-P.height+i,0):n.top,left:l?n.left:Math.max(n.left+m-k.width,0)}:{top:n.top+Math.max(0,(g-k.height)/2),left:n.left+Math.max(0,(m-k.width)/2)}),{isPortrait:l,videosContainer:BC(Object.assign(Object.assign({},T),E)),subgrid:Object.assign(Object.assign({},BC(Object.assign(Object.assign({},k),O))),{cells:S.videoCells.map(((e,t)=>{var r,n;return Object.assign({aspectRatio:(null===(r=f[t])||void 0===r?void 0:r.aspectRatio)||1,type:"video",clientId:null===(n=f[t])||void 0===n?void 0:n.clientId},e)})),contentBounds:S.contentBounds}),hasOverflow:R||h||s,overflowNeedBounds:h?NC():C}}function wR({containerBounds:e,containerOrigin:t,gridGap:r,supersizedContentAspectRatio:n,hasPresentationContent:i,hasPresentationGrid:s,hasVideoContent:o,minGridBounds:a}){const{width:c,height:d}=e;let l=c<=d,u=NC(),p=AC(),h=o?Object.assign({},e):NC(),f=o?Object.assign({},t):AC();if(i){const i=function({bounds:e,aspectRatio:t,minGridContainerBounds:r,hasPresentationGrid:n}){const{width:i,height:s}=e;if(!(r.width>0))return{isPortrait:i<=s,supersizedContentBounds:e};const o=Math.round(i/2),a=Math.round(s/2),c=Math.max(i-r.width,0),d=Math.max(s-r.height,0);let l=c<=d,u=0,p=0;if(t){const e=VC(t,{width:c,height:s}),r=VC(t,{width:i,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)}}else n&&(l=c/d>=5);return{isPortrait:l,supersizedContentBounds:{width:l?i:c-u,height:l?d-p:s}}}({bounds:e,aspectRatio:n||1,minGridContainerBounds:NC({width:o?a.width+r:0,height:o?a.height+r:0}),hasPresentationGrid:s});l=i.isPortrait,u=i.supersizedContentBounds,p=Object.assign({},t),o&&(h=NC({width:l?e.width:e.width-u.width-r,height:l?e.height-u.height-r:e.height}),f=AC({top:l?t.top+u.height+r:t.top,left:l?t.left:t.left+u.width+r}))}return{isPortrait:l,presentationGrid:Object.assign({},BC(Object.assign(Object.assign({},u),p))),videoGrid:BC(Object.assign(Object.assign({},h),f))}}function _R({containerBounds:e,paddings:t=FC(),videos:r,isConstrained:n,maxGridWidth:i,gridGap:s}){const{width:o,height:a}=e,c=i?Math.min(o,i):o,d=r.length;let l=null,u=null;if(n){const e=iR({width:o,height:a,cellCount:d,gridGap:s,paddings:t}),n=d>4;u=r.map(((t,r)=>{const i=function({index:e,layout:t}){const{cellRects:r}=t,n=r[e]||BC();return{top:n.origin.y,left:n.origin.x,width:n.bounds.width,height:n.bounds.height}}({index:r,layout:e});return{clientId:t.clientId,isDraggable:t.isDraggable,origin:AC({top:i.top,left:i.left}),bounds:NC({width:i.width,height:i.height}),aspectRatio:i.width/i.height,isSmallCell:n,type:"video"}})),l=e}else{const e=r.map((e=>e.aspectRatio||1)),i=vR({cellCount:d}),o=YC({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:n,rows:i,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:n,cellCount:i,gridGap:s}){const o=e*t,a=o-i;if(!a)return 0;const c=o-a-1;return n>=c-(t-a)+1&&n<=c?a*r/2+s:0}({rows:i,cols:s,cellWidth:r,index:e,cellCount:o,gridGap:a});return{top:c*n+c*a,left:d*r+d*a+l,width:r,height:n}}({index:t,layout:o}),s=o.cellWidth<i.width,a=n||s?o.cellWidth/o.cellHeight:e.aspectRatio||1;return{clientId:e.clientId,isDraggable:e.isDraggable,origin:AC({top:r.top,left:r.left}),bounds:NC({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 SR({a:e,b:t,gridGap:r,isPortrait:n}){const i=n?e.vertical:e.horizontal,s=n?t.vertical:t.horizontal;if(i===s)return{a:0,b:0};const o=i<s?e:t,a=n?o.vertical:o.horizontal,c=(r+(i+s)+a)/2-a;return{a:o===e?c:0,b:o===t?c:0}}function CR({gridGap:e,isConstrained:t,presentationVideos:r,videos:n,videosContainerLayout:i,gridLayoutPaddings:s=FC(),presentationGridLayoutPaddings:o=FC(),maxGridWidth:a}){return{gridLayout:_R({containerBounds:i.videoGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:s,videos:n}),presentationGridLayout:_R({containerBounds:i.presentationGrid.bounds,gridGap:e,isConstrained:t,maxGridWidth:a,paddings:o,videos:r})}}function RR({floatingVideo:e,frame:t,gridGap:r,isConstrained:n,isMaximizeMode:i=!1,isXLMeetingSize:s=!1,paddings:o=FC(),presentationVideos:a=[],rebalanceLayout:c=!1,roomBounds:d,roomLayoutHasOverlow:l=!1,subgridCellPaddings:u=mR,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=n&&f.length>fR,T=S/4,k=Math.ceil((f.length-fR)/3);S=R?S+T*k:S;const P=NC({width:_,height:S}),E=AC({top:o.top,left:o.left}),O=vR({cellCount:f.length}),I=d.width<cR||d.height<cR,D=i||g||!(v||w)||P.width<=P.height,x={cellPaddings:u,containerBounds:P,containerOrigin:E,gridGap:r,hasPresentationContent:v,hasVideoContent:w,isConstrained:n,isMaximizeMode:i,isSmallScreen:I,subgridVideos:p,maxGridWidth:C};let M=yR(Object.assign(Object.assign({},x),{cellSizeOptions:gR({hasOverflow:g,hasStage:v||w}),isPortrait:D,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})),j=!1;if(!g&&l&&!M.hasOverflow){yR(Object.assign(Object.assign({},x),{containerBounds:NC({width:P.width,height:P.height-oR}),cellSizeOptions:gR({hasOverflow:g,hasStage:v||w}),isPortrait:D,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})).hasOverflow&&(j=!0)}(j||M.hasOverflow&&!g)&&(g=!0,M=yR(Object.assign(Object.assign({},x),{cellSizeOptions:gR({hasOverflow:!0,hasStage:v||w}),isPortrait:!0,shouldOverflowSubgrid:g,hasConstrainedOverflow:R})));const L=wR({containerBounds:M.videosContainer.bounds,containerOrigin:M.videosContainer.origin,gridGap:r,supersizedContentAspectRatio:y||1,hasPresentationContent:v,hasPresentationGrid:b,hasVideoContent:w,minGridBounds:O});let{gridLayout:A,presentationGridLayout:N}=CR({gridGap:m||r,isConstrained:n,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:n,videosContainerLayout:i}){let s={presentationGrid:0,grid:0},o={presentationGrid:0,grid:0};if(t.isPortrait){const t=Math.min(r.extraVerticalPadding,n.extraVerticalPadding);s={presentationGrid:Math.min(i.isPortrait?n.extraVerticalPadding:t,e.height),grid:Math.min(i.isPortrait?r.extraVerticalPadding:t,e.height)}}else{const t=Math.min(r.extraHorizontalPadding,n.extraHorizontalPadding);o={presentationGrid:Math.min(i.isPortrait?t:n.extraHorizontalPadding,e.width),grid:Math.min(i.isPortrait?t:r.extraHorizontalPadding,e.width)}}return{vPaddings:s,hPaddings:o}}({need:M.overflowNeedBounds||NC(),stageLayout:M,gridLayout:A,presentationGridLayout:N,videosContainerLayout:L});(e.presentationGrid||e.grid||t.presentationGrid||t.grid)&&(!function({vPaddings:e,hPaddings:t,stageLayout:r,videosContainerLayout:n}){if(r.isPortrait&&(e.presentationGrid||e.grid)){const t=n.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,n.presentationGrid.bounds.height-=2*e.presentationGrid,n.videoGrid.bounds.height-=2*e.grid,n.isPortrait&&(n.videoGrid.origin.top-=e.presentationGrid)}if(!r.isPortrait&&(t.presentationGrid||t.grid)){const e=n.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,n.presentationGrid.bounds.width-=2*t.presentationGrid,n.videoGrid.bounds.width-=2*t.grid,n.isPortrait||(n.videoGrid.origin.left-=t.grid)}}({vPaddings:e,hPaddings:t,stageLayout:M,videosContainerLayout:L}),({gridLayout:A,presentationGridLayout:N}=CR({gridGap:m||r,isConstrained:n,presentationVideos:a,videos:f,videosContainerLayout:L,maxGridWidth:C})))}const B=function({roomBounds:e,containerFrame:t,floatingVideo:r,videoControlsHeight:n,margin:i=8}){if(!r)return null;const s=VC(r.aspectRatio||0,{width:pR,height:pR}),o=!(e.height-t.bounds.height-t.origin.top),a=t.bounds.width-2*(s.width+i)<aR;let c=0;o&&a?c=-1*n:o||a||(c=n);const d=AC({top:t.origin.top+(t.bounds.height-s.height-i)+c,left:t.origin.left+(t.bounds.width-s.width-i)});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:n,gridGap:i,shouldOverflowSubgrid:s}){const o=e.presentationGrid.bounds.width>0,a=e.videoGrid.bounds.width>0,c=n.subgrid.bounds.width>0,d={vertical:0,horizontal:0};if(o&&a){const n=SR({a:{horizontal:r.extraHorizontalPadding,vertical:r.extraVerticalPadding},b:{horizontal:t.extraHorizontalPadding,vertical:t.extraVerticalPadding},gridGap:i,isPortrait:e.isPortrait});e.isPortrait?(e.presentationGrid.origin.top+=n.a,e.videoGrid.origin.top-=n.b,d.vertical=n.b):(e.presentationGrid.origin.left+=n.a,e.videoGrid.origin.left-=n.b,d.horizontal=n.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&&!n.isPortrait?s.horizontal<c.horizontal?s:c:u&&!e.isPortrait&&n.isPortrait?s.vertical<c.vertical?s:c:a?c:s;const p=SR({a:l,b:{horizontal:0,vertical:0},gridGap:i,isPortrait:n.isPortrait});n.isPortrait?n.subgrid.origin.top-=p.b:n.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:NC({width:M.videosContainer.bounds.width,height:M.videosContainer.bounds.height}),origin:AC({top:M.videosContainer.origin.top,left:M.videosContainer.origin.left})}),bounds:NC({height:g?F:t.bounds.height,width:t.bounds.width}),gridGap:r,presentationGrid:Object.assign(Object.assign({},L.presentationGrid),{cells:N.videoCells,paddings:FC({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:FC({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)||AC(),bounds:(null==B?void 0:B.bounds)||NC(),aspectRatio:(null==e?void 0:e.aspectRatio)||1})}}function TR({aspectRatio:e,avatarSize:t,cellPaddings:r,client:n,isDraggable:i=!0,isPlaceholder:s=!1,isSubgrid:o=!1}){return{aspectRatio:e||16/9,avatarSize:t,cellPaddings:r,client:n,clientId:(null==n?void 0:n.id)||"",isDraggable:i,isPlaceholder:s,isSubgrid:o,type:"video"}}const kR=12,PR=12,ER=24;function OR({activeVideosSubgridTrigger:e=PR,stageParticipantLimit:t=kR,forceSubgrid:r=!0,enableSubgrid:n=!0,maximizedParticipant:i,floatingParticipant:o,isConstrained:a=!1}={}){const c=IC(sS),d=IC(jS),l=IC(R_),u=s.useMemo((()=>o),[o]),p=s.useMemo((()=>u?c.filter((e=>e.id!==u.id)):c),[c,u]),h=s.useMemo((()=>!!n&&(!!r||l>t)),[r,l,t,n]),f=s.useMemo((()=>function({clientViews:e,activeVideosSubgridTrigger:t,shouldShowSubgrid:r,spotlightedParticipants:n,maximizedParticipant:i,isPhoneResolution:s}){if(!r)return[];const o=n.length>0,a=(i?e.filter((e=>e.id!==i.id)):e).filter((e=>!e.isPresentation&&!n.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>ER){const e=[...l,...u],t=e.slice(0,ER);return t.length<=ER?[...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:i,isPhoneResolution:a})),[p,h,e,d,a]),m=s.useMemo((()=>p.filter((e=>!f.includes(e)))),[p,f]),g=s.useMemo((()=>i?[i]:d),[d,i]),v=s.useMemo((()=>m.filter((e=>!g.includes(e)))),[m,g]);return{floatingClientView:u,clientViewsInGrid:v,clientViewsInPresentationGrid:g,clientViewsInSubgrid:f}}var IR={exports:{}};const DR=55296,xR=56319,MR=56320,jR=127462,LR=127487,AR=127995,NR=127999,BR=65024,FR=65039,zR=8400,VR=8447,UR=8205,$R=[776,2359,2359,2367,2367,2984,3007,3021,3633,3635,3648,3657,4352,4449,4520];function GR(e){if("string"!=typeof e)throw new Error("string cannot be undefined or null");const t=[];let r=0,n=0;for(;r<e.length;)n+=qR(r+n,e),JR(e[r+n])&&n++,WR(e[r+n])&&n++,KR(e[r+n])&&n++,QR(e[r+n])?n++:(t.push(e.substring(r,r+n)),r+=n,n=0);return t}function qR(e,t){const r=t[e];if(!function(e){return e&&YR(e[0].charCodeAt(0),DR,xR)}(r)||e===t.length-1)return 1;const n=r+t[e+1];let i=t.substring(e+2,e+5);return HR(n)&&HR(i)||function(e){return YR(XR(e),AR,NR)}(i)?4:2}function HR(e){return YR(XR(e),jR,LR)}function WR(e){return"string"==typeof e&&YR(e.charCodeAt(0),BR,FR)}function KR(e){return"string"==typeof e&&YR(e.charCodeAt(0),zR,VR)}function JR(e){return"string"==typeof e&&-1!==$R.indexOf(e.charCodeAt(0))}function QR(e){return"string"==typeof e&&e.charCodeAt(0)===UR}function XR(e){return(e.charCodeAt(0)-DR<<10)+(e.charCodeAt(1)-MR)+65536}function YR(e,t,r){return e>=t&&e<=r}IR.exports=GR,IR.exports.substr=function(e,t,r){const n=GR(e);if(void 0===t)return e;if(t>=n.length)return"";const i=n.length-t;let s=t+(void 0===r?i:r);return s>t+i&&(s=void 0),n.slice(t,s).join("")};var ZR=c(IR.exports);const eT=({name:e})=>{const t=((e="")=>{if(e=e.trim())return e.split(/-| /).map((e=>ZR(e)[0])).slice(0,3);return[]})(e),r=[0,56,48,40][t.length]||32,n=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},n))};function tT(e){var{avatarUrl:t,className:r,size:n=40,name:i,variant:o="round"}=e,a=EC(e,["avatarUrl","className","size","name","variant"]);return s.createElement("div",Object.assign({style:{height:`${n}px`,width:`${n}px`,userSelect:"none",overflow:"hidden",borderRadius:"round"===o?"50%":"4px",backgroundColor:"#f8e3c8"},className:r,title:i},a),!t&&i?s.createElement(eT,{name:i}):s.createElement("img",{src:t||"",alt:"",style:{height:"100%",width:"100%",objectFit:"cover",maxWidth:"initial"}}))}function rT({avatarUrl:e,displayName:t,isSmallCell:r,withRoundedCorners:n}){return s.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",position:"absolute",top:0,left:0,height:"100%",width:"100%",borderRadius:n?"8px":"0"}},s.createElement("div",{style:{height:r?60:80,width:r?60:80,pointerEvents:"none",position:"relative"}},s.createElement(tT,{variant:"square",avatarUrl:e,name:t,size:r?60:80})))}function nT(){return nT=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},nT.apply(this,arguments)}function iT(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(null==e||e(n),!1===r||!n.defaultPrevented)return null==t?void 0:t(n)}}function sT(...e){return t=>e.forEach((e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t)))}function oT(...e){return t.useCallback(sT(...e),e)}function aT(e,r=[]){let n=[];const i=()=>{const r=n.map((e=>t.createContext(e)));return function(n){const i=(null==n?void 0:n[e])||r;return t.useMemo((()=>({[`__scope${e}`]:{...n,[e]:i}})),[n,i])}};return i.scopeName=e,[function(r,i){const s=t.createContext(i),o=n.length;function a(r){const{scope:n,children:i,...a}=r,c=(null==n?void 0:n[e][o])||s,d=t.useMemo((()=>a),Object.values(a));return t.createElement(c.Provider,{value:d},i)}return n=[...n,i],a.displayName=r+"Provider",[a,function(n,a){const c=(null==a?void 0:a[e][o])||s,d=t.useContext(c);if(d)return d;if(void 0!==i)return i;throw new Error(`\`${n}\` must be used within \`${r}\``)}]},cT(i,...r)]}function cT(...e){const r=e[0];if(1===e.length)return r;const n=()=>{const n=e.map((e=>({useScope:e(),scopeName:e.scopeName})));return function(e){const i=n.reduce(((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]})),{});return t.useMemo((()=>({[`__scope${r.scopeName}`]:i})),[i])}};return n.scopeName=r.scopeName,n}const dT=t.forwardRef(((e,r)=>{const{children:n,...i}=e,s=t.Children.toArray(n),o=s.find(pT);if(o){const e=o.props.children,n=s.map((r=>r===o?t.Children.count(e)>1?t.Children.only(null):t.isValidElement(e)?e.props.children:null:r));return t.createElement(lT,nT({},i,{ref:r}),t.isValidElement(e)?t.cloneElement(e,void 0,n):null)}return t.createElement(lT,nT({},i,{ref:r}),n)}));dT.displayName="Slot";const lT=t.forwardRef(((e,r)=>{const{children:n,...i}=e;return t.isValidElement(n)?t.cloneElement(n,{...hT(i,n.props),ref:r?sT(r,n.ref):n.ref}):t.Children.count(n)>1?t.Children.only(null):null}));lT.displayName="SlotClone";const uT=({children:e})=>t.createElement(t.Fragment,null,e);function pT(e){return t.isValidElement(e)&&e.type===uT}function hT(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{s(...e),i(...e)}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}const fT=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce(((e,r)=>{const n=t.forwardRef(((e,n)=>{const{asChild:i,...s}=e,o=i?dT:r;return t.useEffect((()=>{window[Symbol.for("radix-ui")]=!0}),[]),t.createElement(o,nT({},s,{ref:n}))}));return n.displayName=`Primitive.${r}`,{...e,[r]:n}}),{});function mT(e){const r=t.useRef(e);return t.useEffect((()=>{r.current=e})),t.useMemo((()=>(...e)=>{var t;return null===(t=r.current)||void 0===t?void 0:t.call(r,...e)}),[])}const gT="dismissableLayer.update",vT="dismissableLayer.pointerDownOutside",bT="dismissableLayer.focusOutside";let yT;const wT=t.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),_T=t.forwardRef(((e,r)=>{var n;const{disableOutsidePointerEvents:i=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:c,onDismiss:d,...l}=e,u=t.useContext(wT),[p,h]=t.useState(null),f=null!==(n=null==p?void 0:p.ownerDocument)&&void 0!==n?n:null===globalThis||void 0===globalThis?void 0:globalThis.document,[,m]=t.useState({}),g=oT(r,(e=>h(e))),v=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=v.indexOf(b),w=p?v.indexOf(p):-1,_=u.layersWithOutsidePointerEventsDisabled.size>0,S=w>=y,C=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const n=mT(e),i=t.useRef(!1),s=t.useRef((()=>{}));return t.useEffect((()=>{const e=e=>{if(e.target&&!i.current){const t={originalEvent:e};function o(){CT(vT,n,t,{discrete:!0})}"touch"===e.pointerType?(r.removeEventListener("click",s.current),s.current=o,r.addEventListener("click",s.current,{once:!0})):o()}else r.removeEventListener("click",s.current);i.current=!1},t=window.setTimeout((()=>{r.addEventListener("pointerdown",e)}),0);return()=>{window.clearTimeout(t),r.removeEventListener("pointerdown",e),r.removeEventListener("click",s.current)}}),[r,n]),{onPointerDownCapture:()=>i.current=!0}}((e=>{const t=e.target,r=[...u.branches].some((e=>e.contains(t)));S&&!r&&(null==o||o(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f),R=function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const n=mT(e),i=t.useRef(!1);return t.useEffect((()=>{const e=e=>{if(e.target&&!i.current){CT(bT,n,{originalEvent:e},{discrete:!1})}};return r.addEventListener("focusin",e),()=>r.removeEventListener("focusin",e)}),[r,n]),{onFocusCapture:()=>i.current=!0,onBlurCapture:()=>i.current=!1}}((e=>{const t=e.target;[...u.branches].some((e=>e.contains(t)))||(null==a||a(e),null==c||c(e),e.defaultPrevented||null==d||d())}),f);return function(e,r=(null===globalThis||void 0===globalThis?void 0:globalThis.document)){const n=mT(e);t.useEffect((()=>{const e=e=>{"Escape"===e.key&&n(e)};return r.addEventListener("keydown",e),()=>r.removeEventListener("keydown",e)}),[n,r])}((e=>{w===u.layers.size-1&&(null==s||s(e),!e.defaultPrevented&&d&&(e.preventDefault(),d()))}),f),t.useEffect((()=>{if(p)return i&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(yT=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(p)),u.layers.add(p),ST(),()=>{i&&1===u.layersWithOutsidePointerEventsDisabled.size&&(f.body.style.pointerEvents=yT)}}),[p,f,i,u]),t.useEffect((()=>()=>{p&&(u.layers.delete(p),u.layersWithOutsidePointerEventsDisabled.delete(p),ST())}),[p,u]),t.useEffect((()=>{const e=()=>m({});return document.addEventListener(gT,e),()=>document.removeEventListener(gT,e)}),[]),t.createElement(fT.div,nT({},l,{ref:g,style:{pointerEvents:_?S?"auto":"none":void 0,...e.style},onFocusCapture:iT(e.onFocusCapture,R.onFocusCapture),onBlurCapture:iT(e.onBlurCapture,R.onBlurCapture),onPointerDownCapture:iT(e.onPointerDownCapture,C.onPointerDownCapture)}))}));function ST(){const e=new CustomEvent(gT);document.dispatchEvent(e)}function CT(e,t,n,{discrete:i}){const s=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&s.addEventListener(e,t,{once:!0}),i?function(e,t){e&&r.flushSync((()=>e.dispatchEvent(t)))}(s,o):s.dispatchEvent(o)}let RT=0;function TT(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}const kT="focusScope.autoFocusOnMount",PT="focusScope.autoFocusOnUnmount",ET={bubbles:!1,cancelable:!0},OT=t.forwardRef(((e,r)=>{const{loop:n=!1,trapped:i=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...a}=e,[c,d]=t.useState(null),l=mT(s),u=mT(o),p=t.useRef(null),h=oT(r,(e=>d(e))),f=t.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;t.useEffect((()=>{if(i){function e(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?p.current=t:MT(p.current,{select:!0})}function t(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||MT(p.current,{select:!0}))}function r(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&MT(c)}document.addEventListener("focusin",e),document.addEventListener("focusout",t);const n=new MutationObserver(r);return c&&n.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),n.disconnect()}}}),[i,c,f.paused]),t.useEffect((()=>{if(c){jT.add(f);const t=document.activeElement;if(!c.contains(t)){const r=new CustomEvent(kT,ET);c.addEventListener(kT,l),c.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const n of e)if(MT(n,{select:t}),document.activeElement!==r)return}((e=IT(c),e.filter((e=>"A"!==e.tagName))),{select:!0}),document.activeElement===t&&MT(c))}return()=>{c.removeEventListener(kT,l),setTimeout((()=>{const e=new CustomEvent(PT,ET);c.addEventListener(PT,u),c.dispatchEvent(e),e.defaultPrevented||MT(null!=t?t:document.body,{select:!0}),c.removeEventListener(PT,u),jT.remove(f)}),0)}}var e}),[c,l,u,f]);const m=t.useCallback((e=>{if(!n&&!i)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,r=document.activeElement;if(t&&r){const t=e.currentTarget,[i,s]=function(e){const t=IT(e),r=DT(t,e),n=DT(t.reverse(),e);return[r,n]}(t);i&&s?e.shiftKey||r!==s?e.shiftKey&&r===i&&(e.preventDefault(),n&&MT(s,{select:!0})):(e.preventDefault(),n&&MT(i,{select:!0})):r===t&&e.preventDefault()}}),[n,i,f.paused]);return t.createElement(fT.div,nT({tabIndex:-1},a,{ref:h,onKeyDown:m}))}));function IT(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 DT(e,t){for(const r of e)if(!xT(r,{upTo:t}))return r}function xT(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 MT(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()}}const jT=function(){let e=[];return{add(t){const r=e[0];t!==r&&(null==r||r.pause()),e=LT(e,t),e.unshift(t)},remove(t){var r;e=LT(e,t),null===(r=e[0])||void 0===r||r.resume()}}}();function LT(e,t){const r=[...e],n=r.indexOf(t);return-1!==n&&r.splice(n,1),r}const AT=Boolean(null===globalThis||void 0===globalThis?void 0:globalThis.document)?t.useLayoutEffect:()=>{},NT=s["useId".toString()]||(()=>{});let BT=0;function FT(e){const[t,r]=s.useState(NT());return AT((()=>{e||r((e=>null!=e?e:String(BT++)))}),[e]),e||(t?`radix-${t}`:"")}const zT=["top","right","bottom","left"],VT=Math.min,UT=Math.max,$T=Math.round,GT=Math.floor,qT=e=>({x:e,y:e}),HT={left:"right",right:"left",bottom:"top",top:"bottom"},WT={start:"end",end:"start"};function KT(e,t,r){return UT(e,VT(t,r))}function JT(e,t){return"function"==typeof e?e(t):e}function QT(e){return e.split("-")[0]}function XT(e){return e.split("-")[1]}function YT(e){return"x"===e?"y":"x"}function ZT(e){return"y"===e?"height":"width"}function ek(e){return["top","bottom"].includes(QT(e))?"y":"x"}function tk(e){return YT(ek(e))}function rk(e){return e.replace(/start|end/g,(e=>WT[e]))}function nk(e){return e.replace(/left|right|bottom|top/g,(e=>HT[e]))}function ik(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 sk(e){const{x:t,y:r,width:n,height:i}=e;return{width:n,height:i,top:r,left:t,right:t+n,bottom:r+i,x:t,y:r}}function ok(e,t,r){let{reference:n,floating:i}=e;const s=ek(t),o=tk(t),a=ZT(o),c=QT(t),d="y"===s,l=n.x+n.width/2-i.width/2,u=n.y+n.height/2-i.height/2,p=n[a]/2-i[a]/2;let h;switch(c){case"top":h={x:l,y:n.y-i.height};break;case"bottom":h={x:l,y:n.y+n.height};break;case"right":h={x:n.x+n.width,y:u};break;case"left":h={x:n.x-i.width,y:u};break;default:h={x:n.x,y:n.y}}switch(XT(t)){case"start":h[o]-=p*(r&&d?-1:1);break;case"end":h[o]+=p*(r&&d?-1:1)}return h}async function ak(e,t){var r;void 0===t&&(t={});const{x:n,y:i,platform:s,rects:o,elements:a,strategy:c}=e,{boundary:d="clippingAncestors",rootBoundary:l="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=JT(t,e),f=ik(h),m=a[p?"floating"===u?"reference":"floating":u],g=sk(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:n,y:i,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=sk(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 ck(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function dk(e){return zT.some((t=>e[t]>=0))}function lk(e){return hk(e)?(e.nodeName||"").toLowerCase():"#document"}function uk(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function pk(e){var t;return null==(t=(hk(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function hk(e){return e instanceof Node||e instanceof uk(e).Node}function fk(e){return e instanceof Element||e instanceof uk(e).Element}function mk(e){return e instanceof HTMLElement||e instanceof uk(e).HTMLElement}function gk(e){return"undefined"!=typeof ShadowRoot&&(e instanceof ShadowRoot||e instanceof uk(e).ShadowRoot)}function vk(e){const{overflow:t,overflowX:r,overflowY:n,display:i}=Sk(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&!["inline","contents"].includes(i)}function bk(e){return["table","td","th"].includes(lk(e))}function yk(e){const t=wk(),r=Sk(e);return"none"!==r.transform||"none"!==r.perspective||!!r.containerType&&"normal"!==r.containerType||!t&&!!r.backdropFilter&&"none"!==r.backdropFilter||!t&&!!r.filter&&"none"!==r.filter||["transform","perspective","filter"].some((e=>(r.willChange||"").includes(e)))||["paint","layout","strict","content"].some((e=>(r.contain||"").includes(e)))}function wk(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function _k(e){return["html","body","#document"].includes(lk(e))}function Sk(e){return uk(e).getComputedStyle(e)}function Ck(e){return fk(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Rk(e){if("html"===lk(e))return e;const t=e.assignedSlot||e.parentNode||gk(e)&&e.host||pk(e);return gk(t)?t.host:t}function Tk(e){const t=Rk(e);return _k(t)?e.ownerDocument?e.ownerDocument.body:e.body:mk(t)&&vk(t)?t:Tk(t)}function kk(e,t,r){var n;void 0===t&&(t=[]),void 0===r&&(r=!0);const i=Tk(e),s=i===(null==(n=e.ownerDocument)?void 0:n.body),o=uk(i);return s?t.concat(o,o.visualViewport||[],vk(i)?i:[],o.frameElement&&r?kk(o.frameElement):[]):t.concat(i,kk(i,[],r))}function Pk(e){const t=Sk(e);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const i=mk(e),s=i?e.offsetWidth:r,o=i?e.offsetHeight:n,a=$T(r)!==s||$T(n)!==o;return a&&(r=s,n=o),{width:r,height:n,$:a}}function Ek(e){return fk(e)?e:e.contextElement}function Ok(e){const t=Ek(e);if(!mk(t))return qT(1);const r=t.getBoundingClientRect(),{width:n,height:i,$:s}=Pk(t);let o=(s?$T(r.width):r.width)/n,a=(s?$T(r.height):r.height)/i;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}const Ik=qT(0);function Dk(e){const t=uk(e);return wk()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:Ik}function xk(e,t,r,n){void 0===t&&(t=!1),void 0===r&&(r=!1);const i=e.getBoundingClientRect(),s=Ek(e);let o=qT(1);t&&(n?fk(n)&&(o=Ok(n)):o=Ok(e));const a=function(e,t,r){return void 0===t&&(t=!1),!(!r||t&&r!==uk(e))&&t}(s,r,n)?Dk(s):qT(0);let c=(i.left+a.x)/o.x,d=(i.top+a.y)/o.y,l=i.width/o.x,u=i.height/o.y;if(s){const e=uk(s),t=n&&fk(n)?uk(n):n;let r=e,i=r.frameElement;for(;i&&n&&t!==r;){const e=Ok(i),t=i.getBoundingClientRect(),n=Sk(i),s=t.left+(i.clientLeft+parseFloat(n.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(n.paddingTop))*e.y;c*=e.x,d*=e.y,l*=e.x,u*=e.y,c+=s,d+=o,r=uk(i),i=r.frameElement}}return sk({width:l,height:u,x:c,y:d})}const Mk=[":popover-open",":modal"];function jk(e){return Mk.some((t=>{try{return e.matches(t)}catch(e){return!1}}))}function Lk(e){return xk(pk(e)).left+Ck(e).scrollLeft}function Ak(e,t,r){let n;if("viewport"===t)n=function(e,t){const r=uk(e),n=pk(e),i=r.visualViewport;let s=n.clientWidth,o=n.clientHeight,a=0,c=0;if(i){s=i.width,o=i.height;const e=wk();(!e||e&&"fixed"===t)&&(a=i.offsetLeft,c=i.offsetTop)}return{width:s,height:o,x:a,y:c}}(e,r);else if("document"===t)n=function(e){const t=pk(e),r=Ck(e),n=e.ownerDocument.body,i=UT(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),s=UT(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let o=-r.scrollLeft+Lk(e);const a=-r.scrollTop;return"rtl"===Sk(n).direction&&(o+=UT(t.clientWidth,n.clientWidth)-i),{width:i,height:s,x:o,y:a}}(pk(e));else if(fk(t))n=function(e,t){const r=xk(e,!0,"fixed"===t),n=r.top+e.clientTop,i=r.left+e.clientLeft,s=mk(e)?Ok(e):qT(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:i*s.x,y:n*s.y}}(t,r);else{const r=Dk(e);n={...t,x:t.x-r.x,y:t.y-r.y}}return sk(n)}function Nk(e,t){const r=Rk(e);return!(r===t||!fk(r)||_k(r))&&("fixed"===Sk(r).position||Nk(r,t))}function Bk(e,t,r){const n=mk(t),i=pk(t),s="fixed"===r,o=xk(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=qT(0);if(n||!n&&!s)if(("body"!==lk(t)||vk(i))&&(a=Ck(t)),n){const e=xk(t,!0,s,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else i&&(c.x=Lk(i));return{x:o.left+a.scrollLeft-c.x,y:o.top+a.scrollTop-c.y,width:o.width,height:o.height}}function Fk(e){return"static"===Sk(e).position}function zk(e,t){return mk(e)&&"fixed"!==Sk(e).position?t?t(e):e.offsetParent:null}function Vk(e,t){const r=uk(e);if(jk(e))return r;if(!mk(e)){let t=Rk(e);for(;t&&!_k(t);){if(fk(t)&&!Fk(t))return t;t=Rk(t)}return r}let n=zk(e,t);for(;n&&bk(n)&&Fk(n);)n=zk(n,t);return n&&_k(n)&&Fk(n)&&!yk(n)?r:n||function(e){let t=Rk(e);for(;mk(t)&&!_k(t);){if(yk(t))return t;t=Rk(t)}return null}(e)||r}const Uk={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:r,offsetParent:n,strategy:i}=e;const s="fixed"===i,o=pk(n),a=!!t&&jk(t.floating);if(n===o||a&&s)return r;let c={scrollLeft:0,scrollTop:0},d=qT(1);const l=qT(0),u=mk(n);if((u||!u&&!s)&&(("body"!==lk(n)||vk(o))&&(c=Ck(n)),mk(n))){const e=xk(n);d=Ok(n),l.x=e.x+n.clientLeft,l.y=e.y+n.clientTop}return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+l.x,y:r.y*d.y-c.scrollTop*d.y+l.y}},getDocumentElement:pk,getClippingRect:function(e){let{element:t,boundary:r,rootBoundary:n,strategy:i}=e;const s="clippingAncestors"===r?jk(t)?[]:function(e,t){const r=t.get(e);if(r)return r;let n=kk(e,[],!1).filter((e=>fk(e)&&"body"!==lk(e))),i=null;const s="fixed"===Sk(e).position;let o=s?Rk(e):e;for(;fk(o)&&!_k(o);){const t=Sk(o),r=yk(o);r||"fixed"!==t.position||(i=null),(s?!r&&!i:!r&&"static"===t.position&&i&&["absolute","fixed"].includes(i.position)||vk(o)&&!r&&Nk(e,o))?n=n.filter((e=>e!==o)):i=t,o=Rk(o)}return t.set(e,n),n}(t,this._c):[].concat(r),o=[...s,n],a=o[0],c=o.reduce(((e,r)=>{const n=Ak(t,r,i);return e.top=UT(n.top,e.top),e.right=VT(n.right,e.right),e.bottom=VT(n.bottom,e.bottom),e.left=UT(n.left,e.left),e}),Ak(t,a,i));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:Vk,getElementRects:async function(e){const t=this.getOffsetParent||Vk,r=this.getDimensions,n=await r(e.floating);return{reference:Bk(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:r}=Pk(e);return{width:t,height:r}},getScale:Ok,isElement:fk,isRTL:function(e){return"rtl"===Sk(e).direction}};function $k(e,t,r,n){void 0===n&&(n={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=n,d=Ek(e),l=i||s?[...d?kk(d):[],...kk(t)]:[];l.forEach((e=>{i&&e.addEventListener("scroll",r,{passive:!0}),s&&e.addEventListener("resize",r)}));const u=d&&a?function(e,t){let r,n=null;const i=pk(e);function s(){var e;clearTimeout(r),null==(e=n)||e.disconnect(),n=null}return function o(a,c){void 0===a&&(a=!1),void 0===c&&(c=1),s();const{left:d,top:l,width:u,height:p}=e.getBoundingClientRect();if(a||t(),!u||!p)return;const h={rootMargin:-GT(l)+"px "+-GT(i.clientWidth-(d+u))+"px "+-GT(i.clientHeight-(l+p))+"px "+-GT(d)+"px",threshold:UT(0,VT(1,c))||1};let f=!0;function m(e){const t=e[0].intersectionRatio;if(t!==c){if(!f)return o();t?o(!1,t):r=setTimeout((()=>{o(!1,1e-7)}),1e3)}f=!1}try{n=new IntersectionObserver(m,{...h,root:i.ownerDocument})}catch(e){n=new IntersectionObserver(m,h)}n.observe(e)}(!0),s}(d,r):null;let p,h=-1,f=null;o&&(f=new ResizeObserver((e=>{let[n]=e;n&&n.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?xk(e):null;return c&&function t(){const n=xk(e);!m||n.x===m.x&&n.y===m.y&&n.width===m.width&&n.height===m.height||r();m=n,p=requestAnimationFrame(t)}(),r(),()=>{var e;l.forEach((e=>{i&&e.removeEventListener("scroll",r),s&&e.removeEventListener("resize",r)})),null==u||u(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}const Gk=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var r,n;const{x:i,y:s,placement:o,middlewareData:a}=t,c=await async function(e,t){const{placement:r,platform:n,elements:i}=e,s=await(null==n.isRTL?void 0:n.isRTL(i.floating)),o=QT(r),a=XT(r),c="y"===ek(r),d=["left","top"].includes(o)?-1:1,l=s&&c?-1:1,u=JT(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...u};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!=(n=a.arrow)&&n.alignmentOffset?{}:{x:i+c.x,y:s+c.y,data:{...c,placement:o}}}}},qk=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:n,placement:i}=t,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:r}=e;return{x:t,y:r}}},...c}=JT(e,t),d={x:r,y:n},l=await ak(t,c),u=ek(QT(i)),p=YT(u);let h=d[p],f=d[u];if(s){const e="y"===p?"bottom":"right";h=KT(h+l["y"===p?"top":"left"],h,h-l[e])}if(o){const e="y"===u?"bottom":"right";f=KT(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-n}}}}},Hk=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var r,n;const{placement:i,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}=JT(e,t);if(null!=(r=s.arrow)&&r.alignmentOffset)return{};const v=QT(i),b=QT(a)===a,y=await(null==c.isRTL?void 0:c.isRTL(d.floating)),w=p||(b||!m?[nk(a)]:function(e){const t=nk(e);return[rk(e),t,rk(t)]}(a));p||"none"===f||w.push(...function(e,t,r,n){const i=XT(e);let s=function(e,t,r){const n=["left","right"],i=["right","left"],s=["top","bottom"],o=["bottom","top"];switch(e){case"top":case"bottom":return r?t?i:n:t?n:i;case"left":case"right":return t?s:o;default:return[]}}(QT(e),"start"===r,n);return i&&(s=s.map((e=>e+"-"+i)),t&&(s=s.concat(s.map(rk)))),s}(a,m,f,y));const _=[a,...w],S=await ak(t,g),C=[];let R=(null==(n=s.flip)?void 0:n.overflows)||[];if(l&&C.push(S[v]),u){const e=function(e,t,r){void 0===r&&(r=!1);const n=XT(e),i=tk(e),s=ZT(i);let o="x"===i?n===(r?"end":"start")?"right":"left":"start"===n?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=nk(o)),[o,nk(o)]}(i,o,y);C.push(S[e[0]],S[e[1]])}if(R=[...R,{placement:i,overflows:C}],!C.every((e=>e<=0))){var T,k;const e=((null==(T=s.flip)?void 0:T.index)||0)+1,t=_[e];if(t)return{data:{index:e,overflows:R},reset:{placement:t}};let r=null==(k=R.filter((e=>e.overflows[0]<=0)).sort(((e,t)=>e.overflows[1]-t.overflows[1]))[0])?void 0:k.placement;if(!r)switch(h){case"bestFit":{var P;const e=null==(P=R.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:P[0];e&&(r=e);break}case"initialPlacement":r=a}if(i!==r)return{reset:{placement:r}}}return{}}}},Wk=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){const{placement:r,rects:n,platform:i,elements:s}=t,{apply:o=(()=>{}),...a}=JT(e,t),c=await ak(t,a),d=QT(r),l=XT(r),u="y"===ek(r),{width:p,height:h}=n.floating;let f,m;"top"===d||"bottom"===d?(f=d,m=l===(await(null==i.isRTL?void 0:i.isRTL(s.floating))?"start":"end")?"left":"right"):(m=d,f="end"===l?"top":"bottom");const g=h-c.top-c.bottom,v=p-c.left-c.right,b=VT(h-c[f],g),y=VT(p-c[m],v),w=!t.middlewareData.shift;let _=b,S=y;if(u?S=l||w?VT(y,v):v:_=l||w?VT(b,g):g,w&&!l){const e=UT(c.left,0),t=UT(c.right,0),r=UT(c.top,0),n=UT(c.bottom,0);u?S=p-2*(0!==e||0!==t?e+t:UT(c.left,c.right)):_=h-2*(0!==r||0!==n?r+n:UT(c.top,c.bottom))}await o({...t,availableWidth:S,availableHeight:_});const C=await i.getDimensions(s.floating);return p!==C.width||h!==C.height?{reset:{rects:!0}}:{}}}},Kk=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:r}=t,{strategy:n="referenceHidden",...i}=JT(e,t);switch(n){case"referenceHidden":{const e=ck(await ak(t,{...i,elementContext:"reference"}),r.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:dk(e)}}}case"escaped":{const e=ck(await ak(t,{...i,altBoundary:!0}),r.floating);return{data:{escapedOffsets:e,escaped:dk(e)}}}default:return{}}}}},Jk=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:n,placement:i,rects:s,platform:o,elements:a,middlewareData:c}=t,{element:d,padding:l=0}=JT(e,t)||{};if(null==d)return{};const u=ik(l),p={x:r,y:n},h=tk(i),f=ZT(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,T=C/2-m[f]/2-1,k=VT(u[v],T),P=VT(u[b],T),E=k,O=C-m[f]-P,I=C/2-m[f]/2+R,D=KT(E,I,O),x=!c.arrow&&null!=XT(i)&&I!==D&&s.reference[f]/2-(I<E?k:P)-m[f]/2<0,M=x?I<E?I-E:I-O:0;return{[h]:p[h]+M,data:{[h]:D,centerOffset:I-D-M,...x&&{alignmentOffset:M}},reset:x}}}),Qk=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:r,y:n,placement:i,rects:s,middlewareData:o}=t,{offset:a=0,mainAxis:c=!0,crossAxis:d=!0}=JT(e,t),l={x:r,y:n},u=ek(i),p=YT(u);let h=l[p],f=l[u];const m=JT(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=["top","left"].includes(QT(i)),r=s.reference[u]-s.floating[e]+(t&&(null==(v=o.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),n=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>n&&(f=n)}return{[p]:h,[u]:f}}}},Xk=(e,t,r)=>{const n=new Map,i={platform:Uk,...r},s={...i.platform,_c:n};return(async(e,t,r)=>{const{placement:n="bottom",strategy:i="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:i}),{x:l,y:u}=ok(d,n,c),p=n,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:n,placement:p,strategy:i,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:i}):y.rects),({x:l,y:u}=ok(d,p,c))),r=-1)}return{x:l,y:u,placement:p,strategy:i,middlewareData:h}})(e,t,{...i,platform:s})};var Yk="undefined"!=typeof document?t.useLayoutEffect:t.useEffect;function Zk(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,n,i;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;0!=n--;)if(!Zk(e[n],t[n]))return!1;return!0}if(i=Object.keys(e),r=i.length,r!==Object.keys(t).length)return!1;for(n=r;0!=n--;)if(!{}.hasOwnProperty.call(t,i[n]))return!1;for(n=r;0!=n--;){const r=i[n];if(("_owner"!==r||!e.$$typeof)&&!Zk(e[r],t[r]))return!1}return!0}return e!=e&&t!=t}function eP(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function tP(e,t){const r=eP(e);return Math.round(t*r)/r}function rP(e){const t=s.useRef(e);return Yk((()=>{t.current=e})),t}const nP=e=>({name:"arrow",options:e,fn(t){const{element:r,padding:n}="function"==typeof e?e(t):e;return r&&function(e){return{}.hasOwnProperty.call(e,"current")}(r)?null!=r.current?Jk({element:r.current,padding:n}).fn(t):{}:r?Jk({element:r,padding:n}).fn(t):{}}}),iP=(e,t)=>({...Gk(e),options:[e,t]}),sP=(e,t)=>({...qk(e),options:[e,t]}),oP=(e,t)=>({...Qk(e),options:[e,t]}),aP=(e,t)=>({...Hk(e),options:[e,t]}),cP=(e,t)=>({...Wk(e),options:[e,t]}),dP=(e,t)=>({...Kk(e),options:[e,t]}),lP=(e,t)=>({...nP(e),options:[e,t]});const uP="Popper",[pP,hP]=aT(uP),[fP,mP]=pP(uP),gP=t.forwardRef(((e,r)=>{const{__scopePopper:n,virtualRef:i,...s}=e,o=mP("PopperAnchor",n),a=t.useRef(null),c=oT(r,a);return t.useEffect((()=>{o.onAnchorChange((null==i?void 0:i.current)||a.current)})),i?null:t.createElement(fT.div,nT({},s,{ref:c}))})),vP="PopperContent",[bP,yP]=pP(vP),wP=t.forwardRef(((e,r)=>{var n,i,a,c,d,l,u,p;const{__scopePopper:h,side:f="bottom",sideOffset:m=0,align:g="center",alignOffset:v=0,arrowPadding:b=0,avoidCollisions:y=!0,collisionBoundary:w=[],collisionPadding:_=0,sticky:S="partial",hideWhenDetached:C=!1,updatePositionStrategy:R="optimized",onPlaced:T,...k}=e,P=mP(vP,h),[E,O]=t.useState(null),I=oT(r,(e=>O(e))),[D,x]=t.useState(null),M=function(e){const[r,n]=t.useState(void 0);return AT((()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver((t=>{if(!Array.isArray(t))return;if(!t.length)return;const r=t[0];let i,s;if("borderBoxSize"in r){const e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;i=t.inlineSize,s=t.blockSize}else i=e.offsetWidth,s=e.offsetHeight;n({width:i,height:s})}));return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}n(void 0)}),[e]),r}(D),j=null!==(n=null==M?void 0:M.width)&&void 0!==n?n:0,L=null!==(i=null==M?void 0:M.height)&&void 0!==i?i:0,A=f+("center"!==g?"-"+g:""),N="number"==typeof _?_:{top:0,right:0,bottom:0,left:0,..._},B=Array.isArray(w)?w:[w],F=B.length>0,z={padding:N,boundary:B.filter(_P),altBoundary:F},{refs:V,floatingStyles:U,placement:$,isPositioned:G,middlewareData:q}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:i,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(n);Zk(f,n)||m(n);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!==T.current&&(T.current=e,y(e))}),[]),S=a||g,C=c||b,R=s.useRef(null),T=s.useRef(null),k=s.useRef(p),P=null!=l,E=rP(l),O=rP(i),I=s.useCallback((()=>{if(!R.current||!T.current)return;const e={placement:t,strategy:r,middleware:f};O.current&&(e.platform=O.current),Xk(R.current,T.current,e).then((e=>{const t={...e,isPositioned:!0};D.current&&!Zk(k.current,t)&&(k.current=t,o.flushSync((()=>{h(t)})))}))}),[f,t,r,O]);Yk((()=>{!1===u&&k.current.isPositioned&&(k.current.isPositioned=!1,h((e=>({...e,isPositioned:!1}))))}),[u]);const D=s.useRef(!1);Yk((()=>(D.current=!0,()=>{D.current=!1})),[]),Yk((()=>{if(S&&(R.current=S),C&&(T.current=C),S&&C){if(E.current)return E.current(S,C,I);I()}}),[S,C,I,E,P]);const x=s.useMemo((()=>({reference:R,floating:T,setReference:w,setFloating:_})),[w,_]),M=s.useMemo((()=>({reference:S,floating:C})),[S,C]),j=s.useMemo((()=>{const e={position:r,left:0,top:0};if(!M.floating)return e;const t=tP(M.floating,p.x),n=tP(M.floating,p.y);return d?{...e,transform:"translate("+t+"px, "+n+"px)",...eP(M.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:t,top:n}}),[r,d,M.floating,p.x,p.y]);return s.useMemo((()=>({...p,update:I,refs:x,elements:M,floatingStyles:j})),[p,I,x,M,j])}({strategy:"fixed",placement:A,whileElementsMounted:(...e)=>$k(...e,{animationFrame:"always"===R}),elements:{reference:P.anchor},middleware:[iP({mainAxis:m+L,alignmentAxis:v}),y&&sP({mainAxis:!0,crossAxis:!1,limiter:"partial"===S?oP():void 0,...z}),y&&aP({...z}),cP({...z,apply:({elements:e,rects:t,availableWidth:r,availableHeight:n})=>{const{width:i,height:s}=t.reference,o=e.floating.style;o.setProperty("--radix-popper-available-width",`${r}px`),o.setProperty("--radix-popper-available-height",`${n}px`),o.setProperty("--radix-popper-anchor-width",`${i}px`),o.setProperty("--radix-popper-anchor-height",`${s}px`)}}),D&&lP({element:D,padding:b}),SP({arrowWidth:j,arrowHeight:L}),C&&dP({strategy:"referenceHidden",...z})]}),[H,W]=CP($),K=mT(T);AT((()=>{G&&(null==K||K())}),[G,K]);const J=null===(a=q.arrow)||void 0===a?void 0:a.x,Q=null===(c=q.arrow)||void 0===c?void 0:c.y,X=0!==(null===(d=q.arrow)||void 0===d?void 0:d.centerOffset),[Y,Z]=t.useState();return AT((()=>{E&&Z(window.getComputedStyle(E).zIndex)}),[E]),t.createElement("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...U,transform:G?U.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[null===(l=q.transformOrigin)||void 0===l?void 0:l.x,null===(u=q.transformOrigin)||void 0===u?void 0:u.y].join(" ")},dir:e.dir},t.createElement(bP,{scope:h,placedSide:H,onArrowChange:x,arrowX:J,arrowY:Q,shouldHideArrow:X},t.createElement(fT.div,nT({"data-side":H,"data-align":W},k,{ref:I,style:{...k.style,animation:G?void 0:"none",opacity:null!==(p=q.hide)&&void 0!==p&&p.referenceHidden?0:void 0}}))))}));function _P(e){return null!==e}const SP=e=>({name:"transformOrigin",options:e,fn(t){var r,n,i,s,o;const{placement:a,rects:c,middlewareData:d}=t,l=0!==(null===(r=d.arrow)||void 0===r?void 0:r.centerOffset),u=l?0:e.arrowWidth,p=l?0:e.arrowHeight,[h,f]=CP(a),m={start:"0%",center:"50%",end:"100%"}[f],g=(null!==(n=null===(i=d.arrow)||void 0===i?void 0:i.x)&&void 0!==n?n:0)+u/2,v=(null!==(s=null===(o=d.arrow)||void 0===o?void 0:o.y)&&void 0!==s?s:0)+p/2;let b="",y="";return"bottom"===h?(b=l?m:`${g}px`,y=-p+"px"):"top"===h?(b=l?m:`${g}px`,y=`${c.floating.height+p}px`):"right"===h?(b=-p+"px",y=l?m:`${v}px`):"left"===h&&(b=`${c.floating.width+p}px`,y=l?m:`${v}px`),{data:{x:b,y:y}}}});function CP(e){const[t,r="center"]=e.split("-");return[t,r]}const RP=e=>{const{__scopePopper:r,children:n}=e,[i,s]=t.useState(null);return t.createElement(fP,{scope:r,anchor:i,onAnchorChange:s},n)},TP=gP,kP=wP,PP=t.forwardRef(((e,n)=>{var i;const{container:s=(null===globalThis||void 0===globalThis||null===(i=globalThis.document)||void 0===i?void 0:i.body),...o}=e;return s?r.createPortal(t.createElement(fT.div,nT({},o,{ref:n})),s):null}));const EP=e=>{const{present:n,children:i}=e,s=function(e){const[n,i]=t.useState(),s=t.useRef({}),o=t.useRef(e),a=t.useRef("none"),c=e?"mounted":"unmounted",[d,l]=function(e,r){return t.useReducer(((e,t)=>{const n=r[e][t];return null!=n?n:e}),e)}(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return t.useEffect((()=>{const e=OP(s.current);a.current="mounted"===d?e:"none"}),[d]),AT((()=>{const t=s.current,r=o.current;if(r!==e){const n=a.current,i=OP(t);if(e)l("MOUNT");else if("none"===i||"none"===(null==t?void 0:t.display))l("UNMOUNT");else{l(r&&n!==i?"ANIMATION_OUT":"UNMOUNT")}o.current=e}}),[e,l]),AT((()=>{if(n){const e=e=>{const t=OP(s.current).includes(e.animationName);e.target===n&&t&&r.flushSync((()=>l("ANIMATION_END")))},t=e=>{e.target===n&&(a.current=OP(s.current))};return n.addEventListener("animationstart",t),n.addEventListener("animationcancel",e),n.addEventListener("animationend",e),()=>{n.removeEventListener("animationstart",t),n.removeEventListener("animationcancel",e),n.removeEventListener("animationend",e)}}l("ANIMATION_END")}),[n,l]),{isPresent:["mounted","unmountSuspended"].includes(d),ref:t.useCallback((e=>{e&&(s.current=getComputedStyle(e)),i(e)}),[])}}(n),o="function"==typeof i?i({present:s.isPresent}):t.Children.only(i),a=oT(s.ref,o.ref);return"function"==typeof i||s.isPresent?t.cloneElement(o,{ref:a}):null};function OP(e){return(null==e?void 0:e.animationName)||"none"}function IP({prop:e,defaultProp:r,onChange:n=(()=>{})}){const[i,s]=function({defaultProp:e,onChange:r}){const n=t.useState(e),[i]=n,s=t.useRef(i),o=mT(r);return t.useEffect((()=>{s.current!==i&&(o(i),s.current=i)}),[i,s,o]),n}({defaultProp:r,onChange:n}),o=void 0!==e,a=o?e:i,c=mT(n),d=t.useCallback((t=>{if(o){const r="function"==typeof t?t(e):t;r!==e&&c(r)}else s(t)}),[o,e,s,c]);return[a,d]}EP.displayName="Presence";var DP=new WeakMap,xP=new WeakMap,MP={},jP=0,LP=function(e){return e&&(e.host||LP(e.parentNode))},AP=function(e,t,r,n){var i=function(e,t){return t.map((function(t){if(e.contains(t))return t;var r=LP(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]);MP[r]||(MP[r]=new WeakMap);var s=MP[r],o=[],a=new Set,c=new Set(i),d=function(e){e&&!a.has(e)&&(a.add(e),d(e.parentNode))};i.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(n),i=null!==t&&"false"!==t,c=(DP.get(e)||0)+1,d=(s.get(e)||0)+1;DP.set(e,c),s.set(e,d),o.push(e),1===c&&i&&xP.set(e,!0),1===d&&e.setAttribute(r,"true"),i||e.setAttribute(n,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}}))};return l(t),a.clear(),jP++,function(){o.forEach((function(e){var t=DP.get(e)-1,i=s.get(e)-1;DP.set(e,t),s.set(e,i),t||(xP.has(e)||e.removeAttribute(n),xP.delete(e)),i||e.removeAttribute(r)})),--jP||(DP=new WeakMap,DP=new WeakMap,xP=new WeakMap,MP={})}},NP=function(e,t,r){void 0===r&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),i=t||function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live]"))),AP(n,i,r,"aria-hidden")):function(){return null}},BP="right-scroll-bar-position",FP="width-before-scroll-bar";function zP(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var VP=new WeakMap;function UP(e,r){var n,i,o,a=(n=r||null,i=function(t){return e.forEach((function(e){return zP(e,t)}))},o=t.useState((function(){return{value:n,callback:i,facade:{get current(){return o.value},set current(e){var t=o.value;t!==e&&(o.value=e,o.callback(e,t))}}}}))[0],o.callback=i,o.facade);return s.useLayoutEffect((function(){var t=VP.get(a);if(t){var r=new Set(t),n=new Set(e),i=a.current;r.forEach((function(e){n.has(e)||zP(e,null)})),n.forEach((function(e){r.has(e)||zP(e,i)}))}VP.set(a,e)}),[e]),a}function $P(e){return e}var GP=function(e){var t=e.sideCar,r=EC(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return s.createElement(n,PC({},r))};GP.isSideCarExport=!0;var qP=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=$P);var r=[],n=!1;return{read:function(){if(n)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 i=t(e,n);return r.push(i),function(){r=r.filter((function(e){return e!==i}))}},assignSyncMedium:function(e){for(n=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){n=!0;var t=[];if(r.length){var i=r;r=[],i.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=PC({async:!0,ssr:!1},e),t}(),HP=function(){},WP=s.forwardRef((function(e,t){var r=s.useRef(null),n=s.useState({onScrollCapture:HP,onWheelCapture:HP,onTouchMoveCapture:HP}),i=n[0],o=n[1],a=e.forwardProps,c=e.children,d=e.className,l=e.removeScrollBar,u=e.enabled,p=e.shards,h=e.sideCar,f=e.noIsolation,m=e.inert,g=e.allowPinchZoom,v=e.as,b=void 0===v?"div":v,y=EC(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as"]),w=h,_=UP([r,t]),S=PC(PC({},y),i);return s.createElement(s.Fragment,null,u&&s.createElement(w,{sideCar:qP,removeScrollBar:l,shards:p,noIsolation:f,inert:m,setCallbacks:o,allowPinchZoom:!!g,lockRef:r}),a?s.cloneElement(s.Children.only(c),PC(PC({},S),{ref:_})):s.createElement(b,PC({},S,{className:d,ref:_}),c))}));WP.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},WP.classNames={fullWidth:FP,zeroRight:BP};function KP(){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 JP=function(){var e=0,t=null;return{add:function(r){var n,i;0==e&&(t=KP())&&(i=r,(n=t).styleSheet?n.styleSheet.cssText=i:n.appendChild(document.createTextNode(i)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},QP=function(){var e,t=(e=JP(),function(t,r){s.useEffect((function(){return e.add(t),function(){e.remove()}}),[t&&r])});return function(e){var r=e.styles,n=e.dynamic;return t(r,n),null}},XP={left:0,top:0,right:0,gap:0},YP=function(e){return parseInt(e||"",10)||0},ZP=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return XP;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],n=t["padding"===e?"paddingTop":"marginTop"],i=t["padding"===e?"paddingRight":"marginRight"];return[YP(r),YP(n),YP(i)]}(e),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},eE=QP(),tE="data-scroll-locked",rE=function(e,t,r,n){var i=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(n,";\n padding-right: ").concat(a,"px ").concat(n,";\n }\n body[").concat(tE,"] {\n overflow: hidden ").concat(n,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(n,";"),"margin"===r&&"\n padding-left: ".concat(i,"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(n,";\n "),"padding"===r&&"padding-right: ".concat(a,"px ").concat(n,";")].filter(Boolean).join(""),"\n }\n \n .").concat(BP," {\n right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(FP," {\n margin-right: ").concat(a,"px ").concat(n,";\n }\n \n .").concat(BP," .").concat(BP," {\n right: 0 ").concat(n,";\n }\n \n .").concat(FP," .").concat(FP," {\n margin-right: 0 ").concat(n,";\n }\n \n body[").concat(tE,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(a,"px;\n }\n")},nE=function(){var e=parseInt(document.body.getAttribute(tE)||"0",10);return isFinite(e)?e:0},iE=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,i=void 0===n?"margin":n;s.useEffect((function(){return document.body.setAttribute(tE,(nE()+1).toString()),function(){var e=nE()-1;e<=0?document.body.removeAttribute(tE):document.body.setAttribute(tE,e.toString())}}),[]);var o=s.useMemo((function(){return ZP(i)}),[i]);return s.createElement(eE,{styles:rE(o,!t,i,r?"":"!important")})},sE=!1;if("undefined"!=typeof window)try{var oE=Object.defineProperty({},"passive",{get:function(){return sE=!0,!0}});window.addEventListener("test",oE,oE),window.removeEventListener("test",oE,oE)}catch(pO){sE=!1}var aE=!!sE&&{passive:!1},cE=function(e,t){var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},dE=function(e,t){var r=t;do{if("undefined"!=typeof ShadowRoot&&r instanceof ShadowRoot&&(r=r.host),lE(e,r)){var n=uE(e,r);if(n[1]>n[2])return!0}r=r.parentNode}while(r&&r!==document.body);return!1},lE=function(e,t){return"v"===e?function(e){return cE(e,"overflowY")}(t):function(e){return cE(e,"overflowX")}(t)},uE=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)},pE=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},hE=function(e){return[e.deltaX,e.deltaY]},fE=function(e){return e&&"current"in e?e.current:e},mE=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},gE=0,vE=[];var bE,yE=(bE=function(e){var t=s.useRef([]),r=s.useRef([0,0]),n=s.useRef(),i=s.useState(gE++)[0],o=s.useState((function(){return QP()}))[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(i));var t=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(fE),!0).filter(Boolean);return t.forEach((function(e){return e.classList.add("allow-interactivity-".concat(i))})),function(){document.body.classList.remove("block-interactivity-".concat(i)),t.forEach((function(e){return e.classList.remove("allow-interactivity-".concat(i))}))}}}),[e.inert,e.lockRef.current,e.shards]);var c=s.useCallback((function(e,t){if("touches"in e&&2===e.touches.length)return!a.current.allowPinchZoom;var i,s=pE(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=dE(u,l);if(!p)return!0;if(p?i=u:(i="v"===u?"h":"v",p=dE(u,l)),!p)return!1;if(!n.current&&"changedTouches"in e&&(c||d)&&(n.current=i),!i)return!0;var h=n.current||i;return function(e,t,r,n,i){var s=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),o=s*n,a=r.target,c=t.contains(a),d=!1,l=o>0,u=0,p=0;do{var h=uE(e,a),f=h[0],m=h[1]-h[2]-s*f;(f||m)&&lE(e,a)&&(u+=m,p+=f),a=a.parentNode}while(!c&&a!==document.body||c&&(t.contains(a)||t===a));return(l&&(i&&0===u||!i&&o>u)||!l&&(i&&0===p||!i&&-o>p))&&(d=!0),d}(h,t,e,"h"===h?c:d,!0)}),[]),d=s.useCallback((function(e){var r=e;if(vE.length&&vE[vE.length-1]===o){var n="deltaY"in r?hE(r):pE(r),i=t.current.filter((function(e){return e.name===r.type&&e.target===r.target&&(t=e.delta,i=n,t[0]===i[0]&&t[1]===i[1]);var t,i}))[0];if(i&&i.should)r.cancelable&&r.preventDefault();else if(!i){var s=(a.current.shards||[]).map(fE).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,n,i){var s={name:e,delta:r,target:n,should: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=pE(e),n.current=void 0}),[]),p=s.useCallback((function(t){l(t.type,hE(t),t.target,c(t,e.lockRef.current))}),[]),h=s.useCallback((function(t){l(t.type,pE(t),t.target,c(t,e.lockRef.current))}),[]);s.useEffect((function(){return vE.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,aE),document.addEventListener("touchmove",d,aE),document.addEventListener("touchstart",u,aE),function(){vE=vE.filter((function(e){return e!==o})),document.removeEventListener("wheel",d,aE),document.removeEventListener("touchmove",d,aE),document.removeEventListener("touchstart",u,aE)}}),[]);var f=e.removeScrollBar,m=e.inert;return s.createElement(s.Fragment,null,m?s.createElement(o,{styles:mE(i)}):null,f?s.createElement(iE,{gapMode:"margin"}):null)},qP.useMedium(bE),GP),wE=s.forwardRef((function(e,t){return s.createElement(WP,PC({},e,{ref:t,sideCar:yE}))}));wE.classNames=WP.classNames;var _E=wE;const SE="Popover",[CE,RE]=aT(SE,[hP]),TE=hP(),[kE,PE]=CE(SE),EE=t.forwardRef(((e,r)=>{const{__scopePopover:n,...i}=e,s=PE("PopoverTrigger",n),o=TE(n),a=oT(r,s.triggerRef),c=t.createElement(fT.button,nT({type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":NE(s.open)},i,{ref:a,onClick:iT(e.onClick,s.onOpenToggle)}));return s.hasCustomAnchor?c:t.createElement(TP,nT({asChild:!0},o),c)})),OE="PopoverPortal",[IE,DE]=CE(OE,{forceMount:void 0}),xE="PopoverContent",ME=t.forwardRef(((e,r)=>{const n=DE(xE,e.__scopePopover),{forceMount:i=n.forceMount,...s}=e,o=PE(xE,e.__scopePopover);return t.createElement(EP,{present:i||o.open},o.modal?t.createElement(jE,nT({},s,{ref:r})):t.createElement(LE,nT({},s,{ref:r})))})),jE=t.forwardRef(((e,r)=>{const n=PE(xE,e.__scopePopover),i=t.useRef(null),s=oT(r,i),o=t.useRef(!1);return t.useEffect((()=>{const e=i.current;if(e)return NP(e)}),[]),t.createElement(_E,{as:dT,allowPinchZoom:!0},t.createElement(AE,nT({},e,{ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:iT(e.onCloseAutoFocus,(e=>{var t;e.preventDefault(),o.current||null===(t=n.triggerRef.current)||void 0===t||t.focus()})),onPointerDownOutside:iT(e.onPointerDownOutside,(e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey,n=2===t.button||r;o.current=n}),{checkForDefaultPrevented:!1}),onFocusOutside:iT(e.onFocusOutside,(e=>e.preventDefault()),{checkForDefaultPrevented:!1})})))})),LE=t.forwardRef(((e,r)=>{const n=PE(xE,e.__scopePopover),i=t.useRef(!1),s=t.useRef(!1);return t.createElement(AE,nT({},e,{ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{var r,o;(null===(r=e.onCloseAutoFocus)||void 0===r||r.call(e,t),t.defaultPrevented)||(i.current||null===(o=n.triggerRef.current)||void 0===o||o.focus(),t.preventDefault());i.current=!1,s.current=!1},onInteractOutside:t=>{var r,o;null===(r=e.onInteractOutside)||void 0===r||r.call(e,t),t.defaultPrevented||(i.current=!0,"pointerdown"===t.detail.originalEvent.type&&(s.current=!0));const a=t.target;(null===(o=n.triggerRef.current)||void 0===o?void 0:o.contains(a))&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&s.current&&t.preventDefault()}}))})),AE=t.forwardRef(((e,r)=>{const{__scopePopover:n,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onInteractOutside:u,...p}=e,h=PE(xE,n),f=TE(n);return t.useEffect((()=>{var e,t;const r=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",null!==(e=r[0])&&void 0!==e?e:TT()),document.body.insertAdjacentElement("beforeend",null!==(t=r[1])&&void 0!==t?t:TT()),RT++,()=>{1===RT&&document.querySelectorAll("[data-radix-focus-guard]").forEach((e=>e.remove())),RT--}}),[]),t.createElement(OT,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:s,onUnmountAutoFocus:o},t.createElement(_T,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:l,onDismiss:()=>h.onOpenChange(!1)},t.createElement(kP,nT({"data-state":NE(h.open),role:"dialog",id:h.contentId},f,p,{ref:r,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)"}}))))}));function NE(e){return e?"open":"closed"}const BE=e=>{const{__scopePopover:r,forceMount:n,children:i,container:s}=e,o=PE(OE,r);return t.createElement(IE,{scope:r,forceMount:n},t.createElement(EP,{present:n||o.open},t.createElement(PP,{asChild:!0,container:s},i)))},FE=ME,zE=e=>{const{__scopePopover:r,children:n,open:i,defaultOpen:s,onOpenChange:o,modal:a=!1}=e,c=TE(r),d=t.useRef(null),[l,u]=t.useState(!1),[p=!1,h]=IP({prop:i,defaultProp:s,onChange:o});return t.createElement(RP,c,t.createElement(kE,{scope:r,contentId:FT(),triggerRef:d,open:p,onOpenChange:h,onOpenToggle:t.useCallback((()=>h((e=>!e))),[h]),hasCustomAnchor:l,onCustomAnchorAdd:t.useCallback((()=>u(!0)),[]),onCustomAnchorRemove:t.useCallback((()=>u(!1)),[]),modal:a},n))},VE=EE,UE=s.forwardRef(((e,t)=>{var{style:r,align:n="center",sideOffset:i=4}=e,o=EC(e,["style","align","sideOffset"]);return s.createElement(BE,null,s.createElement(FE,Object.assign({ref:t,align:n,sideOffset:i,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)))}));UE.displayName=FE.displayName;const $E=s.createContext({}),GE=s.createContext({}),qE=()=>{const e=s.useContext($E),t=s.useContext(GE);if(!t)throw new Error("useGridCell must be used within a GridCell");return Object.assign(Object.assign({},e),t)},HE=s.createContext({}),WE=e=>{const{children:t}=e,r=EC(e,["children"]),[n,i]=s.useState(!1);return s.createElement(HE.Provider,{value:{open:n,setOpen:i}},s.createElement(zE,Object.assign({},r,{open:n,onOpenChange:i}),t))},KE=s.forwardRef(((e,t)=>{var{children:r,style:n}=e,i=EC(e,["children","style"]);return s.createElement(UE,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},n)},i),r)}));KE.displayName="ParticipantMenuContent";const JE=s.forwardRef(((e,t)=>{var{children:r,style:n}=e,i=EC(e,["children","style"]);return s.createElement(VE,Object.assign({ref:t,style:Object.assign({position:"absolute",top:"10px",right:"20px",textDecoration:"none",whiteSpace:"nowrap",border:"none",cursor:"pointer"},n)},i),r)}));JE.displayName=VE.displayName;const QE=s.forwardRef(((e,t)=>{var{children:r,style:n,participantAction:i}=e,o=EC(e,["children","style","participantAction"]);const{participant:a,setOpen:c,maximizedParticipant:d,setMaximizedParticipant:l,setFloatingParticipant:u,floatingParticipant:p}=(()=>{const e=s.useContext(HE),t=qE();if(!e)throw new Error("useParticipantMenu must be used within a ParticipantMenu");return Object.assign(Object.assign({},e),t)})(),h=OC(),f=IC(jS).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(i){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%"},n)},o),r)}));function XE(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 YE(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 ZE(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 eO(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 tO(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 rO({participant:e}){const t=IC(jS).find((t=>t.id===e.id)),{isHovered:r,maximizedParticipant:n,floatingParticipant:i}=qE(),o=(null==n?void 0:n.id)===e.id,a=(null==i?void 0:i.id)===e.id;return r?s.createElement(WE,null,s.createElement(JE,{style:{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"#fff",borderRadius:"6px",padding:"4px"}},s.createElement(XE,{height:20,width:20,transform:"rotate(90)"})),s.createElement(KE,null,e.isLocalClient?s.createElement(QE,{participantAction:"float",style:{display:"flex",alignItems:"center",gap:"10px"}},a?s.createElement(s.Fragment,null,s.createElement(tO,{height:16,width:16}),"Move to grid"):s.createElement(s.Fragment,null,s.createElement(eO,{height:16,width:16}),"Pop out")):null,s.createElement(QE,{participantAction:"maximize",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(YE,{height:16,width:16}),o?"Minimize":"Maximize"),s.createElement(QE,{participantAction:"spotlight",style:{display:"flex",alignItems:"center",gap:"10px"}},s.createElement(ZE,{height:16,width:16}),t?"Remove spotlight":"Spotlight"))):null}QE.displayName="ParticipantMenuItem";const nO=s.forwardRef((({className:e,participant:t,children:r},n)=>{const[i,o]=s.useState(!1),a=s.useCallback((()=>{o(!0)}),[]),c=s.useCallback((()=>{o(!1)}),[]);return s.createElement(GE.Provider,{value:{participant:t,isHovered:i}},s.createElement("div",{ref:n,className:e,onMouseEnter:a,onMouseLeave:c,style:{height:"100%",width:"100%"}},r))}));nO.displayName="GridCell";const iO=s.forwardRef(((e,t)=>{var{stream:r,style:n}=e,i=EC(e,["stream","style"]);const o=s.useRef(null),{onSetClientAspectRatio:a,clientAspectRatios:c,participant:d,isConstrained:l}=qE();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?s.createElement(DC,Object.assign({ref:o,style:Object.assign(Object.assign({borderRadius:l?0:"8px"},l?{objectFit:"cover"}:{}),n),muted:d.isLocalClient},i,{stream:h,onVideoResize:p})):s.createElement(rT,{isSmallCell:!1,displayName:(null==d?void 0:d.displayName)||"Guest",withRoundedCorners:!0})}));function sO({cellView:e,enableParticipantMenu:t,render:r}){const n=null==e?void 0:e.client;if(n)return"video"===e.type?s.createElement(nO,{participant:n},n.isVideoEnabled?s.createElement(s.Fragment,null,r?r({participant:n}):s.createElement(s.Fragment,null,s.createElement(iO,null),t?s.createElement(rO,{participant:n}):null)):s.createElement(rT,{isSmallCell:!1,displayName:(null==n?void 0:n.displayName)||"Guest",withRoundedCorners:!0})):void 0}return iO.displayName="GridVideoView",e.GridCell=nO,e.GridVideoView=iO,e.ParticipantMenu=WE,e.ParticipantMenuContent=KE,e.ParticipantMenuItem=QE,e.ParticipantMenuTrigger=JE,e.VideoGrid=function({renderParticipant:e,renderFloatingParticipant:t,stageParticipantLimit:r,gridGap:n,videoGridGap:i,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}=function({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r=kR,gridGap:n=8,videoGridGap:i=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:_}=OR({activeVideosSubgridTrigger:e,forceSubgrid:t,stageParticipantLimit:r,enableSubgrid:o,maximizedParticipant:f,floatingParticipant:g,isConstrained:!!a&&!!l}),S=s.useMemo((()=>_?[TR({client:_,aspectRatio:p[_.id],avatarSize:0,cellPaddings:{top:0,right:0}})]:[]),[_,p]),C=s.useMemo((()=>b.map((e=>TR({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[b,p]),R=s.useMemo((()=>y.map((e=>TR({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0}})))),[y,p]),T=s.useMemo((()=>w.map((e=>TR({client:e,aspectRatio:p[e.id],avatarSize:0,cellPaddings:{top:0,right:0},isSubgrid:!0})))),[w,p]),k=s.useMemo((()=>BC(c)),[c]);s.useEffect((()=>{a&&u(c.width<500||c.height<500)}),[c,a]);const P=s.useMemo((()=>RR({floatingVideo:S[0],frame:k,gridGap:n,isConstrained:l,roomBounds:k.bounds,videos:C,videoGridGap:i,presentationVideos:R,subgridVideos:T})),[k,S,C,R,T,n,i]);return{containerFrame:k,cellViewsFloating:S,cellViewsVideoGrid:C,cellViewsInPresentationGrid:R,cellViewsInSubgrid:T,clientAspectRatios:p,videoStage:P,setContainerBounds:d,setClientAspectRatios:h,maximizedParticipant:f,setMaximizedParticipant:m,floatingParticipant:g,setFloatingParticipant:v,isConstrained:l}}({activeVideosSubgridTrigger:12,stageParticipantLimit:r,gridGap:n,videoGridGap:i,enableSubgrid:o,enableConstrainedGrid:c}),R=s.useCallback((({aspectRatio:e,clientId:t})=>{b((r=>Object.assign(Object.assign({},r),{[t]:e})))}),[b]),T=s.useMemo((()=>sO(Object.assign({cellView:u[0],enableParticipantMenu:a},t?{render:({participant:e})=>t({participant:e})}:{}))),[u]),k=s.useMemo((()=>h.map((t=>sO(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[h]),P=s.useMemo((()=>p.map((t=>sO(Object.assign({cellView:t,enableParticipantMenu:a},e?{render:({participant:t})=>e({participant:t})}:{}))))),[p]),E=s.useMemo((()=>f.map((e=>sO({cellView:e,enableParticipantMenu:a})))),[f]);return s.useEffect((()=>{if(!d.current)return;const e=new ResizeObserver(ow((()=>{var e,t,r,n;v({width:null!==(t=null===(e=d.current)||void 0===e?void 0:e.clientWidth)&&void 0!==t?t:640,height:null!==(n=null===(r=d.current)||void 0===r?void 0:r.clientHeight)&&void 0!==n?n:480})}),{delay:60,edges:!1}));return e.observe(d.current),()=>{e.disconnect()}}),[]),s.createElement($E.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(WC,{containerFrame:l,floatingContent:T,layoutVideoStage:g,presentationGridContent:k,gridContent:P,subgridContent:E})))},e.VideoView=DC,e.WherebyProvider=function({children:e}){const t=(({preloadedState:e,injectServices:t})=>gt({devTools:FS,reducer:VS,middleware:e=>e({thunk:{extraArgument:{services:t}},serializableCheck:!1}).prepend(iy.middleware),preloadedState:e}))({injectServices:function(){const e=mC.create({baseUrl:CC}),t=new nC({fetchDeviceCredentials:e.getCredentials.bind(e),baseUrl:CC}),r=new _C({apiClient:t});return{credentialsService:e,apiClient:t,organizationService:r,fetchOrganizationFromRoomUrl:e=>{const t=Fg({host:new URL(e).host});return new SC({organizationService:r,subdomain:t.subdomain}).fetchOrganization()}}}()});return s.createElement(k,{context:RC,store:t},e)},e.useLocalMedia=function(e={audio:!0,video:!0}){const t=OC(),r=IC(jC);return s.useEffect((()=>(t(Tw(e)),()=>{t(kw())})),[]),{state:r,actions:{setCameraDevice:s.useCallback((e=>t(dw({deviceId:e}))),[t]),setMicrophoneDevice:s.useCallback((e=>t(lw({deviceId:e}))),[t]),setSpeakerDevice:s.useCallback((e=>t(uw({deviceId:e}))),[t]),toggleCameraEnabled:s.useCallback((e=>t(pw({enabled:e}))),[t]),toggleMicrophoneEnabled:s.useCallback((e=>t(hw({enabled:e}))),[t]),toggleLowDataModeEnabled:s.useCallback((e=>t(fw({enabled:e}))),[t])}}},e.useRoomConnection=function(e,t=MC){const r=OC(),n=IC(xC),i=s.useMemo((()=>{const r=new URL(e),n=new URLSearchParams(r.search),i=t.roomKey||n.get("roomKey");return{displayName:t.displayName||"Guest",localMediaOptions:t.localMedia?void 0:t.localMediaOptions,roomKey:i,roomUrl:e,userAgent:"browser-sdk:3.10.6",externalId:t.externalId||null}}),[e,t]);s.useEffect((()=>()=>{r(cy())}),[]);const o=s.useCallback((e=>r(Xy({text:e}))),[r]),a=s.useCallback((()=>r(o_())),[r]),c=s.useCallback((e=>r(Kw({displayName:e}))),[r]),d=s.useCallback((e=>r(pw({enabled:e}))),[r]),l=s.useCallback((e=>r(hw({enabled:e}))),[r]),u=s.useCallback((e=>r(fw({enabled:e}))),[r]),p=s.useCallback((e=>r(Xw({enabled:e}))),[r]),h=s.useCallback((e=>r(w_({clientIds:[e],enable:!0}))),[r]),f=s.useCallback((e=>r(__({clientIds:[e],enable:!0}))),[r]),m=s.useCallback((e=>r(NS({participantId:e}))),[r]),g=s.useCallback((e=>r(BS({participantId:e}))),[r]),v=s.useCallback((()=>r(ew())),[r]),b=s.useCallback((()=>r(P_())),[r]),y=s.useCallback((()=>r(tw())),[r]),w=s.useCallback((()=>r(E_())),[r]),_=s.useCallback((()=>r(dy(i))),[r]),S=s.useCallback((()=>r(cy())),[r]),C=s.useCallback((e=>r(eS({locked:e}))),[r]),R=s.useCallback((e=>r(w_({clientIds:e,enable:!1}))),[r]),T=s.useCallback((e=>r(__({clientIds:e,enable:!1}))),[r]),k=s.useCallback((e=>r(DS({id:e}))),[r]),P=s.useCallback((e=>r(xS({id:e}))),[r]),E=s.useCallback((e=>r(tS({clientId:e}))),[r]),O=s.useCallback((e=>r(rS({stayBehind:e}))),[r]),{events:I}=n;return{state:EC(n,["events"]),events:I,actions:{toggleLowDataMode:u,toggleRaiseHand:p,askToSpeak:h,askToTurnOnCamera:f,acceptWaitingParticipant:m,knock:a,joinRoom:_,leaveRoom:S,lockRoom:C,muteParticipants:R,turnOffParticipantCameras:T,kickParticipant:E,endMeeting:O,rejectWaitingParticipant:g,sendChatMessage:o,setDisplayName:c,startCloudRecording:v,startScreenshare:b,stopCloudRecording:y,stopScreenshare:w,toggleCamera:d,toggleMicrophone:l,spotlightParticipant:k,removeSpotlight:P}}},e}({},React,ReactDOM);
|