obi-sdk 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assertIs=function(e){},i.assertNever=function(e){throw new Error},i.arrayToEnum=e=>{const t={};for(const i of e)t[i]=i;return t},i.getValidEnumValues=e=>{const t=i.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),n={};for(const i of t)n[i]=e[i];return i.objectValues(n)},i.objectValues=e=>i.objectKeys(e).map((function(t){return e[t]})),i.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.push(i);return t},i.find=(e,t)=>{for(const i of e)if(t(i))return i},i.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,i.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},i.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(n||(n={})).mergeShapes=(e,t)=>({...e,...t});const s=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),r=e=>{switch(typeof e){case"undefined":return s.undefined;case"string":return s.string;case"number":return isNaN(e)?s.nan:s.number;case"boolean":return s.boolean;case"function":return s.function;case"bigint":return s.bigint;case"symbol":return s.symbol;case"object":return Array.isArray(e)?s.array:null===e?s.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?s.promise:"undefined"!=typeof Map&&e instanceof Map?s.map:"undefined"!=typeof Set&&e instanceof Set?s.set:"undefined"!=typeof Date&&e instanceof Date?s.date:s.object;default:return s.unknown}},o=t.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class a extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},i={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)i._errors.push(t(s));else{let e=i,n=0;for(;n<s.path.length;){const i=s.path[n];n===s.path.length-1?(e[i]=e[i]||{_errors:[]},e[i]._errors.push(t(s))):e[i]=e[i]||{_errors:[]},e=e[i],n++}}};return n(this),i}static assert(e){if(!(e instanceof a))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},i=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}a.create=e=>new a(e);const c=(e,i)=>{let n;switch(e.code){case o.invalid_type:n=e.received===s.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case o.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:n=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case o.invalid_union:n="Invalid input";break;case o.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case o.invalid_enum_value:n=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case o.invalid_arguments:n="Invalid function arguments";break;case o.invalid_return_type:n="Invalid function return type";break;case o.invalid_date:n="Invalid date";break;case o.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case o.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case o.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case o.custom:n="Invalid input";break;case o.invalid_intersection_types:n="Intersection results could not be merged";break;case o.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case o.not_finite:n="Number must be finite";break;default:n=i.defaultError,t.assertNever(e)}return{message:n}};let d=c;function l(){return d}const u=e=>{const{data:t,path:i,errorMaps:n,issueData:s}=e,r=[...i,...s.path||[]],o={...s,path:r};if(void 0!==s.message)return{...s,path:r,message:s.message};let a="";const c=n.filter((e=>!!e)).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...s,path:r,message:a}};function h(e,t){const i=l(),n=u({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,i,i===c?void 0:c].filter((e=>!!e))});e.common.issues.push(n)}class p{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const n of t){if("aborted"===n.status)return m;"dirty"===n.status&&e.dirty(),i.push(n.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const n of t){const e=await n.key,t=await n.value;i.push({key:e,value:t})}return p.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return m;if("aborted"===s.status)return m;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(i[t.value]=s.value)}return{status:e.value,value:i}}}const m=Object.freeze({status:"aborted"}),g=e=>({status:"dirty",value:e}),f=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,y=e=>"dirty"===e.status,b=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;function T(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)}function S(e,t,i,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,i):s?s.value=i:t.set(e,i),i}var C,w,E,_;"function"==typeof SuppressedError&&SuppressedError,(w=C||(C={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},w.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class P{constructor(e,t,i,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const R=(e,t)=>{if(b(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new a(e.common.issues);return this._error=t,this._error}}};function x(e){if(!e)return{};const{errorMap:t,invalid_type_error:i,required_error:n,description:s}=e;if(t&&(i||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{var r,o;const{message:a}=e;return"invalid_enum_value"===t.code?{message:null!=a?a:s.defaultError}:void 0===s.data?{message:null!==(r=null!=a?a:n)&&void 0!==r?r:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(o=null!=a?a:i)&&void 0!==o?o:s.defaultError}},description:s}}class O{get description(){return this._def.description}_getType(e){return r(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new p,ctx:{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const n={common:{issues:[],async:null!==(i=null==t?void 0:t.async)&&void 0!==i&&i,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},s=this._parseSync({data:e,path:n.path,parent:n});return R(n,s)}"~validate"(e){var t,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return b(t)?{value:t.value}:{issues:n.common.issues}}catch(s){(null===(i=null===(t=null==s?void 0:s.message)||void 0===t?void 0:t.toLowerCase())||void 0===i?void 0:i.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>b(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},n=this._parse({data:e,path:i.path,parent:i}),s=await(k(n)?n:Promise.resolve(n));return R(i,s)}refine(e,t){const i=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const s=e(t),r=()=>n.addIssue({code:o.custom,...i(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(r(),!1))):!!s||(r(),!1)}))}refinement(e,t){return this._refinement(((i,n)=>!!e(i)||(n.addIssue("function"==typeof t?t(i,n):t),!1)))}_refinement(e){return new Oe({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ie.create(this,this._def)}nullable(){return Ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ue.create(this)}promise(){return xe.create(this,this._def)}or(e){return me.create([this,e],this._def)}and(e){return ye.create(this,e,this._def)}transform(e){return new Oe({...x(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ne({...x(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new Ue({typeName:qe.ZodBranded,type:this,...x(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new De({...x(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return je.create(this,e)}readonly(){return Fe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I=/^c[^\s-]{8,}$/i,A=/^[0-9a-z]+$/,N=/^[0-9A-HJKMNP-TV-Z]{26}$/i,D=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,M=/^[a-z0-9_-]{21}$/i,L=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,U=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,j=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let F;const $=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,V=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,q=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,z=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Z=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,H="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",K=new RegExp(`^${H}$`);function G(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function W(e){let t=`${H}T${G(e)}`;const i=[];return i.push(e.local?"Z?":"Z"),e.offset&&i.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function J(e,t){if(!L.test(e))return!1;try{const[i]=e.split("."),n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||!s.typ||!s.alg||t&&s.alg!==t)}catch(i){return!1}}function Y(e,t){return!("v4"!==t&&t||!B.test(e))||!("v6"!==t&&t||!q.test(e))}class Q extends O{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==s.string){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.string,received:t.parsedType}),m}const i=new p;let n;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if("max"===s.kind)e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if("length"===s.kind){const t=e.data.length>s.value,r=e.data.length<s.value;(t||r)&&(n=this._getOrReturnCtx(e,n),t?h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):r&&h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),i.dirty())}else if("email"===s.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"email",code:o.invalid_string,message:s.message}),i.dirty());else if("emoji"===s.kind)F||(F=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),F.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"emoji",code:o.invalid_string,message:s.message}),i.dirty());else if("uuid"===s.kind)D.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"uuid",code:o.invalid_string,message:s.message}),i.dirty());else if("nanoid"===s.kind)M.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"nanoid",code:o.invalid_string,message:s.message}),i.dirty());else if("cuid"===s.kind)I.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"cuid",code:o.invalid_string,message:s.message}),i.dirty());else if("cuid2"===s.kind)A.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"cuid2",code:o.invalid_string,message:s.message}),i.dirty());else if("ulid"===s.kind)N.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"ulid",code:o.invalid_string,message:s.message}),i.dirty());else if("url"===s.kind)try{new URL(e.data)}catch(c){n=this._getOrReturnCtx(e,n),h(n,{validation:"url",code:o.invalid_string,message:s.message}),i.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"regex",code:o.invalid_string,message:s.message}),i.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()):"datetime"===s.kind?W(s).test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:"datetime",message:s.message}),i.dirty()):"date"===s.kind?K.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:"date",message:s.message}),i.dirty()):"time"===s.kind?new RegExp(`^${G(s)}$`).test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:"time",message:s.message}),i.dirty()):"duration"===s.kind?U.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"duration",code:o.invalid_string,message:s.message}),i.dirty()):"ip"===s.kind?(r=e.data,("v4"!==(a=s.version)&&a||!$.test(r))&&("v6"!==a&&a||!V.test(r))&&(n=this._getOrReturnCtx(e,n),h(n,{validation:"ip",code:o.invalid_string,message:s.message}),i.dirty())):"jwt"===s.kind?J(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"jwt",code:o.invalid_string,message:s.message}),i.dirty()):"cidr"===s.kind?Y(e.data,s.version)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"cidr",code:o.invalid_string,message:s.message}),i.dirty()):"base64"===s.kind?z.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"base64",code:o.invalid_string,message:s.message}),i.dirty()):"base64url"===s.kind?Z.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"base64url",code:o.invalid_string,message:s.message}),i.dirty()):t.assertNever(s);var r,a;return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement((t=>e.test(t)),{validation:t,code:o.invalid_string,...C.errToObj(i)})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){var t,i;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(i=null==e?void 0:e.local)&&void 0!==i&&i,...C.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...C.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...C.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...C.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...C.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...C.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...C.errToObj(t)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new Q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Q({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function X(e,t){const i=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=i>n?i:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}Q.create=e=>{var t;return new Q({checks:[],typeName:qe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class ee extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==s.number){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.number,received:t.parsedType}),m}let i;const n=new p;for(const s of this._def.checks)"int"===s.kind?t.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:o.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"multipleOf"===s.kind?0!==X(e.data,s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:o.not_finite,message:s.message}),n.dirty()):t.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,n){return new ee({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(n)}]})}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;"min"===i.kind?(null===t||i.value>t)&&(t=i.value):"max"===i.kind&&(null===e||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ee.create=e=>new ee({checks:[],typeName:qe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class te extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(r){return this._getInvalidInput(e)}if(this._getType(e)!==s.bigint)return this._getInvalidInput(e);let i;const n=new p;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):t.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,n){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(n)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}te.create=e=>{var t;return new te({checks:[],typeName:qe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class ie extends O{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==s.boolean){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.boolean,received:t.parsedType}),m}return f(e.data)}}ie.create=e=>new ie({typeName:qe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class ne extends O{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==s.date){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.date,received:t.parsedType}),m}if(isNaN(e.data.getTime()))return h(this._getOrReturnCtx(e),{code:o.invalid_date}),m;const i=new p;let n;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()):t.assertNever(s);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ne({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ne.create=e=>new ne({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:qe.ZodDate,...x(e)});class se extends O{_parse(e){if(this._getType(e)!==s.symbol){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.symbol,received:t.parsedType}),m}return f(e.data)}}se.create=e=>new se({typeName:qe.ZodSymbol,...x(e)});class re extends O{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.undefined,received:t.parsedType}),m}return f(e.data)}}re.create=e=>new re({typeName:qe.ZodUndefined,...x(e)});class oe extends O{_parse(e){if(this._getType(e)!==s.null){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.null,received:t.parsedType}),m}return f(e.data)}}oe.create=e=>new oe({typeName:qe.ZodNull,...x(e)});class ae extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return f(e.data)}}ae.create=e=>new ae({typeName:qe.ZodAny,...x(e)});class ce extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return f(e.data)}}ce.create=e=>new ce({typeName:qe.ZodUnknown,...x(e)});class de extends O{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.never,received:t.parsedType}),m}}de.create=e=>new de({typeName:qe.ZodNever,...x(e)});class le extends O{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.void,received:t.parsedType}),m}return f(e.data)}}le.create=e=>new le({typeName:qe.ZodVoid,...x(e)});class ue extends O{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),n=this._def;if(t.parsedType!==s.array)return h(t,{code:o.invalid_type,expected:s.array,received:t.parsedType}),m;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(h(t,{code:e?o.too_big:o.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(h(t,{code:o.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(h(t,{code:o.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map(((e,i)=>n.type._parseAsync(new P(t,e,t.path,i))))).then((e=>p.mergeArray(i,e)));const r=[...t.data].map(((e,i)=>n.type._parseSync(new P(t,e,t.path,i))));return p.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new ue({...this._def,minLength:{value:e,message:C.toString(t)}})}max(e,t){return new ue({...this._def,maxLength:{value:e,message:C.toString(t)}})}length(e,t){return new ue({...this._def,exactLength:{value:e,message:C.toString(t)}})}nonempty(e){return this.min(1,e)}}function he(e){if(e instanceof pe){const t={};for(const i in e.shape){const n=e.shape[i];t[i]=Ie.create(he(n))}return new pe({...e._def,shape:()=>t})}return e instanceof ue?new ue({...e._def,type:he(e.element)}):e instanceof Ie?Ie.create(he(e.unwrap())):e instanceof Ae?Ae.create(he(e.unwrap())):e instanceof be?be.create(e.items.map((e=>he(e)))):e}ue.create=(e,t)=>new ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...x(t)});class pe extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),i=t.objectKeys(e);return this._cached={shape:e,keys:i}}_parse(e){if(this._getType(e)!==s.object){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.object,received:t.parsedType}),m}const{status:t,ctx:i}=this._processInputParams(e),{shape:n,keys:r}=this._getCached(),a=[];if(!(this._def.catchall instanceof de&&"strip"===this._def.unknownKeys))for(const s in i.data)r.includes(s)||a.push(s);const c=[];for(const s of r){const e=n[s],t=i.data[s];c.push({key:{status:"valid",value:s},value:e._parse(new P(i,t,i.path,s)),alwaysSet:s in i.data})}if(this._def.catchall instanceof de){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of a)c.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===e)a.length>0&&(h(i,{code:o.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=i.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new P(i,n,i.path,t)),alwaysSet:t in i.data})}}return i.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of c){const i=await t.key,n=await t.value;e.push({key:i,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>p.mergeObjectSync(t,e))):p.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new pe({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,i)=>{var n,s,r,o;const a=null!==(r=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,i).message)&&void 0!==r?r:i.defaultError;return"unrecognized_keys"===t.code?{message:null!==(o=C.errToObj(e).message)&&void 0!==o?o:a}:{message:a}}}:{}})}strip(){return new pe({...this._def,unknownKeys:"strip"})}passthrough(){return new pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new pe({...this._def,catchall:e})}pick(e){const i={};return t.objectKeys(e).forEach((t=>{e[t]&&this.shape[t]&&(i[t]=this.shape[t])})),new pe({...this._def,shape:()=>i})}omit(e){const i={};return t.objectKeys(this.shape).forEach((t=>{e[t]||(i[t]=this.shape[t])})),new pe({...this._def,shape:()=>i})}deepPartial(){return he(this)}partial(e){const i={};return t.objectKeys(this.shape).forEach((t=>{const n=this.shape[t];e&&!e[t]?i[t]=n:i[t]=n.optional()})),new pe({...this._def,shape:()=>i})}required(e){const i={};return t.objectKeys(this.shape).forEach((t=>{if(e&&!e[t])i[t]=this.shape[t];else{let e=this.shape[t];for(;e instanceof Ie;)e=e._def.innerType;i[t]=e}})),new pe({...this._def,shape:()=>i})}keyof(){return _e(t.objectKeys(this.shape))}}pe.create=(e,t)=>new pe({shape:()=>e,unknownKeys:"strip",catchall:de.create(),typeName:qe.ZodObject,...x(t)}),pe.strictCreate=(e,t)=>new pe({shape:()=>e,unknownKeys:"strict",catchall:de.create(),typeName:qe.ZodObject,...x(t)}),pe.lazycreate=(e,t)=>new pe({shape:e,unknownKeys:"strip",catchall:de.create(),typeName:qe.ZodObject,...x(t)});class me extends O{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;if(t.common.async)return Promise.all(i.map((async e=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const i=e.map((e=>new a(e.ctx.common.issues)));return h(t,{code:o.invalid_union,unionErrors:i}),m}));{let e;const n=[];for(const r of i){const i={...t,common:{...t.common,issues:[]},parent:null},s=r._parseSync({data:t.data,path:t.path,parent:i});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new a(e)));return h(t,{code:o.invalid_union,unionErrors:s}),m}}get options(){return this._def.options}}me.create=(e,t)=>new me({options:e,typeName:qe.ZodUnion,...x(t)});const ge=e=>e instanceof we?ge(e.schema):e instanceof Oe?ge(e.innerType()):e instanceof Ee?[e.value]:e instanceof Pe?e.options:e instanceof Re?t.objectValues(e.enum):e instanceof Ne?ge(e._def.innerType):e instanceof re?[void 0]:e instanceof oe?[null]:e instanceof Ie?[void 0,...ge(e.unwrap())]:e instanceof Ae?[null,...ge(e.unwrap())]:e instanceof Ue||e instanceof Fe?ge(e.unwrap()):e instanceof De?ge(e._def.innerType):[];class fe extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return h(t,{code:o.invalid_type,expected:s.object,received:t.parsedType}),m;const i=this.discriminator,n=t.data[i],r=this.optionsMap.get(n);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const n=new Map;for(const s of t){const t=ge(s.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new fe({typeName:qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...x(i)})}}function ve(e,i){const n=r(e),o=r(i);if(e===i)return{valid:!0,data:e};if(n===s.object&&o===s.object){const n=t.objectKeys(i),s=t.objectKeys(e).filter((e=>-1!==n.indexOf(e))),r={...e,...i};for(const t of s){const n=ve(e[t],i[t]);if(!n.valid)return{valid:!1};r[t]=n.data}return{valid:!0,data:r}}if(n===s.array&&o===s.array){if(e.length!==i.length)return{valid:!1};const t=[];for(let n=0;n<e.length;n++){const s=ve(e[n],i[n]);if(!s.valid)return{valid:!1};t.push(s.data)}return{valid:!0,data:t}}return n===s.date&&o===s.date&&+e==+i?{valid:!0,data:e}:{valid:!1}}class ye extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return m;const s=ve(e.value,n.value);return s.valid?((y(e)||y(n))&&t.dirty(),{status:t.value,value:s.data}):(h(i,{code:o.invalid_intersection_types}),m)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ye.create=(e,t,i)=>new ye({left:e,right:t,typeName:qe.ZodIntersection,...x(i)});class be extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.array)return h(i,{code:o.invalid_type,expected:s.array,received:i.parsedType}),m;if(i.data.length<this._def.items.length)return h(i,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&i.data.length>this._def.items.length&&(h(i,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...i.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new P(i,e,i.path,t)):null})).filter((e=>!!e));return i.common.async?Promise.all(n).then((e=>p.mergeArray(t,e))):p.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new be({...this._def,rest:e})}}be.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new be({items:e,typeName:qe.ZodTuple,rest:null,...x(t)})};class ke extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.object)return h(i,{code:o.invalid_type,expected:s.object,received:i.parsedType}),m;const n=[],r=this._def.keyType,a=this._def.valueType;for(const s in i.data)n.push({key:r._parse(new P(i,s,i.path,s)),value:a._parse(new P(i,i.data[s],i.path,s)),alwaysSet:s in i.data});return i.common.async?p.mergeObjectAsync(t,n):p.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,i){return new ke(t instanceof O?{keyType:e,valueType:t,typeName:qe.ZodRecord,...x(i)}:{keyType:Q.create(),valueType:e,typeName:qe.ZodRecord,...x(t)})}}class Te extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.map)return h(i,{code:o.invalid_type,expected:s.map,received:i.parsedType}),m;const n=this._def.keyType,r=this._def.valueType,a=[...i.data.entries()].map((([e,t],s)=>({key:n._parse(new P(i,e,i.path,[s,"key"])),value:r._parse(new P(i,t,i.path,[s,"value"]))})));if(i.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const i of a){const n=await i.key,s=await i.value;if("aborted"===n.status||"aborted"===s.status)return m;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const i of a){const n=i.key,s=i.value;if("aborted"===n.status||"aborted"===s.status)return m;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}Te.create=(e,t,i)=>new Te({valueType:t,keyType:e,typeName:qe.ZodMap,...x(i)});class Se extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.set)return h(i,{code:o.invalid_type,expected:s.set,received:i.parsedType}),m;const n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(h(i,{code:o.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(h(i,{code:o.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const r=this._def.valueType;function a(e){const i=new Set;for(const n of e){if("aborted"===n.status)return m;"dirty"===n.status&&t.dirty(),i.add(n.value)}return{status:t.value,value:i}}const c=[...i.data.values()].map(((e,t)=>r._parse(new P(i,e,i.path,t))));return i.common.async?Promise.all(c).then((e=>a(e))):a(c)}min(e,t){return new Se({...this._def,minSize:{value:e,message:C.toString(t)}})}max(e,t){return new Se({...this._def,maxSize:{value:e,message:C.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Se.create=(e,t)=>new Se({valueType:e,minSize:null,maxSize:null,typeName:qe.ZodSet,...x(t)});class Ce extends O{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.function)return h(t,{code:o.invalid_type,expected:s.function,received:t.parsedType}),m;function i(e,i){return u({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l(),c].filter((e=>!!e)),issueData:{code:o.invalid_arguments,argumentsError:i}})}function n(e,i){return u({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l(),c].filter((e=>!!e)),issueData:{code:o.invalid_return_type,returnTypeError:i}})}const r={errorMap:t.common.contextualErrorMap},d=t.data;if(this._def.returns instanceof xe){const e=this;return f((async function(...t){const s=new a([]),o=await e._def.args.parseAsync(t,r).catch((e=>{throw s.addIssue(i(t,e)),s})),c=await Reflect.apply(d,this,o);return await e._def.returns._def.type.parseAsync(c,r).catch((e=>{throw s.addIssue(n(c,e)),s}))}))}{const e=this;return f((function(...t){const s=e._def.args.safeParse(t,r);if(!s.success)throw new a([i(t,s.error)]);const o=Reflect.apply(d,this,s.data),c=e._def.returns.safeParse(o,r);if(!c.success)throw new a([n(o,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ce({...this._def,args:be.create(e).rest(ce.create())})}returns(e){return new Ce({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new Ce({args:e||be.create([]).rest(ce.create()),returns:t||ce.create(),typeName:qe.ZodFunction,...x(i)})}}class we extends O{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}we.create=(e,t)=>new we({getter:e,typeName:qe.ZodLazy,...x(t)});class Ee extends O{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}}function _e(e,t){return new Pe({values:e,typeName:qe.ZodEnum,...x(t)})}Ee.create=(e,t)=>new Ee({value:e,typeName:qe.ZodLiteral,...x(t)});class Pe extends O{constructor(){super(...arguments),E.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const i=this._getOrReturnCtx(e),n=this._def.values;return h(i,{expected:t.joinValues(n),received:i.parsedType,code:o.invalid_type}),m}if(T(this,E,"f")||S(this,E,new Set(this._def.values),"f"),!T(this,E,"f").has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return h(t,{received:t.data,code:o.invalid_enum_value,options:i}),m}return f(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Pe.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}E=new WeakMap,Pe.create=_e;class Re extends O{constructor(){super(...arguments),_.set(this,void 0)}_parse(e){const i=t.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==s.string&&n.parsedType!==s.number){const e=t.objectValues(i);return h(n,{expected:t.joinValues(e),received:n.parsedType,code:o.invalid_type}),m}if(T(this,_,"f")||S(this,_,new Set(t.getValidEnumValues(this._def.values)),"f"),!T(this,_,"f").has(e.data)){const e=t.objectValues(i);return h(n,{received:n.data,code:o.invalid_enum_value,options:e}),m}return f(e.data)}get enum(){return this._def.values}}_=new WeakMap,Re.create=(e,t)=>new Re({values:e,typeName:qe.ZodNativeEnum,...x(t)});class xe extends O{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.promise&&!1===t.common.async)return h(t,{code:o.invalid_type,expected:s.promise,received:t.parsedType}),m;const i=t.parsedType===s.promise?t.data:Promise.resolve(t.data);return f(i.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}xe.create=(e,t)=>new xe({type:e,typeName:qe.ZodPromise,...x(t)});class Oe extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:i,ctx:n}=this._processInputParams(e),s=this._def.effect||null,r={addIssue:e=>{h(n,e),e.fatal?i.abort():i.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),"preprocess"===s.type){const e=s.transform(n.data,r);if(n.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===i.value)return m;const t=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===t.status?m:"dirty"===t.status||"dirty"===i.value?g(t.value):t}));{if("aborted"===i.value)return m;const t=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===t.status?m:"dirty"===t.status||"dirty"===i.value?g(t.value):t}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,r);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const t=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===t.status?m:("dirty"===t.status&&i.dirty(),e(t.value),{status:i.value,value:t.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((t=>"aborted"===t.status?m:("dirty"===t.status&&i.dirty(),e(t.value).then((()=>({status:i.value,value:t.value}))))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!b(e))return e;const t=s.transform(e.value,r);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:t}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((e=>b(e)?Promise.resolve(s.transform(e.value,r)).then((e=>({status:i.value,value:e}))):e))}t.assertNever(s)}}Oe.create=(e,t,i)=>new Oe({schema:e,typeName:qe.ZodEffects,effect:t,...x(i)}),Oe.createWithPreprocess=(e,t,i)=>new Oe({schema:t,effect:{type:"preprocess",transform:e},typeName:qe.ZodEffects,...x(i)});class Ie extends O{_parse(e){return this._getType(e)===s.undefined?f(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:qe.ZodOptional,...x(t)});class Ae extends O{_parse(e){return this._getType(e)===s.null?f(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:qe.ZodNullable,...x(t)});class Ne extends O{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===s.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:qe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...x(t)});class De extends O{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return k(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new a(i.common.issues)},input:i.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new a(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:qe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...x(t)});class Me extends O{_parse(e){if(this._getType(e)!==s.nan){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.nan,received:t.parsedType}),m}return{status:"valid",value:e.data}}}Me.create=e=>new Me({typeName:qe.ZodNaN,...x(e)});const Le=Symbol("zod_brand");class Ue extends O{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class je extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?m:"dirty"===e.status?(t.dirty(),g(e.value)):this._def.out._parseAsync({data:e.value,path:i.path,parent:i})})();{const e=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?m:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:i.path,parent:i})}}static create(e,t){return new je({in:e,out:t,typeName:qe.ZodPipeline})}}class Fe extends O{_parse(e){const t=this._def.innerType._parse(e),i=e=>(b(e)&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then((e=>i(e))):i(t)}unwrap(){return this._def.innerType}}function $e(e,t){const i="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof i?{message:i}:i}function Be(e,t={},i){return e?ae.create().superRefine(((n,s)=>{var r,o;const a=e(n);if(a instanceof Promise)return a.then((e=>{var r,o;if(!e){const e=$e(t,n),a=null===(o=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===o||o;s.addIssue({code:"custom",...e,fatal:a})}}));if(!a){const e=$e(t,n),a=null===(o=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===o||o;s.addIssue({code:"custom",...e,fatal:a})}})):ae.create()}Fe.create=(e,t)=>new Fe({innerType:e,typeName:qe.ZodReadonly,...x(t)});const Ve={object:pe.lazycreate};var qe,ze;(ze=qe||(qe={})).ZodString="ZodString",ze.ZodNumber="ZodNumber",ze.ZodNaN="ZodNaN",ze.ZodBigInt="ZodBigInt",ze.ZodBoolean="ZodBoolean",ze.ZodDate="ZodDate",ze.ZodSymbol="ZodSymbol",ze.ZodUndefined="ZodUndefined",ze.ZodNull="ZodNull",ze.ZodAny="ZodAny",ze.ZodUnknown="ZodUnknown",ze.ZodNever="ZodNever",ze.ZodVoid="ZodVoid",ze.ZodArray="ZodArray",ze.ZodObject="ZodObject",ze.ZodUnion="ZodUnion",ze.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ze.ZodIntersection="ZodIntersection",ze.ZodTuple="ZodTuple",ze.ZodRecord="ZodRecord",ze.ZodMap="ZodMap",ze.ZodSet="ZodSet",ze.ZodFunction="ZodFunction",ze.ZodLazy="ZodLazy",ze.ZodLiteral="ZodLiteral",ze.ZodEnum="ZodEnum",ze.ZodEffects="ZodEffects",ze.ZodNativeEnum="ZodNativeEnum",ze.ZodOptional="ZodOptional",ze.ZodNullable="ZodNullable",ze.ZodDefault="ZodDefault",ze.ZodCatch="ZodCatch",ze.ZodPromise="ZodPromise",ze.ZodBranded="ZodBranded",ze.ZodPipeline="ZodPipeline",ze.ZodReadonly="ZodReadonly";const Ze=Q.create,He=ee.create,Ke=Me.create,Ge=te.create,We=ie.create,Je=ne.create,Ye=se.create,Qe=re.create,Xe=oe.create,et=ae.create,tt=ce.create,it=de.create,nt=le.create,st=ue.create,rt=pe.create,ot=pe.strictCreate,at=me.create,ct=fe.create,dt=ye.create,lt=be.create,ut=ke.create,ht=Te.create,pt=Se.create,mt=Ce.create,gt=we.create,ft=Ee.create,vt=Pe.create,yt=Re.create,bt=xe.create,kt=Oe.create,Tt=Ie.create,St=Ae.create,Ct=Oe.createWithPreprocess,wt=je.create,Et={string:e=>Q.create({...e,coerce:!0}),number:e=>ee.create({...e,coerce:!0}),boolean:e=>ie.create({...e,coerce:!0}),bigint:e=>te.create({...e,coerce:!0}),date:e=>ne.create({...e,coerce:!0})},_t=m;var Pt=Object.freeze({__proto__:null,defaultErrorMap:c,setErrorMap:function(e){d=e},getErrorMap:l,makeIssue:u,EMPTY_PATH:[],addIssueToContext:h,ParseStatus:p,INVALID:m,DIRTY:g,OK:f,isAborted:v,isDirty:y,isValid:b,isAsync:k,get util(){return t},get objectUtil(){return n},ZodParsedType:s,getParsedType:r,ZodType:O,datetimeRegex:W,ZodString:Q,ZodNumber:ee,ZodBigInt:te,ZodBoolean:ie,ZodDate:ne,ZodSymbol:se,ZodUndefined:re,ZodNull:oe,ZodAny:ae,ZodUnknown:ce,ZodNever:de,ZodVoid:le,ZodArray:ue,ZodObject:pe,ZodUnion:me,ZodDiscriminatedUnion:fe,ZodIntersection:ye,ZodTuple:be,ZodRecord:ke,ZodMap:Te,ZodSet:Se,ZodFunction:Ce,ZodLazy:we,ZodLiteral:Ee,ZodEnum:Pe,ZodNativeEnum:Re,ZodPromise:xe,ZodEffects:Oe,ZodTransformer:Oe,ZodOptional:Ie,ZodNullable:Ae,ZodDefault:Ne,ZodCatch:De,ZodNaN:Me,BRAND:Le,ZodBranded:Ue,ZodPipeline:je,ZodReadonly:Fe,custom:Be,Schema:O,ZodSchema:O,late:Ve,get ZodFirstPartyTypeKind(){return qe},coerce:Et,any:et,array:st,bigint:Ge,boolean:We,date:Je,discriminatedUnion:ct,effect:kt,enum:vt,function:mt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Be((t=>t instanceof e),t),intersection:dt,lazy:gt,literal:ft,map:ht,nan:Ke,nativeEnum:yt,never:it,null:Xe,nullable:St,number:He,object:rt,oboolean:()=>We().optional(),onumber:()=>He().optional(),optional:Tt,ostring:()=>Ze().optional(),pipeline:wt,preprocess:Ct,promise:bt,record:ut,set:pt,strictObject:ot,string:Ze,symbol:Ye,transformer:kt,tuple:lt,undefined:Qe,union:at,unknown:tt,void:nt,NEVER:_t,ZodIssueCode:o,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:a});const Rt=Pt.object({apiKey:Pt.string().optional(),baseUrl:Pt.string().default("https://iamobi.ai/api"),enableVoice:Pt.boolean().default(!0),enableScreenCapture:Pt.boolean().default(!0),debug:Pt.boolean().default(!1)});var xt=(e=>(e.READY="ready",e.ERROR="error",e.VOICE_START="voice:start",e.VOICE_STOP="voice:stop",e.SCREEN_CAPTURE_START="screen:start",e.SCREEN_CAPTURE_STOP="screen:stop",e.STATE_CHANGE="state:change",e))(xt||{}),Ot=(e=>(e.READY="ready",e.ERROR="error",e.PAUSED="paused",e.LOADING="loading",e.THINKING="thinking",e.RESEARCHING="researching",e.AGENT_SPEAKING="agent_speaking",e.USER_SPEAKING="user_speaking",e.AWAITING_USER_INPUT="awaiting_user_input",e))(Ot||{});function It(e){return{all:e=e||new Map,on:function(t,i){var n=e.get(t);n?n.push(i):e.set(t,[i])},off:function(t,i){var n=e.get(t);n&&(i?n.splice(n.indexOf(i)>>>0,1):e.set(t,[]))},emit:function(t,i){var n=e.get(t);n&&n.slice().map((function(e){e(i)})),(n=e.get("*"))&&n.slice().map((function(e){e(t,i)}))}}}class At{constructor(e={}){this.state=Ot.READY,this.emitter=It(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=Rt.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState(Ot.READY),this.emitter.emit(xt.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(xt.STATE_CHANGE,e)}handleError(e){this.setState(Ot.ERROR),this.emitter.emit(xt.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(this.voiceEnabled)try{this.setState(Ot.AGENT_SPEAKING),this.emitter.emit(xt.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}else this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"})}async stopVoiceRecording(){if(this.state===Ot.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState(Ot.READY),this.emitter.emit(xt.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(this.screenCaptureEnabled)try{this.setState(Ot.AGENT_SPEAKING),this.emitter.emit(xt.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}else this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"})}async stopScreenCapture(){if(this.state===Ot.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState(Ot.READY),this.emitter.emit(xt.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}}function Nt(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var Dt=Object.defineProperty,Mt=(e,t,i)=>((e,t,i)=>t in e?Dt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let Lt=class{constructor(){Mt(this,"_locking"),Mt(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}};function Ut(e,t){if(!e)throw new Error(t)}function jt(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Ft(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function $t(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const Bt=Symbol("@bufbuild/protobuf/enum-type");function Vt(e,t,i,n){e[Bt]=qt(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function qt(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const o of t){const e=zt(o);r.push(e),n[o.name]=e,s[o.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function zt(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class Zt{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Ht(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function Kt(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),o=255&(s?128|n:n);if(i.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const Gt=4294967296;function Wt(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=Gt&&(s+=n/Gt|0,n%=Gt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?Qt(n,s):Yt(n,s)}function Jt(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(Gt*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+Xt(r)+Xt(s)}function Yt(e,t){return{lo:0|e,hi:0|t}}function Qt(e,t){return t=~t,e?e=1+~e:t+=1,Yt(e,t)}const Xt=e=>{const t=String(e);return"0000000".slice(t.length)+t};function ei(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function ti(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const ii=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>Ut(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>Ut(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),Wt(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),Wt(e)),dec:(e,t)=>function(e,t){let i=Yt(e,t);const n=2147483648&i.hi;n&&(i=Qt(i.lo,i.hi));const s=Jt(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>Jt(e,t)}}();var ni,si,ri,oi,ai,ci;function di(e,t,i){if(t===i)return!0;if(e==ni.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case ni.UINT64:case ni.FIXED64:case ni.INT64:case ni.SFIXED64:case ni.SINT64:return t==i}return!1}function li(e,t){switch(e){case ni.BOOL:return!1;case ni.UINT64:case ni.FIXED64:case ni.INT64:case ni.SFIXED64:case ni.SINT64:return 0==t?ii.zero:"0";case ni.DOUBLE:case ni.FLOAT:return 0;case ni.BYTES:return new Uint8Array(0);case ni.STRING:return"";default:return 0}}function ui(e,t){switch(e){case ni.BOOL:return!1===t;case ni.STRING:return""===t;case ni.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(si=ni||(ni={}))[si.DOUBLE=1]="DOUBLE",si[si.FLOAT=2]="FLOAT",si[si.INT64=3]="INT64",si[si.UINT64=4]="UINT64",si[si.INT32=5]="INT32",si[si.FIXED64=6]="FIXED64",si[si.FIXED32=7]="FIXED32",si[si.BOOL=8]="BOOL",si[si.STRING=9]="STRING",si[si.BYTES=12]="BYTES",si[si.UINT32=13]="UINT32",si[si.SFIXED32=15]="SFIXED32",si[si.SFIXED64=16]="SFIXED64",si[si.SINT32=17]="SINT32",si[si.SINT64=18]="SINT64",(oi=ri||(ri={}))[oi.BIGINT=0]="BIGINT",oi[oi.STRING=1]="STRING",(ci=ai||(ai={}))[ci.Varint=0]="Varint",ci[ci.Bit64=1]="Bit64",ci[ci.LengthDelimited=2]="LengthDelimited",ci[ci.StartGroup=3]="StartGroup",ci[ci.EndGroup=4]="EndGroup",ci[ci.Bit32=5]="Bit32";class hi{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ft(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return jt(e),ei(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){$t(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ft(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){jt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return jt(e),ei(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=ii.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=ii.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=ii.enc(e);return Kt(t.lo,t.hi,this.buf),this}sint64(e){let t=ii.enc(e),i=t.hi>>31;return Kt(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=ii.uEnc(e);return Kt(t.lo,t.hi,this.buf),this}}class pi{constructor(e,t){this.varint64=Ht,this.uint32=ti,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ai.Varint:for(;128&this.buf[this.pos++];);break;case ai.Bit64:this.pos+=4;case ai.Bit32:this.pos+=4;break;case ai.LengthDelimited:let i=this.uint32();this.pos+=i;break;case ai.StartGroup:for(;;){const[e,i]=this.tag();if(i===ai.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return ii.dec(...this.varint64())}uint64(){return ii.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,ii.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ii.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ii.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function mi(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return li(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let gi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),fi=[];for(let pm=0;pm<gi.length;pm++)fi[gi[pm].charCodeAt(0)]=pm;fi["-".charCodeAt(0)]=gi.indexOf("+"),fi["_".charCodeAt(0)]=gi.indexOf("/");const vi={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let a=0;a<e.length;a++){if(i=fi[e.charCodeAt(a)],void 0===i)switch(e[a]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=gi[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=gi[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=gi[s|t>>6],i+=gi[63&t],n=0}return n&&(i+=gi[s],i+="=",1==n&&(i+="=")),i}};function yi(e,t,i){Ti(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=mi(t);for(const a of s)t.runtime.bin.readField(r,n.readerFactory(a.data),t.field,a.wireType,n);return o()}function bi(e,t,i,n){Ti(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(ki(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function ki(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function Ti(e,t){Ut(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function Si(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!ui(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function Ci(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?li(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function wi(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(Zt.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Ei(e,t){return wi(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}ni.DOUBLE,ni.FLOAT,ni.INT64,ni.UINT64,ni.INT32,ni.UINT32,ni.BOOL,ni.STRING,ni.BYTES;const _i={ignoreUnknownFields:!1},Pi={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const Ri=Symbol(),xi=Symbol();function Oi(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function Ii(e,t,i,n,s){let r=i.localName;if(i.repeated){if(Ut("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Oi(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Oi(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=Di(i.T,e,n.ignoreUnknownFields,!0);t!==xi&&a.push(t);break;case"scalar":try{a.push(Ni(i.T,e,i.L,!0))}catch(o){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Oi(e));throw o instanceof Error&&o.message.length>0&&(t+=": ".concat(o.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Oi(t)));const a=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=Ai(i.K,e)}catch(o){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Oi(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}switch(i.V.kind){case"message":a[c]=i.V.T.fromJson(r,n);break;case"enum":const e=Di(i.V.T,r,n.ignoreUnknownFields,!0);e!==xi&&(a[c]=e);break;case"scalar":try{a[c]=Ni(i.V.T,r,ri.BIGINT,!0)}catch(o){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Oi(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let c=e[r];wi(c)?c.fromJson(t,n):(e[r]=c=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[r]=a.fieldWrapper.unwrapField(c)));break;case"enum":const d=Di(i.T,t,n.ignoreUnknownFields,!1);switch(d){case Ri:Ci(i,e);break;case xi:break;default:e[r]=d}break;case"scalar":try{const n=Ni(i.T,t,i.L,!1);n===Ri?Ci(i,e):e[r]=n}catch(o){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(Oi(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}function Ai(e,t){if(e===ni.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Ni(e,t,ri.BIGINT,!0).toString()}function Ni(e,t,i,n){if(null===t)return n?li(e,i):Ri;switch(e){case ni.DOUBLE:case ni.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==ni.FLOAT&&$t(n),n;case ni.INT32:case ni.FIXED32:case ni.SFIXED32:case ni.SINT32:case ni.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==ni.UINT32||e==ni.FIXED32?Ft(r):jt(r),r;case ni.INT64:case ni.SFIXED64:case ni.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=ii.parse(t);return i?o.toString():o;case ni.FIXED64:case ni.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=ii.uParse(t);return i?a.toString():a;case ni.BOOL:if("boolean"!=typeof t)break;return t;case ni.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case ni.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return vi.dec(t)}throw new Error}function Di(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Ri;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return xi}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(Oi(t)))}function Mi(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function Li(e,t,i){if("map"==e.kind){Ut("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=ji(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=Ui(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){Ut(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ji(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(Ui(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return ji(e.T,t);case"enum":return Ui(e.T,t,i.enumAsInteger);case"message":return Ei(e.T,t).toJson(i)}}function Ui(e,t,i){var n;if(Ut("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function ji(e,t){switch(e){case ni.INT32:case ni.SFIXED32:case ni.SINT32:case ni.FIXED32:case ni.UINT32:return Ut("number"==typeof t),t;case ni.FLOAT:case ni.DOUBLE:return Ut("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case ni.STRING:return Ut("string"==typeof t),t;case ni.BOOL:return Ut("boolean"==typeof t),t;case ni.UINT64:case ni.FIXED64:case ni.INT64:case ni.SFIXED64:case ni.SINT64:return Ut("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case ni.BYTES:return Ut(t instanceof Uint8Array),vi.enc(t)}}const Fi=Symbol("@bufbuild/protobuf/unknown-fields"),$i={readUnknownFields:!0,readerFactory:e=>new pi(e)},Bi={writeUnknownFields:!0,writerFactory:()=>new hi};function Vi(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?ni.INT32:i.T;let c=Zi;if("scalar"==i.kind&&i.L>0&&(c=zi),r){let i=e[o];if(n==ai.LengthDelimited&&a!=ni.STRING&&a!=ni.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(qi(t,new d,s,i)):wi(e[o])?qi(t,e[o],s,i):(e[o]=qi(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=Zi(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=Zi(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=qi(t,new e.V.T,i,void 0)}}}if(void 0===r&&(r=li(e.K,ri.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===o)switch(e.V.kind){case"scalar":o=li(e.V.T,ri.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function qi(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function zi(e,t){const i=Zi(e,t);return"bigint"==typeof i?i.toString():i}function Zi(e,t){switch(t){case ni.STRING:return e.string();case ni.BOOL:return e.bool();case ni.DOUBLE:return e.double();case ni.FLOAT:return e.float();case ni.INT32:return e.int32();case ni.INT64:return e.int64();case ni.UINT64:return e.uint64();case ni.FIXED64:return e.fixed64();case ni.BYTES:return e.bytes();case ni.FIXED32:return e.fixed32();case ni.SFIXED32:return e.sfixed32();case ni.SFIXED64:return e.sfixed64();case ni.SINT64:return e.sint64();case ni.UINT32:return e.uint32();case ni.SINT32:return e.sint32()}}function Hi(e,t,i,n){Ut(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?ni.INT32:e.T;if(s)if(Ut(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,ai.LengthDelimited).fork();let[,s]=Ji(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)Wi(i,r,e.no,n);else Wi(i,r,e.no,t);break;case"message":if(s){Ut(Array.isArray(t));for(const s of t)Gi(i,n,e,s)}else Gi(i,n,e,t);break;case"map":Ut("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))Ki(i,n,e,s,o)}}function Ki(e,t,i,n,s){e.tag(i.no,ai.LengthDelimited),e.fork();let r=n;switch(i.K){case ni.INT32:case ni.FIXED32:case ni.UINT32:case ni.SFIXED32:case ni.SINT32:r=Number.parseInt(n);break;case ni.BOOL:Ut("true"==n||"false"==n),r="true"==n}switch(Wi(e,i.K,1,r),i.V.kind){case"scalar":Wi(e,i.V.T,2,s);break;case"enum":Wi(e,ni.INT32,2,s);break;case"message":Ut(void 0!==s),e.tag(2,ai.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Gi(e,t,i,n){const s=Ei(i.T,n);i.delimited?e.tag(i.no,ai.StartGroup).raw(s.toBinary(t)).tag(i.no,ai.EndGroup):e.tag(i.no,ai.LengthDelimited).bytes(s.toBinary(t))}function Wi(e,t,i,n){Ut(void 0!==n);let[s,r]=Ji(t);e.tag(i,s)[r](n)}function Ji(e){let t=ai.Varint;switch(e){case ni.BYTES:case ni.STRING:t=ai.LengthDelimited;break;case ni.DOUBLE:case ni.FIXED64:case ni.SFIXED64:t=ai.Bit64;break;case ni.FIXED32:case ni.SFIXED32:case ni.FLOAT:t=ai.Bit32}return[t,ni[e].toLowerCase()]}function Yi(e){if(void 0===e)return e;if(wi(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Qi(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Xi{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function en(e,t){const i=nn(e);return t?i:cn(an(i))}const tn=nn;function nn(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const sn=new Set(["constructor","toString","toJSON","valueOf"]),rn=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),on=e=>"".concat(e,"$"),an=e=>rn.has(e)?on(e):e,cn=e=>sn.has(e)?on(e):e;class dn{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=en(e,!1)}addField(e){Ut(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const ln=(un=e=>new Xi(e,(e=>function(e){var t,i,n,s,r,o;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=en(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:tn(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:ri.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=ni.BYTES&&d.T!=ni.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new dn(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e))),hn=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=li(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},_i),e):_i},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Pi),e):Pi},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(Oi(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}Ii(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=mi(s);Ii(e,a,s.field,i,s),bi(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!Si(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Mi(s))continue}const i=Li(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&ki(e,o)){const i=yi(e,o,t),s=Li(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>Ni(e,t,null!=i?i:ri.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||ui(e,t)?ji(e,t):void 0},debug:Oi},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},$i),e):$i},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},Bi),e):Bi},listUnknownFields(e){var t;return null!==(t=e[Fi])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[Fi]},writeUnknownFields(e,t){const i=e[Fi];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[Fi])||(s[Fi]=[]),s[Fi].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=ai.EndGroup);){const i=r.fields.find(a);if(i)Vi(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=ai.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:Vi,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(Si(s,e))Hi(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Hi(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:Vt,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!wi(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===ni.BYTES&&(o=Qi(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===ni.BYTES&&(a=n.repeated?a.map(Qi):Qi(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===ni.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=Qi(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>wi(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Qi(e):s[i]=e:s[i]=wi(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>di(e.T,t,s[i])));case"enum":return n.every(((e,t)=>di(ni.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return di(ni.INT32,n,s);case"scalar":return di(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return di(ni.INT32,n.value,s.value);case"scalar":return di(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>di(ni.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>di(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map(Yi);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=Yi(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:Yi(t.value)}:{case:void 0}:Yi(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:un,initFields:hn}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new Zt),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:function(e,t,i){const n={};for(const s of t){const e=zt(s);n[e.localName]=e.no,n[e.no]=e.localName}return Vt(n,e,t),n},makeEnumType:qt,getEnumType:function(e){const t=e[Bt];return Ut(t,"missing enum type on enum object"),t},makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var un,hn;class pn extends Zt{constructor(e){super(),this.seconds=ii.zero,this.nanos=0,ln.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(ln.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=ii.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return pn.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new pn({seconds:ii.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new pn).fromBinary(e,t)}static fromJson(e,t){return(new pn).fromJson(e,t)}static fromJsonString(e,t){return(new pn).fromJsonString(e,t)}static equals(e,t){return ln.util.equals(pn,e,t)}}pn.runtime=ln,pn.typeName="google.protobuf.Timestamp",pn.fields=ln.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const mn=ln.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:pn},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:gn,repeated:!0},{no:5,name:"events",kind:"message",T:vn,repeated:!0}])),gn=ln.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:fn,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),fn=ln.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:pn},{no:3,name:"value",kind:"scalar",T:2}])),vn=ln.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:pn},{no:7,name:"normalized_end_timestamp",kind:"message",T:pn,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),yn=ln.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),bn=ln.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),kn=ln.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Tn=ln.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Sn=ln.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Cn=ln.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),wn=ln.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"}]),En=ln.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),_n=ln.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Pn=ln.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),Rn=ln.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:xn,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:os}])),xn=ln.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),On=ln.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:ln.getEnumType(kn),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),In=ln.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:ln.getEnumType(An)},{no:4,name:"tracks",kind:"message",T:Un,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:On},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:ln.getEnumType(Nn)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:ln.getEnumType(wn)},{no:18,name:"kind_details",kind:"enum",T:ln.getEnumType(Dn),repeated:!0}])),An=ln.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Nn=ln.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Dn=ln.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Mn=ln.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Ln=ln.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:jn,repeated:!0}])),Un=ln.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:ln.getEnumType(bn)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:ln.getEnumType(kn)},{no:10,name:"layers",kind:"message",T:jn,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Ln,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:ln.getEnumType(Mn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:os},{no:19,name:"audio_features",kind:"enum",T:ln.getEnumType(Pn),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:ln.getEnumType(yn)}])),jn=ln.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:ln.getEnumType(Tn)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13}])),Fn=ln.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:ln.getEnumType($n)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:qn,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Bn,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:zn,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Zn,oneof:"value"},{no:8,name:"metrics",kind:"message",T:mn,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Kn,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Gn,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Wn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Jn,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ls,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:us,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:hs,oneof:"value"}])),$n=ln.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Bn=ln.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Vn,repeated:!0}])),Vn=ln.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),qn=ln.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),zn=ln.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),Zn=ln.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Hn,repeated:!0}])),Hn=ln.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),Kn=ln.makeMessageType("livekit.ChatMessage",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}])),Gn=ln.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}])),Wn=ln.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Jn=ln.makeMessageType("livekit.RpcResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Yn,oneof:"value"}])),Yn=ln.makeMessageType("livekit.RpcError",(()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}])),Qn=ln.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Xn=ln.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:ln.getEnumType(es)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),es=ln.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),ts=ln.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:ln.getEnumType(is)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}])),is=ln.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"}]),ns=ln.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:ss},{no:2,name:"screen",kind:"message",T:ss},{no:3,name:"resume_connection",kind:"enum",T:ln.getEnumType(Cn)},{no:4,name:"disabled_codecs",kind:"message",T:rs},{no:5,name:"force_relay",kind:"enum",T:ln.getEnumType(Cn)}])),ss=ln.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:ln.getEnumType(Cn)}])),rs=ln.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:xn,repeated:!0},{no:2,name:"publish",kind:"message",T:xn,repeated:!0}])),os=ln.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),as=ln.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),cs=ln.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:ln.getEnumType(as)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}]),{localName:"DataStream_TextHeader"}),ds=ln.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),ls=ln.makeMessageType("livekit.DataStream.Header",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:ln.getEnumType(Mn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:cs,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:ds,oneof:"content_header"}]),{localName:"DataStream_Header"}),us=ln.makeMessageType("livekit.DataStream.Chunk",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}]),{localName:"DataStream_Chunk"}),hs=ln.makeMessageType("livekit.DataStream.Trailer",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]),{localName:"DataStream_Trailer"}),ps=ln.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),ms=ln.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),gs=ln.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),fs=ln.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:_s,oneof:"message"},{no:2,name:"answer",kind:"message",T:_s,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ks,oneof:"message"},{no:4,name:"add_track",kind:"message",T:bs,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ts,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Rs,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:xs,oneof:"message"},{no:8,name:"leave",kind:"message",T:As,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ds,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Ks,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ws,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ys,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ms,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Qs,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Os,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Is,oneof:"message"}])),vs=ln.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Ss,oneof:"message"},{no:2,name:"answer",kind:"message",T:_s,oneof:"message"},{no:3,name:"offer",kind:"message",T:_s,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ks,oneof:"message"},{no:5,name:"update",kind:"message",T:Ps,oneof:"message"},{no:6,name:"track_published",kind:"message",T:ws,oneof:"message"},{no:8,name:"leave",kind:"message",T:As,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ts,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Us,oneof:"message"},{no:11,name:"room_update",kind:"message",T:js,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:$s,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Vs,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Zs,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Gs,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Es,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Cs,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Xs,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ir,oneof:"message"},{no:22,name:"request_response",kind:"message",T:nr,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:rr,oneof:"message"}])),ys=ln.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),bs=ln.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:ln.getEnumType(bn)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:ln.getEnumType(kn)},{no:9,name:"layers",kind:"message",T:jn,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:ys,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:ln.getEnumType(Mn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:ln.getEnumType(yn)}])),ks=ln.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:ln.getEnumType(ps)},{no:3,name:"final",kind:"scalar",T:8}])),Ts=ln.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Ss=ln.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:Rn},{no:2,name:"participant",kind:"message",T:In},{no:3,name:"other_participants",kind:"message",T:In,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Ls,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:ns},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Xn},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:xn,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),Cs=ln.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Ls,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ns}])),ws=ln.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Un}])),Es=ln.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),_s=ln.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),Ps=ln.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:In,repeated:!0}])),Rs=ln.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Qn,repeated:!0}])),xs=ln.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:ln.getEnumType(Tn)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}])),Os=ln.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:ln.getEnumType(Pn),repeated:!0}])),Is=ln.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),As=ln.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:ln.getEnumType(wn)},{no:3,name:"action",kind:"enum",T:ln.getEnumType(Ns)},{no:4,name:"regions",kind:"message",T:er}])),Ns=ln.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ds=ln.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:jn,repeated:!0}])),Ms=ln.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),Ls=ln.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),Us=ln.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Vn,repeated:!0}])),js=ln.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:Rn}])),Fs=ln.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:ln.getEnumType(Sn)},{no:3,name:"score",kind:"scalar",T:2}])),$s=ln.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:Fs,repeated:!0}])),Bs=ln.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:ln.getEnumType(ms)}])),Vs=ln.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:Bs,repeated:!0}])),qs=ln.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:ln.getEnumType(Tn)},{no:2,name:"enabled",kind:"scalar",T:8}])),zs=ln.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:qs,repeated:!0}])),Zs=ln.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:qs,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:zs,repeated:!0}])),Hs=ln.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Ks=ln.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Hs,repeated:!0}])),Gs=ln.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),Ws=ln.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:_s},{no:2,name:"subscription",kind:"message",T:Rs},{no:3,name:"publish_tracks",kind:"message",T:ws,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Js,repeated:!0},{no:5,name:"offer",kind:"message",T:_s},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),Js=ln.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:ln.getEnumType(ps)}])),Ys=ln.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:ln.getEnumType(gs),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),Qs=ln.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Xs=ln.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),er=ln.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:tr,repeated:!0}])),tr=ln.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),ir=ln.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:ln.getEnumType(_n)}])),nr=ln.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:ln.getEnumType(sr)},{no:3,name:"message",kind:"scalar",T:9}])),sr=ln.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),rr=ln.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function or(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ar,cr,dr,lr,ur,hr,pr,mr,gr={exports:{}},fr=(ar||(ar=1,dr=gr.exports,lr=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},(cr=gr).exports?cr.exports=lr():dr.log=lr()),gr.exports);(hr=ur||(ur={}))[hr.trace=0]="trace",hr[hr.debug=1]="debug",hr[hr.info=2]="info",hr[hr.warn=3]="warn",hr[hr.error=4]="error",hr[hr.silent=5]="silent",(mr=pr||(pr={})).Default="livekit",mr.Room="livekit-room",mr.Participant="livekit-participant",mr.Track="livekit-track",mr.Publication="livekit-track-publication",mr.Engine="livekit-engine",mr.Signal="livekit-signal",mr.PCManager="livekit-pc-manager",mr.PCTransport="livekit-pc-transport",mr.E2EE="lk-e2ee";let vr=fr.getLogger("livekit");function yr(e){const t=fr.getLogger(e);return t.setDefaultLevel(vr.getLevel()),t}Object.values(pr).map((e=>fr.getLogger(e))),vr.setDefaultLevel(ur.info);const br=fr.getLogger("lk-e2ee"),kr=7e3,Tr=[0,300,1200,2700,4800,kr,kr,kr,kr,kr];function Sr(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(t){r(t)}}function a(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function Cr(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){!function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)}(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var wr,Er={exports:{}},_r=function(){if(wr)return Er.exports;wr=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}Er.exports=s,Er.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(o(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){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 l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);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 s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.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},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(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},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,a;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[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},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},Er.exports}();let Pr=!0,Rr=!0;function xr(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function Or(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(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,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.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 Ir(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Pr=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Ar(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Rr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Nr(){if("object"==typeof window){if(Pr)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Dr(e,t){Rr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Mr(e){return"[object Object]"===Object.prototype.toString.call(e)}function Lr(e){return Mr(e)?Object.keys(e).reduce((function(t,i){const n=Mr(e[i]),s=n?Lr(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function Ur(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Ur(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Ur(e,e.get(t),i)}))})))}function jr(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)})),r.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Ur(e,i,s)}))})),s}const Fr=Nr;function $r(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=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[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=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 r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),Fr("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return Fr("chrome: "+JSON.stringify(e)),s(e)},r=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(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(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(r(e))))))}}}function Br(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Vr(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Or(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function qr(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 i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};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 i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.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 zr(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 i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>jr(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}),Or(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>jr(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,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Zr(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,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=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();i.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 s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Hr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Zr(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.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 i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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,i){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 s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>r(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 i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(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:r(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((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Kr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Gr(e,t){Or(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Wr=Object.freeze({__proto__:null,fixNegotiationNeeded:Gr,shimAddTrackRemoveTrack:Hr,shimAddTrackRemoveTrackWithNative:Zr,shimGetSendersWithDtmf:qr,shimGetUserMedia:$r,shimMediaStream:Br,shimOnTrack:Vr,shimPeerConnection:Kr,shimSenderReceiverGetStats:zr});function Jr(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Dr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Yr(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,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 i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={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,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(n){if("TypeError"!==n.name)throw n;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function Xr(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 i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.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 eo(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}),Or(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function to(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Dr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function io(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function no(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 i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[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(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function so(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 ro(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 oo(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 ao=Object.freeze({__proto__:null,shimAddTransceiver:no,shimCreateAnswer:oo,shimCreateOffer:ro,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:so,shimGetUserMedia:Jr,shimOnTrack:Yr,shimPeerConnection:Qr,shimRTCDataChannel:io,shimReceiverGetStats:eo,shimRemoveStream:to,shimSenderGetStats:Xr});function co(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((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.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 i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function lo(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 i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function uo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function ho(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(po(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function po(e){return e&&void 0!==e.video?Object.assign({},e,{video:Lr(e.video)}):e}function mo(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(Dr("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function go(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 fo(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 i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function vo(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var yo,bo=Object.freeze({__proto__:null,shimAudioContext:vo,shimCallbacksAPI:uo,shimConstraints:po,shimCreateOfferLegacy:fo,shimGetUserMedia:ho,shimLocalStreamsAPI:co,shimRTCIceServerUrls:mo,shimRemoteStreamsAPI:lo,shimTrackEventTransceiver:go}),ko={exports:{}},To=(yo||(yo=1,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 i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),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 i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\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 i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=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:"+i+" "+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="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},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 i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.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,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},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,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.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 i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.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",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-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}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.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,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},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 i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};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:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="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&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"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 i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(ko)),ko.exports),So=or(To),Co=Nt({__proto__:null,default:So},[To]);function wo(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 i=new t(e),n=So.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Or(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function Eo(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Or(e,"icecandidate",(e=>{if(e.candidate){const t=So.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function _o(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 i=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=So.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=So.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 i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=So.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function Po(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},Or(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Ro(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 i=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 i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function xo(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=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:i}):t.sdp=i}return i.apply(this,arguments)}}function Oo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.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():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Io(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.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"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var Ao=Object.freeze({__proto__:null,removeExtmapAllowMixed:xo,shimAddIceCandidateNullOrEmpty:Oo,shimConnectionState:Ro,shimMaxMessageSize:_o,shimParameterlessSetLocalDescription:Io,shimRTCIceCandidate:wo,shimRTCIceCandidateRelayProtocol:Eo,shimSendThrowTypeError:Po});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=Nr,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:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=xr(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=xr(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=xr(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:Ao,extractVersion:xr,disableLog:Ir,disableWarnings:Ar,sdp:Co};switch(n.browser){case"chrome":if(!Wr||!Kr||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Wr,Oo(e,n),Io(e),$r(e,n),Br(e),Kr(e,n),Vr(e),Hr(e,n),qr(e),zr(e),Gr(e,n),wo(e),Eo(e),Ro(e),_o(e,n),Po(e),xo(e,n);break;case"firefox":if(!ao||!Qr||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=ao,Oo(e,n),Io(e),Jr(e,n),Qr(e,n),Yr(e),to(e),Xr(e),eo(e),io(e),no(e),so(e),ro(e),oo(e),wo(e),Ro(e),_o(e,n),Po(e);break;case"safari":if(!bo||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=bo,Oo(e,n),Io(e),mo(e),fo(e),uo(e),co(e),lo(e),go(e),ho(e),vo(e),wo(e),Eo(e),_o(e,n),Po(e),xo(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const No="lk_e2ee";var Do,Mo,Lo,Uo,jo,Fo,$o,Bo,Vo,qo,zo,Zo,Ho,Ko,Go,Wo,Jo,Yo,Qo,Xo;function ea(){return void 0!==window.RTCRtpScriptTransform}(Mo=Do||(Do={})).SetKey="setKey",Mo.RatchetRequest="ratchetRequest",Mo.KeyRatcheted="keyRatcheted",(Lo||(Lo={})).KeyRatcheted="keyRatcheted",(jo=Uo||(Uo={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",jo.EncryptionError="encryptionError",(Fo||(Fo={})).Error="cryptorError",_r.EventEmitter;class ta extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}(Bo=$o||($o={}))[Bo.NotAllowed=0]="NotAllowed",Bo[Bo.ServerUnreachable=1]="ServerUnreachable",Bo[Bo.InternalError=2]="InternalError",Bo[Bo.Cancelled=3]="Cancelled",Bo[Bo.LeaveRequest=4]="LeaveRequest";class ia extends ta{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=$o[t]}}class na extends ta{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class sa extends ta{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class ra extends ta{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class oa extends ta{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class aa extends ta{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class ca extends ta{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class da extends ta{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:sr[t]}}(qo=Vo||(Vo={})).PermissionDenied="PermissionDenied",qo.NotFound="NotFound",qo.DeviceInUse="DeviceInUse",qo.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(Vo||(Vo={})),(Zo=zo||(zo={}))[Zo.InvalidKey=0]="InvalidKey",Zo[Zo.MissingKey=1]="MissingKey",Zo[Zo.InternalError=2]="InternalError",(Ko=Ho||(Ho={})).Connected="connected",Ko.Reconnecting="reconnecting",Ko.SignalReconnecting="signalReconnecting",Ko.Reconnected="reconnected",Ko.Disconnected="disconnected",Ko.ConnectionStateChanged="connectionStateChanged",Ko.MediaDevicesChanged="mediaDevicesChanged",Ko.ParticipantConnected="participantConnected",Ko.ParticipantDisconnected="participantDisconnected",Ko.TrackPublished="trackPublished",Ko.TrackSubscribed="trackSubscribed",Ko.TrackSubscriptionFailed="trackSubscriptionFailed",Ko.TrackUnpublished="trackUnpublished",Ko.TrackUnsubscribed="trackUnsubscribed",Ko.TrackMuted="trackMuted",Ko.TrackUnmuted="trackUnmuted",Ko.LocalTrackPublished="localTrackPublished",Ko.LocalTrackUnpublished="localTrackUnpublished",Ko.LocalAudioSilenceDetected="localAudioSilenceDetected",Ko.ActiveSpeakersChanged="activeSpeakersChanged",Ko.ParticipantMetadataChanged="participantMetadataChanged",Ko.ParticipantNameChanged="participantNameChanged",Ko.ParticipantAttributesChanged="participantAttributesChanged",Ko.RoomMetadataChanged="roomMetadataChanged",Ko.DataReceived="dataReceived",Ko.SipDTMFReceived="sipDTMFReceived",Ko.TranscriptionReceived="transcriptionReceived",Ko.ConnectionQualityChanged="connectionQualityChanged",Ko.TrackStreamStateChanged="trackStreamStateChanged",Ko.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Ko.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Ko.AudioPlaybackStatusChanged="audioPlaybackChanged",Ko.VideoPlaybackStatusChanged="videoPlaybackChanged",Ko.MediaDevicesError="mediaDevicesError",Ko.ParticipantPermissionsChanged="participantPermissionsChanged",Ko.SignalConnected="signalConnected",Ko.RecordingStatusChanged="recordingStatusChanged",Ko.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Ko.EncryptionError="encryptionError",Ko.DCBufferStatusChanged="dcBufferStatusChanged",Ko.ActiveDeviceChanged="activeDeviceChanged",Ko.ChatMessage="chatMessage",Ko.LocalTrackSubscribed="localTrackSubscribed",Ko.MetricsReceived="metricsReceived",(Wo=Go||(Go={})).TrackPublished="trackPublished",Wo.TrackSubscribed="trackSubscribed",Wo.TrackSubscriptionFailed="trackSubscriptionFailed",Wo.TrackUnpublished="trackUnpublished",Wo.TrackUnsubscribed="trackUnsubscribed",Wo.TrackMuted="trackMuted",Wo.TrackUnmuted="trackUnmuted",Wo.LocalTrackPublished="localTrackPublished",Wo.LocalTrackUnpublished="localTrackUnpublished",Wo.ParticipantMetadataChanged="participantMetadataChanged",Wo.ParticipantNameChanged="participantNameChanged",Wo.DataReceived="dataReceived",Wo.SipDTMFReceived="sipDTMFReceived",Wo.TranscriptionReceived="transcriptionReceived",Wo.IsSpeakingChanged="isSpeakingChanged",Wo.ConnectionQualityChanged="connectionQualityChanged",Wo.TrackStreamStateChanged="trackStreamStateChanged",Wo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Wo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Wo.MediaDevicesError="mediaDevicesError",Wo.AudioStreamAcquired="audioStreamAcquired",Wo.ParticipantPermissionsChanged="participantPermissionsChanged",Wo.PCTrackAdded="pcTrackAdded",Wo.AttributesChanged="attributesChanged",Wo.LocalTrackSubscribed="localTrackSubscribed",Wo.ChatMessage="chatMessage",(Yo=Jo||(Jo={})).TransportsCreated="transportsCreated",Yo.Connected="connected",Yo.Disconnected="disconnected",Yo.Resuming="resuming",Yo.Resumed="resumed",Yo.Restarting="restarting",Yo.Restarted="restarted",Yo.SignalResumed="signalResumed",Yo.SignalRestarted="signalRestarted",Yo.Closing="closing",Yo.MediaTrackAdded="mediaTrackAdded",Yo.ActiveSpeakersUpdate="activeSpeakersUpdate",Yo.DataPacketReceived="dataPacketReceived",Yo.RTPVideoMapUpdate="rtpVideoMapUpdate",Yo.DCBufferStatusChanged="dcBufferStatusChanged",Yo.ParticipantUpdate="participantUpdate",Yo.RoomUpdate="roomUpdate",Yo.SpeakersChanged="speakersChanged",Yo.StreamStateChanged="streamStateChanged",Yo.ConnectionQualityUpdate="connectionQualityUpdate",Yo.SubscriptionError="subscriptionError",Yo.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Yo.RemoteMute="remoteMute",Yo.SubscribedQualityUpdate="subscribedQualityUpdate",Yo.LocalTrackUnpublished="localTrackUnpublished",Yo.LocalTrackSubscribed="localTrackSubscribed",Yo.Offline="offline",Yo.SignalRequestResponse="signalRequestResponse",Yo.SignalConnected="signalConnected",(Xo=Qo||(Qo={})).Message="message",Xo.Muted="muted",Xo.Unmuted="unmuted",Xo.Restarted="restarted",Xo.Ended="ended",Xo.Subscribed="subscribed",Xo.Unsubscribed="unsubscribed",Xo.UpdateSettings="updateSettings",Xo.UpdateSubscription="updateSubscription",Xo.AudioPlaybackStarted="audioPlaybackStarted",Xo.AudioPlaybackFailed="audioPlaybackFailed",Xo.AudioSilenceDetected="audioSilenceDetected",Xo.VisibilityChanged="visibilityChanged",Xo.VideoDimensionsChanged="videoDimensionsChanged",Xo.VideoPlaybackStarted="videoPlaybackStarted",Xo.VideoPlaybackFailed="videoPlaybackFailed",Xo.ElementAttached="elementAttached",Xo.ElementDetached="elementDetached",Xo.UpstreamPaused="upstreamPaused",Xo.UpstreamResumed="upstreamResumed",Xo.SubscriptionPermissionChanged="subscriptionPermissionChanged",Xo.SubscriptionStatusChanged="subscriptionStatusChanged",Xo.SubscriptionFailed="subscriptionFailed",Xo.TrackProcessorUpdate="trackProcessorUpdate",Xo.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Xo.TranscriptionReceived="transcriptionReceived",Xo.TimeSyncUpdate="timeSyncUpdate";const la=/version\/(\d+(\.?_?\d+)+)/i;let ua;function ha(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===ua||t){const e=pa.find((e=>{let{test:t}=e;return t.test(i)}));ua=null==e?void 0:e.describe(i)}return ua}const pa=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:ma(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ga(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:ma(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ga(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:ma(la,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:ga(e)})}];function ma(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function ga(e){return e.includes("mac os")?ma(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class fa{}fa.setTimeout=function(){return setTimeout(...arguments)},fa.setInterval=function(){return setInterval(...arguments)},fa.clearTimeout=function(){return clearTimeout(...arguments)},fa.clearInterval=function(){return clearInterval(...arguments)};const va=[];var ya,ba;(ba=ya||(ya={}))[ba.LOW=0]="LOW",ba[ba.MEDIUM=1]="MEDIUM",ba[ba.HIGH=2]="HIGH";class ka extends _r.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=ka.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=vr,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=yr(null!==(n=i.loggerName)&&void 0!==n?n:pr.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=ka.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Pc(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===ka.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===ka.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(va.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&va.splice(va.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Ta(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?Qo.AudioPlaybackStarted:Qo.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?Qo.AudioPlaybackFailed:Qo.VideoPlaybackFailed,t):"AbortError"===t.name?vr.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):vr.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Qo.ElementAttached,e),e}detach(e){try{if(e){Sa(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Qo.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{Sa(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Qo.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=yr(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),va.forEach((e=>{e.parentElement||(t=!1)})),t&&va.push(e)}}handleAppVisibilityChanged(){return Sr(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==ka.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){qa()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){qa()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Ta(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),Ba()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(Ba()||$a())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function Sa(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var o;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(o=r=e.StreamState||(e.StreamState={})).Active="active",o.Paused="paused",o.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return bn.AUDIO;case t.Video:return bn.VIDEO;default:return bn.DATA}},e.kindFromProto=function(e){switch(e){case bn.AUDIO:return t.Audio;case bn.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return kn.CAMERA;case n.Microphone:return kn.MICROPHONE;case n.ScreenShare:return kn.SCREEN_SHARE;case n.ScreenShareAudio:return kn.SCREEN_SHARE_AUDIO;default:return kn.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case kn.CAMERA:return n.Camera;case kn.MICROPHONE:return n.Microphone;case kn.SCREEN_SHARE:return n.ScreenShare;case kn.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case ms.ACTIVE:return r.Active;case ms.PAUSED:return r.Paused;default:return r.Unknown}}}(ka||(ka={}));class Ca{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const wa=["vp8","h264"],Ea=["vp8","h264","vp9","av1"];function _a(e){return!!wa.find((t=>t===e))}var Pa,Ra,xa,Oa;(Ra=Pa||(Pa={}))[Ra.PREFER_REGRESSION=0]="PREFER_REGRESSION",Ra[Ra.SIMULCAST=1]="SIMULCAST",Ra[Ra.REGRESSION=2]="REGRESSION",(Oa=xa||(xa={})).telephone={maxBitrate:12e3},Oa.speech={maxBitrate:24e3},Oa.music={maxBitrate:48e3},Oa.musicStereo={maxBitrate:64e3},Oa.musicHighQuality={maxBitrate:96e3},Oa.musicHighQualityStereo={maxBitrate:128e3};const Ia={h90:new Ca(160,90,9e4,20),h180:new Ca(320,180,16e4,20),h216:new Ca(384,216,18e4,20),h360:new Ca(640,360,45e4,20),h540:new Ca(960,540,8e5,25),h720:new Ca(1280,720,17e5,30),h1080:new Ca(1920,1080,3e6,30),h1440:new Ca(2560,1440,5e6,30),h2160:new Ca(3840,2160,8e6,30)},Aa={h120:new Ca(160,120,7e4,20),h180:new Ca(240,180,125e3,20),h240:new Ca(320,240,14e4,20),h360:new Ca(480,360,33e4,20),h480:new Ca(640,480,5e5,20),h540:new Ca(720,540,6e5,25),h720:new Ca(960,720,13e5,30),h1080:new Ca(1440,1080,23e5,30),h1440:new Ca(1920,1440,38e5,30)},Na={h360fps3:new Ca(640,360,2e5,3,"medium"),h360fps15:new Ca(640,360,4e5,15,"medium"),h720fps5:new Ca(1280,720,8e5,5,"medium"),h720fps15:new Ca(1280,720,15e5,15,"medium"),h720fps30:new Ca(1280,720,2e6,30,"medium"),h1080fps15:new Ca(1920,1080,25e5,15,"medium"),h1080fps30:new Ca(1920,1080,5e6,30,"medium"),original:new Ca(0,0,7e6,30,"medium")},Da="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Ma(e){return Sr(this,void 0,void 0,(function*(){return new Promise((t=>fa.setTimeout(t,e)))}))}function La(){return"addTransceiver"in RTCPeerConnection.prototype}function Ua(){return"addTrack"in RTCPeerConnection.prototype}function ja(e){return"av1"===e||"vp9"===e}function Fa(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function $a(){var e;return"Firefox"===(null===(e=ha())||void 0===e?void 0:e.name)}function Ba(){var e;return"Safari"===(null===(e=ha())||void 0===e?void 0:e.name)}function Va(){var e,t;return!!qa()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function qa(){return"undefined"!=typeof document}function za(){return"ReactNative"==navigator.product}function Za(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ha(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Ka(){if(!za())return;let e=Ha();return e?e.platform:void 0}function Ga(){if(qa())return window.devicePixelRatio;if(za()){let e=Ha();if(e)return e.devicePixelRatio}return 1}function Wa(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Ja(e){for(const t of e)t.target.handleResize(t)}function Ya(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Qa=null;const Xa=()=>(Qa||(Qa=new ResizeObserver(Ja)),Qa);let ec=null;const tc=()=>(ec||(ec=new IntersectionObserver(Ya,{root:null,rootMargin:"0px"})),ec);function ic(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let nc;function sc(){if(!nc){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[nc]=n.stream.getAudioTracks(),!nc)throw Error("Could not get empty media stream audio track");nc.enabled=!1}return nc.clone()}class rc{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Sr(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function oc(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function ac(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function cc(e){switch(e.reason){case $o.LeaveRequest:return e.context;case $o.Cancelled:return wn.CLIENT_INITIATED;case $o.NotAllowed:return wn.USER_REJECTED;case $o.ServerUnreachable:return wn.JOIN_FAILURE;default:return wn.UNKNOWN_REASON}}function dc(e){return void 0!==e?Number(e):void 0}function lc(e){return void 0!==e?BigInt(e):void 0}function uc(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function hc(e){return!!e&&e.kind==ka.Kind.Audio}function pc(e){return!!e&&e.kind==ka.Kind.Video}function mc(e){return uc(e)&&pc(e)}function gc(e){return uc(e)&&hc(e)}function fc(e){return!!e&&!e.isLocal}function vc(e){return!!e&&!e.isLocal}function yc(e){return fc(e)&&pc(e)}function bc(e,t,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=Rc(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(kc(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(kc(h.video,i),null!==(s=(o=h.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function kc(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function Tc(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,o=e.video;Object.keys(o).forEach((e=>{"resolution"===e?kc(s,o.resolution):s[e]=o[e]})),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Sc(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Sr(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function Cc(e){return"audioinput"===e?ka.Source.Microphone:"videoinput"===e?ka.Source.Camera:ka.Source.Unknown}function wc(e){return e===ka.Source.Microphone?"audioinput":e===ka.Source.Camera?"videoinput":void 0}function Ec(e){return e.split("/")[1].toLowerCase()}function _c(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new ws({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function Pc(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?Pc(e.track):{})}}function Rc(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}class xc extends _r.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":vr.error(s.error.message),this.emit(Uo.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Uo.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(Uo.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(Do.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=e=>{vr.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Uo.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||ea()))throw new na("tried to setup end-to-end encryption on an unsupported browser");if(vr.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:br.getLevel()}};this.worker&&(vr.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){vr.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):vr.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Jo.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(Ho.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Mn.NONE,t.identity))),e.on(Ho.ConnectionStateChanged,(t=>{t===Kd.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Mn.NONE,e.identity)}))}))})).on(Ho.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(Ho.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(Ho.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(Go.LocalTrackPublished,(e=>Sr(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),t.on(Do.SetKey,(e=>this.postKey(e))).on(Do.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?Ec(i.mimeType):void 0)}}setupE2EESender(e,t){uc(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||vr.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Sr(this,void 0,void 0,(function*(){if(this.worker){if(ea()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(No in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(o,[r,s])}e[No]=!0}}))}handleSender(e,t,i){var n;if(!(No in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ea()){vr.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{vr.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[No]=!0}}}const Oc="default";class Ic{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Ic),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Sr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=Ic.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){vr.debug("awaiting getUserMedia promise");try{e?yield Ic.userMediaPromiseMap.get(e):yield Promise.all(Ic.userMediaPromiseMap.values())}catch(r){vr.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!Ba()||!t.hasDeviceInUse(e))&&(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return Sr(this,void 0,void 0,(function*(){if(t!==Oc)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===Oc));if(!s)return void vr.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==Oc&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;vr.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Ic.userMediaPromiseMap.has(e):Ic.userMediaPromiseMap.size>0}}var Ac,Nc;Ic.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Ic.userMediaPromiseMap=new Map,(Nc=Ac||(Ac={}))[Nc.WAITING=0]="WAITING",Nc[Nc.RUNNING=1]="RUNNING",Nc[Nc.COMPLETED=2]="COMPLETED";class Dc{constructor(){this.pendingTasks=new Map,this.taskMutex=new Lt,this.nextTaskIndex=0}run(e){return Sr(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ac.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ac.RUNNING,yield e()}finally{t.status=Ac.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Sr(this,void 0,void 0,(function*(){return this.run((()=>Sr(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function Mc(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const Lc=["syncState","trickle","offer","answer","simulate","leave"];var Uc,jc;(jc=Uc||(Uc={}))[jc.CONNECTING=0]="CONNECTING",jc[jc.CONNECTED=1]="CONNECTED",jc[jc.RECONNECTING=2]="RECONNECTING",jc[jc.DISCONNECTING=3]="DISCONNECTING",jc[jc.DISCONNECTED=4]="DISCONNECTED";class Fc{get currentState(){return this.state}get isDisconnected(){return this.state===Uc.DISCONNECTING||this.state===Uc.DISCONNECTED}get isEstablishingConnection(){return this.state===Uc.CONNECTING||this.state===Uc.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Uc.DISCONNECTED,this.log=vr,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=yr(null!==(i=t.loggerName)&&void 0!==i?i:pr.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Dc,this.queuedRequests=[],this.closingLock=new Lt,this.connectionLock=new Lt,this.state=Uc.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return Sr(this,void 0,void 0,(function*(){return this.state=Uc.CONNECTING,this.options=i,yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Sr(this,void 0,void 0,(function*(){if(this.options)return this.state=Uc.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(e,t,i,n){this.connectOptions=i;const s=function(e,t,i){var n;const s=new URLSearchParams;return s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",za()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel),t.os&&s.set("os",t.os),t.osVersion&&s.set("os_version",t.osVersion),t.browser&&s.set("browser",t.browser),t.browserVersion&&s.set("browser_version",t.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(t,function(){var e;const t=new ts({sdk:is.JS,protocol:15,version:"2.11.4"});return za()&&(t.os=null!==(e=Ka())&&void 0!==e?e:""),t}(),i),r=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),Mc(i,"rtc")}(e,s),o=Mc(new URL(ac(r)),"validate");return new Promise(((e,t)=>Sr(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>Sr(this,void 0,void 0,(function*(){this.close(),clearTimeout(a),t(new ia("room connection has been cancelled (signal)",$o.Cancelled))})),a=setTimeout((()=>{this.close(),t(new ia("room connection has timed out (signal)",$o.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(r);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(a)},this.ws.onerror=e=>Sr(this,void 0,void 0,(function*(){if(this.state===Uc.CONNECTED)this.handleWSError(e);else{this.state=Uc.DISCONNECTED,clearTimeout(a);try{const i=yield fetch(o);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new ia(e,$o.NotAllowed,i.status))}else t(new ia("Encountered unknown websocket error during connection: ".concat(e.toString()),$o.InternalError,i.status))}catch(i){t(new ia(i instanceof Error?i.message:"server was not reachable",$o.ServerUnreachable))}}})),this.ws.onmessage=r=>Sr(this,void 0,void 0,(function*(){var o,a,c;let d;if("string"==typeof r.data){const e=JSON.parse(r.data);d=vs.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);d=vs.fromBinary(new Uint8Array(r.data))}if(this.state!==Uc.CONNECTED){let r=!1;if("join"===(null===(o=d.message)||void 0===o?void 0:o.case)?(this.state=Uc.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(d.message.value)):this.state===Uc.RECONNECTING&&"leave"!==d.message.case?(this.state=Uc.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(a=d.message)||void 0===a?void 0:a.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new ia("Received leave request while trying to (re)connect",$o.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new ia("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),$o.InternalError)),!r)return}this.signalLatency&&(yield Ma(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new ia("Websocket got closed during a (re)connection attempt",$o.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return Sr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Uc.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,Ma(250)])),e.ws=void 0}}finally{t&&(e.state=Uc.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Bc(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Bc(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ks({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ts({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Sr(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Ms({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Ds({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Ks({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ii.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Qs({timestamp:ii.parse(Date.now()),rtt:ii.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Os({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new As({reason:wn.CLIENT_INITIATED,action:Ns.DISCONNECT})})}sendRequest(e){return Sr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=Lc.indexOf(e.case)>=0;return vr.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Uc.RECONNECTING)return void t.queuedRequests.push((()=>Sr(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Ma(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new fs({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=$c(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=$c(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Sr(this,void 0,void 0,(function*(){if(this.state===Uc.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=fa.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&fa.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=fa.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&fa.clearInterval(this.pingInterval)}}function $c(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function Bc(e){return new _s({sdp:e.sdp,type:e.type})}var Vc,qc,zc,Zc,Hc,Kc={},Gc={},Wc={exports:{}};function Jc(){if(Vc)return Wc.exports;Vc=1;var e=Wc.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")+(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":"")+(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"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),Wc.exports}function Yc(){if(Zc)return zc;Zc=1;var e=Jc(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var o=t.names[r];t.name?s.push(n[t.name][o]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return zc=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var o=i.outerOrder||s,a=i.innerOrder||r,c=[];return o.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"}}var Qc=function(){if(Hc)return Kc;Hc=1;var e=(qc||(qc=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Jc(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(Gc)),Gc),t=Yc(),i=Jc();return Kc.grammar=i,Kc.write=t,Kc.parse=e.parse,Kc.parseParams=e.parseParams,Kc.parseFmtpConfig=e.parseFmtpConfig,Kc.parsePayloads=e.parsePayloads,Kc.parseRemoteCandidates=e.parseRemoteCandidates,Kc.parseImageAttributes=e.parseImageAttributes,Kc.parseSimulcastStreamList=e.parseSimulcastStreamList,Kc}();function Xc(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise((function(s,u){var h=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var t=e.apply(n,i);a&&a(t),l.forEach((function(e){return(0,e.resolve)(t)})),l=[]}}),function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return a&&a(p),s(p)}l.push({resolve:s,reject:u})}))};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},u}const ed="negotiationStarted",td="negotiationComplete",id="rtpVideoPayloadTypes";class nd extends _r.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=vr,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Xc((e=>Sr(this,void 0,void 0,(function*(){this.emit(ed);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=yr(null!==(i=t.loggerName)&&void 0!==i?i:pr.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Sr(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return Sr(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Qc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=Qc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=Qc.write(n)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(td),e.sdp)&&Qc.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(id,e.rtp)}))}))}createAndSendOffer(e){return Sr(this,void 0,void 0,(function*(){var t;if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=Qc.parse(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{rd(e),"audio"===e.type?sd(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(ja(t.codec)&&this.ensureVideoDDExtensionForSVC(e,n),"av1"!==t.codec)return!0;const s=Math.round(.7*t.maxbr);for(const n of e.fmtp)if(n.payload===i){n.config.includes("x-google-start-bitrate")||(n.config+=";x-google-start-bitrate=".concat(s));break}return!0}))})),yield this.setMungedSDP(i,Qc.write(n)),this.onOffer(i)}))}createAndSetAnswer(){return Sr(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Qc.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{rd(e),"audio"===e.type&&sd(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Qc.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new oa("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new oa("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Sr(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return Sr(this,void 0,void 0,(function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new aa(t)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Da)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:Da})}}}function sd(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function rd(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const od="vp8",ad={audioPreset:xa.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Na.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:od,backupCodec:!0},cd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},dd={deviceId:{ideal:"default"},resolution:Ia.h720.resolution},ld={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:Tr}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},ud={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var hd,pd;(pd=hd||(hd={}))[pd.NEW=0]="NEW",pd[pd.CONNECTING=1]="CONNECTING",pd[pd.CONNECTED=2]="CONNECTED",pd[pd.FAILED=3]="FAILED",pd[pd.CLOSING=4]="CLOSING",pd[pd.CLOSED=5]="CLOSED";class md{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=ud.peerConnectionTimeout,this.log=vr,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=hd.CONNECTED:i.some((e=>"failed"===e))?this.state=hd.FAILED:i.some((e=>"connecting"===e))?this.state=hd.CONNECTING:i.every((e=>"closed"===e))?this.state=hd.CLOSED:i.some((e=>"closed"===e))?this.state=hd.CLOSING:i.every((e=>"new"===e))&&(this.state=hd.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(hd[t]," to ").concat(hd[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=yr(null!==(n=i.loggerName)&&void 0!==n?n:pr.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new nd(e,i),this.subscriber=new nd(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,ps.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,ps.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=hd.NEW,this.connectionLock=new Lt,this.remoteOfferLock=new Lt}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return Sr(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return Sr(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Sr(this,void 0,void 0,(function*(){t===ps.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return Sr(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Sr(this,void 0,void 0,(function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return Sr(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Sr(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(ed,(()=>{e.signal.aborted||this.publisher.once(td,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===ps.PUBLISHER||e===ps.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Sr(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>Sr(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),fa.clearTimeout(r),s(new ia("room connection has been cancelled",$o.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=fa.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new ia("could not establish pc connection",$o.InternalError))}),n);for(;this.state!==hd.CONNECTED;)if(yield Ma(50),null==t?void 0:t.signal.aborted)return void s(new ia("room connection has been cancelled",$o.Cancelled));fa.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class gd extends Error{constructor(e,t,i){super(t),this.code=e,this.message=vd(t,gd.MAX_MESSAGE_BYTES),this.data=i?vd(i,gd.MAX_DATA_BYTES):void 0}static fromProto(e){return new gd(e.code,e.message,e.data)}toProto(){return new Yn({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new gd(gd.ErrorCode[e],gd.ErrorMessage[e],t)}}function fd(e){return(new TextEncoder).encode(e).length}function vd(e,t){if(fd(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}gd.MAX_MESSAGE_BYTES=256,gd.MAX_DATA_BYTES=15360,gd.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},gd.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const yd=2e3;function bd(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class kd extends ka{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Xc((()=>Sr(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Sr(this,void 0,void 0,(function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()})),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(Qo.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new Lt,this.pauseUpstreamLock=new Lt,this.processorLock=new Lt,this.restartLock=new Lt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==ka.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Sr(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Sa(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Ta(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{Ta(null!=n?n:e,t)})))}))}waitForDimensions(){return Sr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===ka.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=ha())||void 0===i?void 0:i.os)&&(yield Ma(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield Ma(50)}throw new sa("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Sr(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===oc(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),oc(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Sr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===ka.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===ka.Kind.Audio?"audioinput":"videoinput";return t?Ic.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return Sr(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Sr(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Sr(this,void 0,void 0,(function*(){if(!this.sender)throw new sa("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(e){return Sr(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===ka.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{Sa(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield r.applyConstraints(n),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(Qo.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}}))}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Qo.Muted:Qo.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Sr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Va()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Sr(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Qo.UpstreamPaused,this);const t=ha();if("Safari"===(null==t?void 0:t.name)&&Wa(t.version,"12.0")<0)throw new na("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return Sr(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Qo.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return Sr(this,void 0,void 0,(function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()}))}setProcessor(e){return Sr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(Ta(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e})))),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(Sa(t._mediaStreamTrack,e),Ta(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Qo.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Sr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Qo.TrackProcessorUpdate))}()}))}}class Td extends kd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,ka.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Sr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=bd(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Qo.AudioTrackFeatureUpdate,this,Pn.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Qo.AudioTrackFeatureUpdate,this,Pn.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Sr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===ka.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Sr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==oc(this._constraints.deviceId);return this.source!==ka.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Sr(this,void 0,void 0,(function*(){let t;if(e){const i=Tc({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Sr(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){qa()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),yd)))}setProcessor(e){return Sr(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!za()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(Qo.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Sr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Sr(this,void 0,void 0,(function*(){const e=yield function(e){return Sr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Sc();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield Ma(t),n.getByteTimeDomainData(r);const o=r.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}()}))}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(Qo.AudioSilenceDetected)),e}))}}const Sd=Object.values(Ia),Cd=Object.values(Aa),wd=Object.values(Na),Ed=[Ia.h180,Ia.h360],_d=[Aa.h180,Aa.h360],Pd=["q","h","f"];function Rd(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return wd;const n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?Sd:Cd}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let a=0;a<s.length;a+=1){const e=s[a];if(r=e.encoding,e.width>=o)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),vr.debug("using video encoding",o));const l=o.maxFramerate,u=new Ca(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&ja(d)){const e=new Ad(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=ha();if(Ba()||za()||"Chrome"===(null==i?void 0:i.name)&&Wa(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:Pd[2-n],maxBitrate:o.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),vr.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(s=Id(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:xd(e,u):null!==(r=Id(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:xd(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return Od(t,i,[e,h,u],l);if(n>=480)return Od(t,i,[e,u],l)}return Od(t,i,[u])}function xd(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new Ca(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?Ed:_d}function Od(e,t,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=Pd.length)return;const o=Math.min(e,t),a={rid:Pd[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=$a()||0===r;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),za()&&"ios"===Ka()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,vr.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),vr.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function Id(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class Ad{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Nd extends kd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,ka.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>Sr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(i){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:i}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=bd(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Lt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!qa())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),yd))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Sr(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=Cr(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Sr(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=Cr(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Sr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==ka.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Sr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==ka.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Sr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=ya.LOW;i<=ya.HIGH;i+=1)t.push(new qs({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return Sr(this,void 0,void 0,(function*(){var t,i,n,s,r;let o;if(e){const t=Tc({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o);try{for(var a,c=!0,d=Cr(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Sr(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Cr(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return Sr(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Sr(this,void 0,void 0,(function*(){var t,i,n,s,r,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Cr(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield Dd(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return Sr(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield Dd(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Sr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Va()&&this.isInBackground&&this.source===ka.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Dd(e,t,i,n,s,r){return Sr(this,void 0,void 0,(function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:o,senderEncodings:t}));let a=!1;const c=ha();if("Chrome"===(null==c?void 0:c.name)&&Wa(null==c?void 0:c.version,"133")>0&&o[0].scalabilityMode){const e=o[0],n=new Ad(e.scalabilityMode);let s=Tn.OFF;if(i.forEach((e=>{e.enabled&&(s===Tn.OFF||e.quality>s)&&(s=e.quality)})),s===Tn.OFF)e.active&&(e.active=!1,a=!0);else if(!e.active||n.spatial!==s+1){a=!0,e.active=!0;const i=new Ad(t[0].scalabilityMode);n.spatial=s+1,n.suffix=i.suffix,1===n.spatial&&(n.suffix=void 0),e.scalabilityMode=n.toString(),e.scaleResolutionDownBy=Math.pow(2,2-s),t[0].maxBitrate&&(e.maxBitrate=t[0].maxBitrate/(e.scaleResolutionDownBy*e.scaleResolutionDownBy))}}else o.forEach(((e,n)=>{var o;let c=null!==(o=e.rid)&&void 0!==o?o:"";""===c&&(c="q");const d=Md(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(a=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),$a()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}));a&&(n.encodings=o,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}}))}function Md(e){switch(e){case"f":default:return ya.HIGH;case"h":return ya.MEDIUM;case"q":return ya.LOW}}function Ld(e,t,i,n){if(!i)return[new jn({quality:ya.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Ad(n),r=[],o="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new jn({quality:Math.min(ya.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(o,c)),height:Math.ceil(t/Math.pow(o,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return r}return i.map((i=>{var n,s,r;const o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Md(null!==(s=i.rid)&&void 0!==s?s:"");return new jn({quality:a,width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Ud="_lossy",jd="_reliable",Fd="leave-reconnect";var $d,Bd,Vd,qd,zd,Zd,Hd,Kd,Gd,Wd,Jd;(Bd=$d||($d={}))[Bd.New=0]="New",Bd[Bd.Connected=1]="Connected",Bd[Bd.Disconnected=2]="Disconnected",Bd[Bd.Reconnecting=3]="Reconnecting",Bd[Bd.Closed=4]="Closed";class Yd extends _r.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ud.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=$d.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=vr,this.handleDataChannel=e=>Sr(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===jd)t.reliableDCSub=i;else{if(i.label!==Ud)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=e=>Sr(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));n=yield e.data.arrayBuffer()}const s=Fn.fromBinary(new Uint8Array(n));"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(Jo.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(Jo.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?$n.LOSSY:$n.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(e===Fd&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=fa.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),n)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Jo.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===$d.Connected&&e();const i=()=>{this.off(Jo.Disconnected,n),e()},n=()=>{this.off(Jo.Restarted,i),t()};this.once(Jo.Restarted,i),this.once(Jo.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Jo.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Uc.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(En.RR_SIGNAL_DISCONNECTED))},this.log=yr(null!==(t=e.loggerName)&&void 0!==t?t:pr.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Fc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Lt,this.dataProcessLock=new Lt,this.dcBufferStatus=new Map([[$n.LOSSY,!0],[$n.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Jo.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Jo.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Jo.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Jo.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Jo.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Jo.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Jo.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Jo.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r,o,a;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(a=null===(o=this.latestJoinResponse)||void 0===o?void 0:o.participant)||void 0===a?void 0:a.sid}}join(e,t,i,n){return Sr(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout((()=>{this.emit(Jo.SignalConnected)}),10),s}catch(s){if(s instanceof ia&&s.reason===$o.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return Sr(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Jo.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return Sr(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return Sr(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new sa("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new ia("publication of local track timed out, no response from server",$o.InternalError))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Sr(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return Sr(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==hd.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new md(n,e.subscriberPrimary,this.loggerOptions),this.emit(Jo.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>Sr(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===hd.CONNECTED){const t=this.pcState===$d.New;this.pcState=$d.Connected,t&&this.emit(Jo.Connected,e)}else t===hd.FAILED&&this.pcState===$d.Connected&&(this.pcState=$d.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?En.RR_SUBSCRIBER_FAILED:En.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===Uc.RECONNECTING,r=[hd.FAILED,hd.CLOSING,hd.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(Jo.Offline)})),this.pcManager.onTrack=e=>{this.emit(Jo.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>Sr(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>Sr(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Jo.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Jo.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Jo.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Jo.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",En.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Ns.DISCONNECT:this.emit(Jo.Disconnected,null==e?void 0:e.reason),this.close();break;case Ns.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Fd);break;case Ns.RESUME:this.handleDisconnect(Fd)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Cn.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ud,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(jd,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,i){return Sr(this,void 0,void 0,(function*(){if(La())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Ua())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new oa("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Sr(this,void 0,void 0,(function*(){if(La())return this.createSimulcastTransceiverSender(e,t,i,n);if(Ua())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new oa("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Sr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new oa("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),pc(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Sr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new oa("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return Sr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new oa("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return Sr(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)vr.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Cn.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:hd.NEW)!==hd.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof oa?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof Qd||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",En.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(Jo.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return Sr(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new oa("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Jo.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Qd;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof ia&&s.reason===$o.NotAllowed)throw new oa("could not reconnect, token might be expired");throw new Qd}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Jo.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Uc.CONNECTED)throw new Qd("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Jo.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}}))}resumeConnection(e){return Sr(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new oa("could not reconnect, url or token not saved");if(!this.pcManager)throw new oa("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Jo.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof ia&&n.reason===$o.NotAllowed)throw new oa("could not reconnect, token might be expired");if(n instanceof ia&&n.reason===$o.LeaveRequest)throw n;throw new Qd(e)}if(this.emit(Jo.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Uc.CONNECTED)throw new Qd("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(Jo.Resumed)}))}waitForPCInitialConnection(e,t){return Sr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new oa("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Sr(this,void 0,void 0,(function*(){this.pcState=$d.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ma(2e3),!this.pcManager)throw new oa("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=$d.Connected}catch(e){throw this.pcState=$d.Disconnected,new ia("could not establish PC connection, ".concat(e.message),$o.InternalError)}}))}publishRpcResponse(e,t,i,n){return Sr(this,void 0,void 0,(function*(){const s=new Fn({destinationIdentities:[e],kind:$n.RELIABLE,value:{case:"rpcResponse",value:new Jn({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,$n.RELIABLE)}))}publishRpcAck(e,t){return Sr(this,void 0,void 0,(function*(){const i=new Fn({destinationIdentities:[e],kind:$n.RELIABLE,value:{case:"rpcAck",value:new Wn({requestId:t})}});yield this.sendDataPacket(i,$n.RELIABLE)}))}sendDataPacket(e,t){return Sr(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>Sr(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(Jo.Closing,n);!this.dcBufferStatus.get(e);)yield Ma(10);this.off(Jo.Closing,n),t()}}))))}ensureDataTransportConnected(e){return Sr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new oa("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new ia("".concat(r," connection not set"),$o.InternalError);let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate();const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield Ma(50)}throw new ia("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()),$o.InternalError)}()}))}ensurePublisherConnected(e){return Sr(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===hd.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Sr(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Sr(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new aa("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(Jo.Closing,n),this.pcManager.publisher.once(id,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,Ea.includes(n)&&t.set(e.payload,i)})),this.emit(Jo.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof aa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",En.RR_UNKNOWN),t(s)}finally{this.off(Jo.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===$n.LOSSY)return this.lossyDCSub;if(e===$n.RELIABLE)return this.reliableDCSub}else{if(e===$n.LOSSY)return this.lossyDC;if(e===$n.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),r=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Ws({answer:s?Bc({sdp:s.sdp,type:s.type}):void 0,offer:r?Bc({sdp:r.sdp,type:r.type}):void 0,subscription:new Rs({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:_c(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Js({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind($n.LOSSY),ps.PUBLISHER),t(this.dataChannelForKind($n.RELIABLE),ps.PUBLISHER),t(this.dataChannelForKind($n.LOSSY,!0),ps.SUBSCRIBER),t(this.dataChannelForKind($n.RELIABLE,!0),ps.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&fa.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){qa()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){qa()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Qd extends Error{}class Xd{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Za(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Sr(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),vr.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Sr(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new ia("Could not fetch region settings: ".concat(t.statusText),401===t.status?$o.NotAllowed:$o.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class el{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class tl extends el{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>Sr(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(t){return{done:!0,value:void 0}}})),return(){return Sr(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return Sr(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var r,o=!0,a=Cr(this);!(e=(r=yield a.next()).done);o=!0){n=r.value,o=!1;const e=n;s.add(e)}}catch(c){t={error:c}}finally{try{o||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return Array.from(s)}))}}class il extends el{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=dc(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>Sr(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(i){return{done:!0,value:void 0}}})),return(){return Sr(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return Sr(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var r,o=!0,a=Cr(this);!(e=(r=yield a.next()).done);o=!0)n=r.value,o=!1,s+=n}catch(c){t={error:c}}finally{try{o||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return s}))}}class nl{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return Sr(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class sl extends nl{}class rl extends nl{}class ol extends ka{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Qo.Muted:Qo.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Qo.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Sr(this,void 0,void 0,(function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),yd)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Qo.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class al extends ol{constructor(e,t,i,n,s,r){super(e,t,ka.Kind.Audio,i,r),this.monitorReceiver=()=>Sr(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=bd(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;za()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(za())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Sr(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(Fa(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&Fa(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(Qo.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(Qo.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Sr(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class cl extends ol{constructor(e,t,i,n,s){super(e,t,ka.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Sr(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=bd(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Xc((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Sa(this._mediaStreamTrack,t):Ta(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new dl(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Sr(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Sr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),r=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==r&&(!r&&Date.now()-i<100?fa.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=r,this.emit(Qo.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Qo.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?Ga():t||(Ga()>2?2:1)}}class dl{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=ll(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ll(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=ll(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:ul(e),this.isPiP=qa()&&ll(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=ul(this.element),this.isPiP=ll(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,tc().observe(this.element),Xa().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=tc())||void 0===e||e.unobserve(this.element),null===(t=Xa())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function ll(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&ul(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function ul(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class hl extends _r.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=Mn.NONE,this.log=vr,this.handleMuted=()=>{this.emit(Qo.Muted)},this.handleUnmuted=()=>{this.emit(Qo.Unmuted)},this.log=yr(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:pr.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=ka.Source.Unknown}setTrack(e){this.track&&(this.track.off(Qo.Muted,this.handleMuted),this.track.off(Qo.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Qo.Muted,this.handleMuted),e.on(Qo.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),Pc(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Mn.NONE}get audioTrack(){if(hc(this.track))return this.track}get videoTrack(){if(pc(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=ka.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===ka.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(qd=(Vd=hl||(hl={})).SubscriptionStatus||(Vd.SubscriptionStatus={})).Desired="desired",qd.Subscribed="subscribed",qd.Unsubscribed="unsubscribed",(zd=Vd.PermissionStatus||(Vd.PermissionStatus={})).Allowed="allowed",zd.NotAllowed="not_allowed";class pl extends hl{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Qo.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Qo.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Qo.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return Sr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Sr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Sr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Sr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(hc(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Pn.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Pn.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Pn.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Pn.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(Pn.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Pn.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function ml(e,t){return Sr(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Rc(e);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}(!0===r.audio||"object"==typeof r.audio&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(!0===r.video||"object"==typeof r.video&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=bc(r,cd,dd),d=Tc(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(Ic.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Ic.userMediaPromiseMap.delete("audioinput")))),r.video&&(Ic.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Ic.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>Sr(this,void 0,void 0,(function*(){const r="audio"===i.kind;let o,a=r?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=i.getSettings().deviceId;(null==o?void 0:o.deviceId)&&oc(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new Td(e,t,!1,void 0,i);case"video":return new Nd(e,t,!1,i);default:throw new sa("unsupported track type: ".concat(e.kind))}}(i,o,t);return h.kind===ka.Kind.Video?h.source=ka.Source.Camera:h.kind===ka.Kind.Audio&&(h.source=ka.Source.Microphone),h.mediaStream=e,hc(h)&&n?yield h.setProcessor(n):pc(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(u){if(!i)throw u;return ml(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}}))}(Hd=Zd||(Zd={})).Excellent="excellent",Hd.Good="good",Hd.Poor="poor",Hd.Lost="lost",Hd.Unknown="unknown";class gl extends _r.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===Nn.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:Nn.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Zd.Unknown,this.log=vr,this.log=yr(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:pr.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(ka.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(ka.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(ka.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version||(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),0))}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(Go.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(Go.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(Go.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,o;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(Go.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Go.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Sn.EXCELLENT:return Zd.Excellent;case Sn.GOOD:return Zd.Good;case Sn.POOR:return Zd.Poor;case Sn.LOST:return Zd.Lost;default:return Zd.Unknown}}(e),t!==this._connectionQuality&&this.emit(Go.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>hc(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(Qo.Muted,(()=>{this.emit(Go.TrackMuted,e)})),e.on(Qo.Unmuted,(()=>{this.emit(Go.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case ka.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case ka.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class fl extends gl{constructor(e,t,i,n,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Mn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new rc)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==sr.OK&&s.reject(new da(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=gd.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Hs({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Pc(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Pc(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Pc(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.handleSubscribedQualityUpdate=e=>Sr(this,void 0,void 0,(function*(){var t,i,n,s,r,o;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(a)if(e.subscribedCodecs.length>0){if(!a.videoTrack)return;const r=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Cr(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;_a(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Pc(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=a.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Sr(this,void 0,void 0,(function*(){if(e.source===ka.Source.ScreenShare||e.source===ka.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Pc(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(gc(e)||mc(e))try{if(qa())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===ka.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),Pc(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Pc(e))),gc(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Pc(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Mn.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(Jo.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),this.engine.on(Jo.Connected,this.handleReconnected).on(Jo.SignalRestarted,this.handleReconnected).on(Jo.SignalResumed,this.handleReconnected).on(Jo.Restarting,this.handleReconnecting).on(Jo.Resuming,this.handleReconnecting).on(Jo.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Jo.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Jo.Disconnected,this.handleDisconnected).on(Jo.SignalRequestResponse,this.handleSignalRequestResponse).on(Jo.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Sr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Sr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Sr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Sr(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>Sr(t,void 0,void 0,(function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield Ma(50)}r(new da("Request to update local metadata timed out","TimeoutError"))}catch(a){a instanceof Error&&r(a)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(ka.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(ka.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(ka.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(Go.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return Sr(this,void 0,void 0,(function*(){this.encryptionType=e?Mn.GCM:Mn.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return Sr(this,void 0,void 0,(function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case ka.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case ka.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case ka.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new sa(e)}}catch(a){throw null==t||t.forEach((e=>{e.stop()})),a instanceof Error&&this.emit(Go.MediaDevicesError,a),this.pendingPublishing.delete(e),a}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Pc(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[o]=i}catch(a){throw null==t||t.forEach((e=>{e.stop()})),a}finally{this.pendingPublishing.delete(e)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===ka.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const e=this.getTrackPublication(ka.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return Sr(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(ka.Source.Camera)&&!this.pendingPublishing.has(ka.Source.Microphone)){this.pendingPublishing.add(ka.Source.Camera),this.pendingPublishing.add(ka.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(ka.Source.Camera),this.pendingPublishing.delete(ka.Source.Microphone)}}}))}createTracks(e){return Sr(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=bc(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield ml(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((e=>(hc(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=ka.Source.Microphone,this.emit(Go.AudioStreamAcquired)),pc(e)&&(this.cameraError=void 0,e.source=ka.Source.Camera),e)))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}}))}createScreenTracks(e){return Sr(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new na("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=ha();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}()||(e.resolution=Na.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=Ba()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new sa("no video track found");const s=new Nd(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=ka.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(Go.AudioStreamAcquired);const e=new Td(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=ka.Source.ScreenShareAudio,r.push(e)}return r}))}publishTrack(e,t){return Sr(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return Sr(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(gc(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),uc(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case ka.Source.Microphone:t="audioinput";break;case ka.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new Td(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Nd(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new sa("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),Pc(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=null==t?void 0:t.forceStereo)&&void 0!==r?r:l;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),Pc(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=t.dtx)&&void 0!==o||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=ha(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Wa(t,e.osVersion)>=0)||"Safari"===e.name&&Wa(t,e.version)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>Sr(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Uc.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Pc(e)}));const i=()=>Sr(this,void 0,void 0,(function*(){try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}));setTimeout((()=>{this.engine.off(Jo.SignalConnected,i),n(new ca("publishing rejected as engine not connected within timeout",408))}),15e3),this.engine.once(Jo.SignalConnected,i),this.engine.on(Jo.Closing,(()=>{this.engine.off(Jo.SignalConnected,i),n(new ca("publishing rejected as engine closed",499))}))}else try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}catch(i){n(i)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()}))}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Pc(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case kn.CAMERA:return ka.Source.Camera;case kn.MICROPHONE:return ka.Source.Microphone;case kn.SCREEN_SHARE:return ka.Source.ScreenShare;case kn.SCREEN_SHARE_AUDIO:return ka.Source.ScreenShareAudio;default:return ka.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Pc(e))),!1)}publish(e,t,i){return Sr(this,void 0,void 0,(function*(){var n,s,r,o,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new ca("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>uc(e)&&t.source===e.source))&&e.source!==ka.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Pc(e))),t.stopMicTrackOnMute&&hc(e)&&(e.stopOnMute=!0),e.source===ka.Source.ScreenShare&&$a()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Ba())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if($a())return!1;if(Ba()){const e=ha();if((null==e?void 0:e.version)&&Wa(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=od),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===Ec(e.mime)))||(t.videoCodec=Ec(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Qo.Muted,this.onTrackMuted),e.on(Qo.Unmuted,this.onTrackUnmuted),e.on(Qo.Ended,this.handleTrackEnded),e.on(Qo.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Qo.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Qo.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new bs({cid:e.mediaStreamTrack.id,name:t.name,type:ka.kindToProto(e.kind),muted:e.isMuted,source:ka.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy});let g;if(e.kind===ka.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(b){const t=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:Ia.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Pc(e)),{dims:i}))}m.width=i.width,m.height=i.height,mc(e)&&(ja(p)&&(e.source===ka.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Pc(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),m.simulcastCodecs=[new ys({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:od}),t.backupCodec&&p!==t.backupCodec.codec&&m.encryption===Mn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new ys({codec:t.backupCodec.codec,cid:""})))),g=Rd(e.source===ka.Source.ScreenShare,m.width,m.height,t),m.layers=Ld(m.width,m.height,g,ja(t.videoCodec))}else e.kind===ka.Kind.Audio&&(g=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new oa("cannot publish track when not connected");const f=()=>Sr(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new oa("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,g),mc(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===ka.Source.ScreenShare||e.constraints.height&&oc(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),g)if($a()&&e.kind===ka.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=g[0])||void 0===n?void 0:n.maxBitrate)?g[0].maxBitrate/1e3:0})}else e.codec&&ja(e.codec)&&(null===(s=g[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:g[0].maxBitrate/1e3});yield this.engine.negotiate()}));let v;if(this.enabledPublishVideoCodecs.length>0)v=(yield Promise.all([this.engine.addTrack(m),f()]))[0];else{let i;if(v=yield this.engine.addTrack(m),v.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===ka.Kind.Video){const n=Ec(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Pc(e)),{codec:n})),t.videoCodec=n,g=Rd(e.source===ka.Source.ScreenShare,m.width,m.height,t))}yield f()}const y=new pl(e.kind,v,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return y.options=t,e.sid=v.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:g,trackInfo:v})),mc(e)?e.startMonitor(this.engine.client):gc(e)&&e.startMonitor(),this.addTrackPublication(y),this.emit(Go.LocalTrackPublished,y),y}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Sr(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==Mn.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new sa("track is not published");if(!mc(e))throw new sa("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&vr.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===ka.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Rd(e.source===ka.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Pc(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new bs({cid:a.mediaStreamTrack.id,type:ka.kindToProto(e.kind),muted:e.isMuted,source:ka.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Ld(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new oa("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Sr(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(e,t){return Sr(this,void 0,void 0,(function*(){var i,n;if(uc(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Pc(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?Pc(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off(Qo.Muted,this.onTrackMuted),e.off(Qo.Unmuted,this.onTrackUnmuted),e.off(Qo.Ended,this.handleTrackEnded),e.off(Qo.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Qo.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Qo.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<hd.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),mc(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case ka.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case ka.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(Go.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return Sr(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Sr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((n,s)=>Sr(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>Sr(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===ka.Source.ScreenShare||t.source===ka.Source.ScreenShareAudio||!gc(t)&&!mc(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(t){s(t)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Sr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?$n.RELIABLE:$n.LOSSY,s=i.destinationIdentities,r=i.topic,o=new Fn({kind:n,value:{case:"user",value:new qn({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.engine.sendDataPacket(o,n)}()}))}publishDtmf(e,t){return Sr(this,void 0,void 0,(function*(){const i=new Fn({kind:$n.RELIABLE,value:{case:"sipDtmf",value:new zn({code:e,digit:t})}});yield this.engine.sendDataPacket(i,$n.RELIABLE)}))}sendChatMessage(e,t){return Sr(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new Fn({value:{case:"chatMessage",value:new Kn(Object.assign(Object.assign({},i),{timestamp:ii.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,$n.RELIABLE),this.emit(Go.ChatMessage,i),i}))}editChatMessage(e,t){return Sr(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new Fn({value:{case:"chatMessage",value:new Kn(Object.assign(Object.assign({},i),{timestamp:ii.parse(i.timestamp),editTimestamp:ii.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,$n.RELIABLE),this.emit(Go.ChatMessage,i),i}))}sendText(e,t){return Sr(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),o=new Array(r?r.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;const s=o.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map(((e,i)=>Sr(this,void 0,void 0,(function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))))),c.info}))}streamText(e){return Sr(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},r=new ls({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:lc(s.timestamp),totalLength:lc(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new cs({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?as.UPDATE:as.CREATE})}}),o=null==e?void 0:e.destinationIdentities,a=new Fn({destinationIdentities:o,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(a,$n.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return Sr(this,void 0,void 0,(function*(){for(const t of function(e){const t=[];let i=(new TextEncoder).encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){yield d.engine.waitForBufferStatusLow($n.RELIABLE);const e=new us({content:t,streamId:n,chunkIndex:lc(c)}),i=new Fn({destinationIdentities:o,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,$n.RELIABLE),c+=1}}))},close(){return Sr(this,void 0,void 0,(function*(){const e=new hs({streamId:n}),t=new Fn({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,$n.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>Sr(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(Jo.Closing,u);const h=new sl(l,s,(()=>this.engine.off(Jo.Closing,u)));return h}))}sendFile(e,t){return Sr(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return Sr(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return Sr(this,void 0,void 0,(function*(){var t,i,n,s,r;const o=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,c={id:o,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new ls({totalLength:lc(null!==(r=c.size)&&void 0!==r?r:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:lc(Date.now()),contentHeader:{case:"byteHeader",value:new ds({name:c.name})}}),l=new Fn({destinationIdentities:a,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(l,$n.RELIABLE);let u=0;const h=new Lt,p=this.engine,m=this.log,g=new WritableStream({write(e){return Sr(this,void 0,void 0,(function*(){const t=yield h.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield p.waitForBufferStatusLow($n.RELIABLE);const n=new Fn({destinationIdentities:a,value:{case:"streamChunk",value:new us({content:t,streamId:o,chunkIndex:lc(u)})}});yield p.sendDataPacket(n,$n.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}}))},close(){return Sr(this,void 0,void 0,(function*(){const e=new hs({streamId:o}),t=new Fn({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield p.sendDataPacket(t,$n.RELIABLE)}))},abort(e){m.error("Sink error:",e)}});return new rl(g,c)}))}performRpc(e){return Sr(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=1e4}=e;return function*(){return new Promise(((e,o)=>Sr(t,void 0,void 0,(function*(){var t,a,c,d;if(fd(s)>15360)return void o(gd.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&Wa(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(gd.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,r-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),o(gd.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),o(gd.builtIn("RESPONSE_TIMEOUT"))}),r);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return Sr(this,void 0,void 0,(function*(){const r=new Fn({destinationIdentities:[e],kind:$n.RELIABLE,value:{case:"rpcRequest",value:new Gn({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,$n.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,gd.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),Pc(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(gc(n)||mc(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return Sr(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield Ma(20)}}))}}class vl extends hl{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ya.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Qo.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new Rs({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Qn({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Qo.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?hl.SubscriptionStatus.Unsubscribed:super.isSubscribed?hl.SubscriptionStatus.Subscribed:hl.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?hl.PermissionStatus.Allowed:hl.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(yc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&yc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Qo.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Qo.VisibilityChanged,this.handleVisibilityChange),n.off(Qo.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Qo.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Qo.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Qo.VisibilityChanged,this.handleVisibilityChange),e.on(Qo.Ended,this.handleEnded),this.emit(Qo.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Qo.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Qo.Muted:Qo.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Qo.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Qo.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===ka.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return yc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new xs({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=ya.HIGH,this.emit(Qo.UpdateSettings,e)}}class yl extends gl{static fromParticipantInfo(e,t,i){return new yl(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r,o){super(t,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:Nn.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Qo.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Pc(e))),this.signalClient.sendUpdateTrackSettings(t)})),e.on(Qo.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Qo.SubscriptionPermissionChanged,(t=>{this.emit(Go.TrackSubscriptionPermissionChanged,e,t)})),e.on(Qo.SubscriptionStatusChanged,(t=>{this.emit(Go.TrackSubscriptionStatusChanged,e,t)})),e.on(Qo.Subscribed,(t=>{this.emit(Go.TrackSubscribed,t,e)})),e.on(Qo.Unsubscribed,(t=>{this.emit(Go.TrackUnsubscribed,t,e)})),e.on(Qo.SubscriptionFailed,(t=>{this.emit(Go.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ka.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ka.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let o,a=this.getTrackPublicationBySid(t);return a||t.startsWith("TR")||this.trackPublications.forEach((t=>{a||e.kind!==t.kind.toString()||(a=t)})),a?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),Pc(a))),void this.emit(Go.TrackSubscriptionFailed,t)):(o="video"===e.kind?new cl(e,t,n,s):new al(e,t,n,this.audioContext,this.audioOutput),o.source=a.source,o.isMuted=a.isMuted,o.setMediaStream(i),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&fc(o)&&hc(o)&&o.setVolume(this.volumeMap.get(a.source)),a):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(Go.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=ka.kindFromProto(e.type);if(!t)return;r=new vl(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));o&&r.source!==ka.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:Pc(o),newTrack:Pc(r)})),this.addTrackPublication(r)}t.set(e.sid,r)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),Pc(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(Go.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case ka.Kind.Audio:this.audioTrackPublications.delete(e);break;case ka.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(Go.TrackUnpublished,i)}setAudioOutput(e){return Sr(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;hc(i.track)&&fc(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(Gd=Kd||(Kd={})).Disconnected="disconnected",Gd.Connecting="connecting",Gd.Connected="connected",Gd.Reconnecting="reconnecting",Gd.SignalReconnecting="signalReconnecting";class bl extends _r.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=Kd.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=vr,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>Sr(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!La()&&!Ua())throw za()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===Kd.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(Kd.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Za(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Xd(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(n,o,a)=>Sr(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof ia&&u.reason!==$o.Cancelled&&u.reason!==$o.NotAllowed){let e=null;try{e=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof ia&&(401===h.status||h.reason===$o.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(h)}e&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(e),this.logContext),this.recreateEngine(),yield r(n,o,e)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,cc(u)),o(u))}else{let e=wn.UNKNOWN_REASON;u instanceof ia&&(e=cc(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(u)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new rc(((e,t)=>{r(e,t,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>Sr(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new ra("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>Sr(this,void 0,void 0,(function*(){var s,r;this.state===Kd.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ud),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Ho.SignalConnected)}catch(o){yield this.engine.close(),this.recreateEngine();const e=new ia("could not establish signal connection",$o.ServerUnreachable);throw o instanceof Error&&(e.message="".concat(e.message,": ").concat(o.message)),o instanceof ia&&(e.reason=o.reason,e.status=o.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:o})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ia("Connection attempt aborted",$o.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(a){throw yield this.engine.close(),this.recreateEngine(),a}qa()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),qa()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Kd.Connected),this.emit(Ho.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return Sr(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,r;const o=yield e.disconnectLock.lock();try{if(e.state===Kd.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===Kd.Connecting||e.state===Kd.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new ia("Client initiated disconnect",$o.Cancelled)),e.connectFuture=void 0),(null===(r=e.engine)||void 0===r?void 0:r.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,wn.CLIENT_INITIATED),e.engine=void 0}finally{o()}}()}))},this.onPageLeave=()=>Sr(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Sr(this,void 0,void 0,(function*(){const e=[],t=ha();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=sc();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(Ho.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...e.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>Sr(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Kd.Reconnecting)&&this.emit(Ho.Reconnecting)},this.handleSignalRestarted=e=>Sr(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(Kd.Connected),this.emit(Ho.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===An.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(Ho.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)})),e.forEach((e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Ho.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=ka.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(Go.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Ho.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(Ho.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(Go.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(Ho.SipDTMFReceived,t,e),null==e||e.emit(Go.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(Qo.TranscriptionReceived,s),null==i||i.emit(Go.TranscriptionReceived,s,n),this.emit(Ho.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(Ho.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(Ho.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Ho.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Ho.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Ho.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Ho.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Sr(this,void 0,void 0,(function*(){var e,t,i;const n=Ic.getInstance().previousDevices,s=yield Ic.getInstance().getDevices(void 0,!1),r=ha();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let a of s){const e=n.find((e=>e.deviceId===a.deviceId));e&&""!==e.label&&e.kind===a.kind&&e.label!==a.label&&"default"===this.getActiveDevice(a.kind)&&this.emit(Ho.ActiveDeviceChanged,a.kind,a.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let a of o){const r=Cc(a),o=this.localParticipant.getTrackPublication(r);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===a)),d=this.getActiveDevice(a);d===(null===(t=n.filter((e=>e.kind===a))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(a,c[0].deviceId):"audioinput"===a&&!Ba()||"videoinput"===a||c.length>0&&!c.find((e=>e.deviceId===this.getActiveDevice(a)))&&(yield this.switchActiveDevice(a,c[0].deviceId))}this.emit(Ho.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Ho.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Ho.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(Ho.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Ho.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Ho.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Ho.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Ho.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>Sr(this,void 0,void 0,(function*(){var t,i,n,s,r,o;null===(t=e.track)||void 0===t||t.on(Qo.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Qo.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(Ho.LocalTrackPublished,e,this.localParticipant),gc(e.track)&&(yield e.track.checkForSilence())&&this.emit(Ho.LocalAudioSilenceDetected,e);const a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),c=wc(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Ho.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Qo.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Qo.Restarted,this.onLocalTrackRestarted),this.emit(Ho.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Sr(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=wc(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(Ho.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(Ho.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Ho.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Ho.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Ho.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},ld),e),this.log=yr(null!==(i=this.options.loggerName)&&void 0!==i?i:pr.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},cd),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},dd),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},ad),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Lt,this.localParticipant=new fl("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",oc(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",oc(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",oc(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),qa()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),bl.cleanupRegistry&&bl.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,i,n,s,r){return Sr(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,gd.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,gd.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});fd(r)>15360?(a=gd.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof gd?a=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),a=gd.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}setE2EEEnabled(e){return Sr(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new xc(this.options.e2ee),this.e2eeManager.on(Uo.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(Ho.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(Uo.EncryptionError,(e=>this.emit(Ho.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Sr(this,void 0,void 0,(function*(){return this.state===Kd.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Jo.RoomUpdate,i),e(t.sid))};this.engine.on(Jo.RoomUpdate,i),this.once(Ho.Disconnected,(()=>{this.engine.off(Jo.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Yd(this.options),this.engine.on(Jo.ParticipantUpdate,this.handleParticipantUpdates).on(Jo.RoomUpdate,this.handleRoomUpdate).on(Jo.SpeakersChanged,this.handleSpeakersChanged).on(Jo.StreamStateChanged,this.handleStreamStateUpdate).on(Jo.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Jo.SubscriptionError,this.handleSubscriptionError).on(Jo.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Jo.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Jo.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Jo.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Jo.DataPacketReceived,this.handleDataPacket).on(Jo.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Kd.SignalReconnecting)&&this.emit(Ho.SignalReconnecting)})).on(Jo.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Kd.Connected)&&this.emit(Ho.Reconnected)})).on(Jo.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Kd.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Jo.Restarting,this.handleRestarting).on(Jo.SignalRestarted,this.handleSignalRestarted).on(Jo.Offline,(()=>{this.setAndEmitConnectionState(Kd.Reconnecting)&&this.emit(Ho.Reconnecting)})).on(Jo.DCBufferStatusChanged,((e,t)=>{this.emit(Ho.DCBufferStatusChanged,e,t)})).on(Jo.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit(Go.LocalTrackSubscribed,t),this.emitWhenConnected(Ho.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ic.getInstance().getDevices(e,t)}prepareConnection(e,t){return Sr(this,void 0,void 0,(function*(){if(this.state===Kd.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Za(new URL(e))&&t){this.regionUrlProvider=new Xd(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Kd.Disconnected&&(this.regionUrl=i,yield fetch(ac(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(ac(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Sr(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Ys({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Ys({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Ys({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Ys({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>Sr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ys({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Sr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Ys({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new Ys({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Sr(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new As({reason:wn.CLIENT_INITIATED,action:Ns.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Ys({scenario:{case:"subscriberBandwidth",value:lc(t)}});break;case"leave-full-reconnect":i=new Ys({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return Sr(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,o,a,c,d,l,u;let h=!0,p=!1;const m=n?{exact:t}:t;if("audioinput"===e){p=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===ka.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.audioCaptureDefaults.deviceId=t,g}}else if("videoinput"===e){p=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===ka.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.videoCaptureDefaults.deviceId=t,g}}else if("audiooutput"===e){if(!Fa()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");i.options.webAudioMix&&(t=null!==(o=yield Ic.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(u=i.options).audioOutput)&&void 0!==a||(u.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(g){throw i.options.audioOutput.deviceId=n,g}}return(p||"audiooutput"===e)&&(i.localParticipant.activeDeviceMap.set(e,"audiooutput"===e&&(null===(l=i.options.audioOutput)||void 0===l?void 0:l.deviceId)||t),i.emit(Ho.ActiveDeviceChanged,e,t)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(Go.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Go.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Go.AttributesChanged,this.onLocalAttributesChanged).on(Go.TrackMuted,this.onLocalTrackMuted).on(Go.TrackUnmuted,this.onLocalTrackUnmuted).on(Go.LocalTrackPublished,this.onLocalTrackPublished).on(Go.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Go.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Go.MediaDevicesError,this.onMediaDevicesError).on(Go.AudioStreamAcquired,this.startAudio).on(Go.ChatMessage,this.onLocalChatMessageSent).on(Go.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Kd.Connecting||this.state===Kd.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(Ho.Reconnected,n),this.off(Ho.Connected,n),this.off(Ho.Disconnected,s)};return this.once(Ho.Reconnected,n),this.once(Ho.Connected,n),void this.once(Ho.Disconnected,s)}if(this.state===Kd.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],o=e.id;if(r&&r.startsWith("TR")&&(o=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(e,o,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Kd.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(Go.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Go.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Go.AttributesChanged,this.onLocalAttributesChanged).off(Go.TrackMuted,this.onLocalTrackMuted).off(Go.TrackUnmuted,this.onLocalTrackUnmuted).off(Go.LocalTrackPublished,this.onLocalTrackPublished).off(Go.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Go.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Go.MediaDevicesError,this.onMediaDevicesError).off(Go.AudioStreamAcquired,this.startAudio).off(Go.ChatMessage,this.onLocalChatMessageSent).off(Go.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),qa()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Kd.Disconnected),this.emit(Ho.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(Ho.ParticipantDisconnected,t),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return Sr(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const r={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:dc(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now()})}});n(new tl(r,o,dc(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},r=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new il(s,r,dc(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return Sr(this,void 0,void 0,(function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Sc())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Ma(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Ho.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?yl.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new yl(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Ho.ParticipantConnected,i),i.on(Go.TrackPublished,(e=>{this.emitWhenConnected(Ho.TrackPublished,e,i)})).on(Go.TrackSubscribed,((e,t)=>{e.kind===ka.Kind.Audio?(e.on(Qo.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Qo.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===ka.Kind.Video&&(e.on(Qo.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Qo.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Ho.TrackSubscribed,e,t,i)})).on(Go.TrackUnpublished,(e=>{this.emit(Ho.TrackUnpublished,e,i)})).on(Go.TrackUnsubscribed,((e,t)=>{this.emit(Ho.TrackUnsubscribed,e,t,i)})).on(Go.TrackMuted,(e=>{this.emitWhenConnected(Ho.TrackMuted,e,i)})).on(Go.TrackUnmuted,(e=>{this.emitWhenConnected(Ho.TrackUnmuted,e,i)})).on(Go.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Ho.ParticipantMetadataChanged,e,i)})).on(Go.ParticipantNameChanged,(e=>{this.emitWhenConnected(Ho.ParticipantNameChanged,e,i)})).on(Go.AttributesChanged,(e=>{this.emitWhenConnected(Ho.ParticipantAttributesChanged,e,i)})).on(Go.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Ho.ConnectionQualityChanged,e,i)})).on(Go.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Ho.ParticipantPermissionsChanged,e,i)})).on(Go.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Ho.TrackSubscriptionStatusChanged,e,t,i)})).on(Go.TrackSubscriptionFailed,((e,t)=>{this.emit(Ho.TrackSubscriptionFailed,e,i,t)})).on(Go.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Ho.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&vc(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=fa.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,wn.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&fa.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Ho.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Kd.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Kd.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return Sr(this,void 0,void 0,(function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Rn({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ii.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new In({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Ho.SignalConnected),this.emit(Ho.Connected),this.setAndEmitConnectionState(Kd.Connected),n.video){const e=new pl(ka.Kind.Video,new Un({source:kn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:bn.AUDIO,name:"video-dummy"}),new Nd(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ic(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Go.LocalTrackPublished,e)}if(n.audio){const e=new pl(ka.Kind.Audio,new Un({source:kn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:bn.AUDIO}),new Td(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:sc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Go.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new In({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:An.ACTIVE,tracks:[],joinedAt:ii.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=ic(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),o=new Un({source:kn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:bn.AUDIO});n.addSubscribedMediaTrack(r,o.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(s.audio){const e=sc(),i=new Un({source:kn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:bn.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==Ho.ActiveSpeakersChanged&&e!==Ho.TranscriptionReceived){const t=kl(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function kl(e){return e.map((e=>{if(e)return Array.isArray(e)?kl(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}bl.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),(Jd=Wd||(Wd={}))[Jd.IDLE=0]="IDLE",Jd[Jd.RUNNING=1]="RUNNING",Jd[Jd.SKIPPED=2]="SKIPPED",Jd[Jd.SUCCESS=3]="SUCCESS",Jd[Jd.FAILED=4]="FAILED",_r.EventEmitter,_r.EventEmitter;const Tl=Symbol.for("@ts-pattern/matcher"),Sl=Symbol.for("@ts-pattern/isVariadic"),Cl="@ts-pattern/anonymous-select-key",wl=e=>Boolean(e&&"object"==typeof e),El=e=>e&&!!e[Tl],_l=(e,t,i)=>{if(El(e)){const n=e[Tl](),{matched:s,selections:r}=n.match(t);return s&&r&&Object.keys(r).forEach((e=>i(e,r[e]))),s}if(wl(e)){if(!wl(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=[],s=[],r=[];for(const t of e.keys()){const i=e[t];El(i)&&i[Sl]?r.push(i):r.length?s.push(i):n.push(i)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(t.length<n.length+s.length)return!1;const e=t.slice(0,n.length),o=0===s.length?[]:t.slice(-s.length),a=t.slice(n.length,0===s.length?1/0:-s.length);return n.every(((t,n)=>_l(t,e[n],i)))&&s.every(((e,t)=>_l(e,o[t],i)))&&(0===r.length||_l(r[0],a,i))}return e.length===t.length&&e.every(((e,n)=>_l(e,t[n],i)))}return Reflect.ownKeys(e).every((n=>{const s=e[n];return(n in t||El(r=s)&&"optional"===r[Tl]().matcherType)&&_l(s,t[n],i);var r}))}return Object.is(t,e)},Pl=e=>{var t,i,n;return wl(e)?El(e)?null!=(t=null==(i=(n=e[Tl]()).getSelectionKeys)?void 0:i.call(n))?t:[]:Array.isArray(e)?Rl(e,Pl):Rl(Object.values(e),Pl):[]},Rl=(e,t)=>e.reduce(((e,i)=>e.concat(t(i))),[]);function xl(e){return Object.assign(e,{optional:()=>Il(e),and:t=>Dl(e,t),or:t=>Ml(e,t),select:t=>void 0===t?Ul(e):Ul(t,e)})}function Ol(e){return Object.assign((t=e,Object.assign(t,{[Symbol.iterator](){let e=0;const i=[{value:Object.assign(t,{[Sl]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var t;return null!=(t=i[e++])?t:i.at(-1)}}}})),{optional:()=>Ol(Il(e)),select:t=>Ol(void 0===t?Ul(e):Ul(t,e))});var t}function Il(e){return xl({[Tl]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return void 0===t?(Pl(e).forEach((e=>n(e,void 0))),{matched:!0,selections:i}):{matched:_l(e,t,n),selections:i}},getSelectionKeys:()=>Pl(e),matcherType:"optional"})})}const Al=(e,t)=>{for(const i of e)if(!t(i))return!1;return!0},Nl=(e,t)=>{for(const[i,n]of e.entries())if(!t(n,i))return!1;return!0};function Dl(...e){return xl({[Tl]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return{matched:e.every((e=>_l(e,t,n))),selections:i}},getSelectionKeys:()=>Rl(e,Pl),matcherType:"and"})})}function Ml(...e){return xl({[Tl]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return Rl(e,Pl).forEach((e=>n(e,void 0))),{matched:e.some((e=>_l(e,t,n))),selections:i}},getSelectionKeys:()=>Rl(e,Pl),matcherType:"or"})})}function Ll(e){return{[Tl]:()=>({match:t=>({matched:Boolean(e(t))})})}}function Ul(...e){const t="string"==typeof e[0]?e[0]:void 0,i=2===e.length?e[1]:"string"==typeof e[0]?void 0:e[0];return xl({[Tl]:()=>({match:e=>{let n={[null!=t?t:Cl]:e};return{matched:void 0===i||_l(i,e,((e,t)=>{n[e]=t})),selections:n}},getSelectionKeys:()=>[null!=t?t:Cl].concat(void 0===i?[]:Pl(i))})})}function jl(e){return"number"==typeof e}function Fl(e){return"string"==typeof e}function $l(e){return"bigint"==typeof e}const Bl=xl(Ll((function(e){return!0}))),Vl=Bl,ql=e=>Object.assign(xl(e),{startsWith:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.startsWith(i))))));var i},endsWith:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.endsWith(i))))));var i},minLength:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.length>=i)))));var i},length:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.length===i)))));var i},maxLength:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.length<=i)))));var i},includes:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.includes(i))))));var i},regex:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&Boolean(e.match(i)))))));var i}}),zl=ql(Ll(Fl)),Zl=e=>Object.assign(xl(e),{between:(t,i)=>{return Zl(Dl(e,(n=t,s=i,Ll((e=>jl(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Zl(Dl(e,(i=t,Ll((e=>jl(e)&&e<i)))));var i},gt:t=>{return Zl(Dl(e,(i=t,Ll((e=>jl(e)&&e>i)))));var i},lte:t=>{return Zl(Dl(e,(i=t,Ll((e=>jl(e)&&e<=i)))));var i},gte:t=>{return Zl(Dl(e,(i=t,Ll((e=>jl(e)&&e>=i)))));var i},int:()=>Zl(Dl(e,Ll((e=>jl(e)&&Number.isInteger(e))))),finite:()=>Zl(Dl(e,Ll((e=>jl(e)&&Number.isFinite(e))))),positive:()=>Zl(Dl(e,Ll((e=>jl(e)&&e>0)))),negative:()=>Zl(Dl(e,Ll((e=>jl(e)&&e<0))))}),Hl=Zl(Ll(jl)),Kl=e=>Object.assign(xl(e),{between:(t,i)=>{return Kl(Dl(e,(n=t,s=i,Ll((e=>$l(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Kl(Dl(e,(i=t,Ll((e=>$l(e)&&e<i)))));var i},gt:t=>{return Kl(Dl(e,(i=t,Ll((e=>$l(e)&&e>i)))));var i},lte:t=>{return Kl(Dl(e,(i=t,Ll((e=>$l(e)&&e<=i)))));var i},gte:t=>{return Kl(Dl(e,(i=t,Ll((e=>$l(e)&&e>=i)))));var i},positive:()=>Kl(Dl(e,Ll((e=>$l(e)&&e>0)))),negative:()=>Kl(Dl(e,Ll((e=>$l(e)&&e<0))))}),Gl=Kl(Ll($l)),Wl=xl(Ll((function(e){return"boolean"==typeof e}))),Jl=xl(Ll((function(e){return"symbol"==typeof e}))),Yl=xl(Ll((function(e){return null==e}))),Ql=xl(Ll((function(e){return null!=e})));var Xl={__proto__:null,matcher:Tl,optional:Il,array:function(...e){return Ol({[Tl]:()=>({match:t=>{if(!Array.isArray(t))return{matched:!1};if(0===e.length)return{matched:!0};const i=e[0];let n={};if(0===t.length)return Pl(i).forEach((e=>{n[e]=[]})),{matched:!0,selections:n};const s=(e,t)=>{n[e]=(n[e]||[]).concat([t])};return{matched:t.every((e=>_l(i,e,s))),selections:n}},getSelectionKeys:()=>0===e.length?[]:Pl(e[0])})})},set:function(...e){return xl({[Tl]:()=>({match:t=>{if(!(t instanceof Set))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};if(0===e.length)return{matched:!0};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])},s=e[0];return{matched:Al(t,(e=>_l(s,e,n))),selections:i}},getSelectionKeys:()=>0===e.length?[]:Pl(e[0])})})},map:function(...e){return xl({[Tl]:()=>({match:t=>{if(!(t instanceof Map))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])};if(0===e.length)return{matched:!0};var s;if(1===e.length)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${null==(s=e[0])?void 0:s.toString()}`);const[r,o]=e;return{matched:Nl(t,((e,t)=>{const i=_l(r,t,n),s=_l(o,e,n);return i&&s})),selections:i}},getSelectionKeys:()=>0===e.length?[]:[...Pl(e[0]),...Pl(e[1])]})})},intersection:Dl,union:Ml,not:function(e){return xl({[Tl]:()=>({match:t=>({matched:!_l(e,t,(()=>{}))}),getSelectionKeys:()=>[],matcherType:"not"})})},when:Ll,select:Ul,any:Bl,_:Vl,string:zl,number:Hl,bigint:Gl,boolean:Wl,symbol:Jl,nullish:Yl,nonNullable:Ql,instanceOf:function(e){return xl(Ll((t=e,e=>e instanceof t)));var t},shape:function(e){return xl(Ll(function(...e){if(1===e.length){const[t]=e;return e=>_l(t,e,(()=>{}))}if(2===e.length){const[t,i]=e;return _l(t,i,(()=>{}))}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${e.length}.`)}(e)))}};let eu=class extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch(i){t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}};const tu={matched:!1,value:void 0};function iu(e){return new nu(e,tu)}let nu=class e{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...t){if(this.state.matched)return this;const i=t[t.length-1],n=[t[0]];let s;3===t.length&&"function"==typeof t[1]?s=t[1]:t.length>2&&n.push(...t.slice(1,t.length-1));let r=!1,o={};const a=(e,t)=>{r=!0,o[e]=t},c=!n.some((e=>_l(e,this.input,a)))||s&&!Boolean(s(this.input))?tu:{matched:!0,value:i(r?Cl in o?o[Cl]:o:this.input,this.input)};return new e(this.input,c)}when(t,i){if(this.state.matched)return this;const n=Boolean(t(this.input));return new e(this.input,n?{matched:!0,value:i(this.input,this.input)}:tu)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=su){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function su(e){throw new eu(e)}class ru{constructor(e={}){this.currentState=Ot.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=It(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token)return console.error("No token found"),void this.emitter.emit("error",{session:this,error:new Error("No session token provided")});await this.requestMicrophone();try{this.room=new bl({adaptiveStream:!0,dynacast:!0}),this.room.on(Ho.LocalTrackUnpublished,(e=>{console.log("Local track unpublished",e.source),e.source===ka.Source.ScreenShare&&(this.screenStream=void 0)})),this.room.on(Ho.Disconnected,(()=>{console.log("LiveKit room disconnected"),this.disconnect()})),this.room.on(Ho.ParticipantDisconnected,(()=>{this.disconnect()})),this.room.on(Ho.TrackSubscribed,((e,t,i)=>{if("audio"===e.kind&&e.attach(),e.source===ka.Source.Microphone&&i.identity.includes("agent-")){const t=e.mediaStream;if(!t)return void console.error("No media stream available for assistant track");const i=new AudioContext,n=i.createAnalyser();i.createMediaStreamSource(t).connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"ASSISTANT"),this.assistantAudioContext=i}})),this.room.on(Ho.ParticipantAttributesChanged,(e=>{if(!e["lk.agent.state"])return;if(this.currentState===Ot.RESEARCHING||this.currentState===Ot.PAUSED)return;const t=iu(e["lk.agent.state"]).with("listening",(()=>Ot.USER_SPEAKING)).with("speaking",(()=>Ot.AGENT_SPEAKING)).with("thinking",(()=>Ot.AGENT_SPEAKING)).otherwise((()=>{}));t&&this.setState(t)})),this.room.on(Ho.DataReceived,(async e=>{try{const t=JSON.parse((new TextDecoder).decode(e));iu(t.status||t.request).with("using_tool",(()=>{const e=this.currentState;this.currentState=Ot.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("using_tool_ended",(()=>{const e=this.currentState;this.currentState=Ot.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("share_screen",(()=>{this.shareScreen()})).with("prompt_user",(()=>{this.promptContinue()})).with("capture_page_html",(()=>{this.emitter.emit("capturePageHTML",{session:this})})).otherwise((()=>{console.warn("Unknown data received:",t)}))}catch(t){console.error("Error parsing data:",t)}}));const e=`${this.apiBaseUrl}/join-token?token=${this.token}`,t=await fetch(e).then((e=>e.json()));if(await this.room.connect(t.url,t.token),this.microphoneStream){const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:ka.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){this.room&&this.room.disconnect(!0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach((e=>e.stop())),this.setState(Ot.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),n=t.createMediaStreamSource(e),s=t.createGain();s.gain.value=1.5,n.connect(s),s.connect(i),i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,r,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream)return void console.warn("Failed to share screen");await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){this.room&&(this.setState(Ot.PAUSED),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!1))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!1)),this.screenStream?.track?.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){this.room&&(this.setState(Ot.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleUnmuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!0))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!0)),this.screenStream?.track?.unmute())}async promptContinue(){await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const n=t.reduce(((e,t)=>e+t),0)/t.length,s=Math.max(.01,Math.min(1,n/128));"USER"===i&&this.currentState===Ot.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:s}):"ASSISTANT"===i&&this.currentState===Ot.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:s}),setTimeout((()=>this.analyzeAudio(e,t,i)),50)}async sendHTML(e){if(this.room)try{const t={type:"page_content",html:e,timestamp:(new Date).toISOString()},i=JSON.stringify(t),n=(new TextEncoder).encode(i);await this.room.localParticipant.publishData(n,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}else console.log("Cannot send HTML: Not connected to LiveKit room")}}const ou=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:ru},Symbol.toStringTag,{value:"Module"})),au=globalThis,cu=au.ShadowRoot&&(void 0===au.ShadyCSS||au.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,du=Symbol(),lu=new WeakMap;let uu=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==du)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(cu&&void 0===e){const i=void 0!==t&&1===t.length;i&&(e=lu.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&lu.set(t,e))}return e}toString(){return this.cssText}};const hu=(e,...t)=>{const i=1===e.length?e[0]:t.reduce(((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1]),e[0]);return new uu(i,e,du)},pu=cu?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new uu("string"==typeof e?e:e+"",void 0,du))(t)})(e):e,{is:mu,defineProperty:gu,getOwnPropertyDescriptor:fu,getOwnPropertyNames:vu,getOwnPropertySymbols:yu,getPrototypeOf:bu}=Object,ku=globalThis,Tu=ku.trustedTypes,Su=Tu?Tu.emptyScript:"",Cu=ku.reactiveElementPolyfillSupport,wu=(e,t)=>e,Eu={toAttribute(e,t){switch(t){case Boolean:e=e?Su:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(n){i=null}}return i}},_u=(e,t)=>!mu(e,t),Pu={attribute:!0,type:String,converter:Eu,reflect:!1,useDefault:!1,hasChanged:_u};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ku.litPropertyMetadata??(ku.litPropertyMetadata=new WeakMap);let Ru=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Pu){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&gu(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:s}=fu(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const r=n?.call(this);s?.call(this,t),this.requestUpdate(e,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Pu}static _$Ei(){if(this.hasOwnProperty(wu("elementProperties")))return;const e=bu(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(wu("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(wu("properties"))){const e=this.properties,t=[...vu(e),...yu(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const e=this._$Eu(t,i);void 0!==e&&this._$Eh.set(e,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(pu(e))}else void 0!==e&&t.push(pu(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??(this._$EO=new Set)).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(cu)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const i of t){const t=document.createElement("style"),n=au.litNonce;void 0!==n&&t.setAttribute("nonce",n),t.textContent=i.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const s=(void 0!==i.converter?.toAttribute?i.converter:Eu).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(n):this.setAttribute(n,s),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:Eu;this._$Em=n,this[n]=s.fromAttribute(t,e.type)??this._$Ej?.get(n)??null,this._$Em=null}}requestUpdate(e,t,i){if(void 0!==e){const n=this.constructor,s=this[e];if(i??(i=n.getPropertyOptions(e)),!((i.hasChanged??_u)(s,t)||i.useDefault&&i.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(n._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:s},r){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,r??t??this[e]),!0!==s||void 0!==r)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(e){}firstUpdated(e){}};Ru.elementStyles=[],Ru.shadowRootOptions={mode:"open"},Ru[wu("elementProperties")]=new Map,Ru[wu("finalized")]=new Map,Cu?.({ReactiveElement:Ru}),(ku.reactiveElementVersions??(ku.reactiveElementVersions=[])).push("2.1.0");const xu=globalThis,Ou=xu.trustedTypes,Iu=Ou?Ou.createPolicy("lit-html",{createHTML:e=>e}):void 0,Au="$lit$",Nu=`lit$${Math.random().toFixed(9).slice(2)}$`,Du="?"+Nu,Mu=`<${Du}>`,Lu=document,Uu=()=>Lu.createComment(""),ju=e=>null===e||"object"!=typeof e&&"function"!=typeof e,Fu=Array.isArray,$u="[ \t\n\f\r]",Bu=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Vu=/-->/g,qu=/>/g,zu=RegExp(`>|${$u}(?:([^\\s"'>=/]+)(${$u}*=${$u}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),Zu=/'/g,Hu=/"/g,Ku=/^(?:script|style|textarea|title)$/i,Gu=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),Wu=Gu(1),Ju=Gu(2),Yu=Symbol.for("lit-noChange"),Qu=Symbol.for("lit-nothing"),Xu=new WeakMap,eh=Lu.createTreeWalker(Lu,129);function th(e,t){if(!Fu(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==Iu?Iu.createHTML(t):t}let ih=class e{constructor({strings:t,_$litType$:i},n){let s;this.parts=[];let r=0,o=0;const a=t.length-1,c=this.parts,[d,l]=((e,t)=>{const i=e.length-1,n=[];let s,r=2===t?"<svg>":3===t?"<math>":"",o=Bu;for(let a=0;a<i;a++){const t=e[a];let i,c,d=-1,l=0;for(;l<t.length&&(o.lastIndex=l,c=o.exec(t),null!==c);)l=o.lastIndex,o===Bu?"!--"===c[1]?o=Vu:void 0!==c[1]?o=qu:void 0!==c[2]?(Ku.test(c[2])&&(s=RegExp("</"+c[2],"g")),o=zu):void 0!==c[3]&&(o=zu):o===zu?">"===c[0]?(o=s??Bu,d=-1):void 0===c[1]?d=-2:(d=o.lastIndex-c[2].length,i=c[1],o=void 0===c[3]?zu:'"'===c[3]?Hu:Zu):o===Hu||o===Zu?o=zu:o===Vu||o===qu?o=Bu:(o=zu,s=void 0);const u=o===zu&&e[a+1].startsWith("/>")?" ":"";r+=o===Bu?t+Mu:d>=0?(n.push(i),t.slice(0,d)+Au+t.slice(d)+Nu+u):t+Nu+(-2===d?a:u)}return[th(e,r+(e[i]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]})(t,i);if(this.el=e.createElement(d,n),eh.currentNode=this.el.content,2===i||3===i){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(s=eh.nextNode())&&c.length<a;){if(1===s.nodeType){if(s.hasAttributes())for(const e of s.getAttributeNames())if(e.endsWith(Au)){const t=l[o++],i=s.getAttribute(e).split(Nu),n=/([.?@])?(.*)/.exec(t);c.push({type:1,index:r,name:n[2],strings:i,ctor:"."===n[1]?ah:"?"===n[1]?ch:"@"===n[1]?dh:oh}),s.removeAttribute(e)}else e.startsWith(Nu)&&(c.push({type:6,index:r}),s.removeAttribute(e));if(Ku.test(s.tagName)){const e=s.textContent.split(Nu),t=e.length-1;if(t>0){s.textContent=Ou?Ou.emptyScript:"";for(let i=0;i<t;i++)s.append(e[i],Uu()),eh.nextNode(),c.push({type:2,index:++r});s.append(e[t],Uu())}}}else if(8===s.nodeType)if(s.data===Du)c.push({type:2,index:r});else{let e=-1;for(;-1!==(e=s.data.indexOf(Nu,e+1));)c.push({type:7,index:r}),e+=Nu.length-1}r++}}static createElement(e,t){const i=Lu.createElement("template");return i.innerHTML=e,i}};function nh(e,t,i=e,n){if(t===Yu)return t;let s=void 0!==n?i._$Co?.[n]:i._$Cl;const r=ju(t)?void 0:t._$litDirective$;return s?.constructor!==r&&(s?._$AO?.(!1),void 0===r?s=void 0:(s=new r(e),s._$AT(e,i,n)),void 0!==n?(i._$Co??(i._$Co=[]))[n]=s:i._$Cl=s),void 0!==s&&(t=nh(e,s._$AS(e,t.values),s,n)),t}let sh=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,n=(e?.creationScope??Lu).importNode(t,!0);eh.currentNode=n;let s=eh.nextNode(),r=0,o=0,a=i[0];for(;void 0!==a;){if(r===a.index){let t;2===a.type?t=new rh(s,s.nextSibling,this,e):1===a.type?t=new a.ctor(s,a.name,a.strings,this,e):6===a.type&&(t=new lh(s,this,e)),this._$AV.push(t),a=i[++o]}r!==a?.index&&(s=eh.nextNode(),r++)}return eh.currentNode=Lu,n}p(e){let t=0;for(const i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}},rh=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,n){this.type=2,this._$AH=Qu,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=nh(this,e,t),ju(e)?e===Qu||null==e||""===e?(this._$AH!==Qu&&this._$AR(),this._$AH=Qu):e!==this._$AH&&e!==Yu&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>Fu(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==Qu&&ju(this._$AH)?this._$AA.nextSibling.data=e:this.T(Lu.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=ih.createElement(th(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new sh(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=Xu.get(e.strings);return void 0===t&&Xu.set(e.strings,t=new ih(e)),t}k(t){Fu(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let n,s=0;for(const r of t)s===i.length?i.push(n=new e(this.O(Uu()),this.O(Uu()),this,this.options)):n=i[s],n._$AI(r),s++;s<i.length&&(this._$AR(n&&n._$AB.nextSibling,s),i.length=s)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e&&e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}};class oh{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,n,s){this.type=1,this._$AH=Qu,this._$AN=void 0,this.element=e,this.name=t,this._$AM=n,this.options=s,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Qu}_$AI(e,t=this,i,n){const s=this.strings;let r=!1;if(void 0===s)e=nh(this,e,t,0),r=!ju(e)||e!==this._$AH&&e!==Yu,r&&(this._$AH=e);else{const n=e;let o,a;for(e=s[0],o=0;o<s.length-1;o++)a=nh(this,n[i+o],t,o),a===Yu&&(a=this._$AH[o]),r||(r=!ju(a)||a!==this._$AH[o]),a===Qu?e=Qu:e!==Qu&&(e+=(a??"")+s[o+1]),this._$AH[o]=a}r&&!n&&this.j(e)}j(e){e===Qu?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}let ah=class extends oh{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Qu?void 0:e}},ch=class extends oh{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Qu)}},dh=class extends oh{constructor(e,t,i,n,s){super(e,t,i,n,s),this.type=5}_$AI(e,t=this){if((e=nh(this,e,t,0)??Qu)===Yu)return;const i=this._$AH,n=e===Qu&&i!==Qu||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==Qu&&(i===Qu||n);n&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},lh=class{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){nh(this,e)}};const uh=xu.litHtmlPolyfillSupport;uh?.(ih,rh),(xu.litHtmlVersions??(xu.litHtmlVersions=[])).push("3.3.0");const hh=globalThis;let ph=class extends Ru{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,i)=>{const n=i?.renderBefore??t;let s=n._$litPart$;if(void 0===s){const e=i?.renderBefore??null;n._$litPart$=s=new rh(t.insertBefore(Uu(),e),e,void 0,i??{})}return s._$AI(e),s})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Yu}};ph._$litElement$=!0,ph.finalized=!0,hh.litElementHydrateSupport?.({LitElement:ph});const mh=hh.litElementPolyfillSupport;mh?.({LitElement:ph}),(hh.litElementVersions??(hh.litElementVersions=[])).push("4.2.0");const gh={attribute:!0,type:String,converter:Eu,reflect:!1,hasChanged:_u},fh=(e=gh,t,i)=>{const{kind:n,metadata:s}=i;let r=globalThis.litPropertyMetadata.get(s);if(void 0===r&&globalThis.litPropertyMetadata.set(s,r=new Map),"setter"===n&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),"accessor"===n){const{name:n}=i;return{set(i){const s=t.get.call(this);t.set.call(this,i),this.requestUpdate(n,s,e)},init(t){return void 0!==t&&this.C(n,void 0,e,t),t}}}if("setter"===n){const{name:n}=i;return function(i){const s=this[n];t.call(this,i),this.requestUpdate(n,s,e)}}throw Error("Unsupported decorator location: "+n)};function vh(e){return(t,i)=>"object"==typeof i?fh(e,t,i):((e,t,i)=>{const n=t.hasOwnProperty(i);return t.constructor.createProperty(i,e),n?Object.getOwnPropertyDescriptor(t,i):void 0})(e,t,i)}function yh(e){return vh({...e,state:!0,attribute:!1})}var bh=Object.defineProperty,kh=Object.getOwnPropertyDescriptor,Th=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?kh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&bh(t,i,r),r};class Sh extends ph{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return Wu`
1
+ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assertIs=function(e){},i.assertNever=function(e){throw new Error},i.arrayToEnum=e=>{const t={};for(const i of e)t[i]=i;return t},i.getValidEnumValues=e=>{const t=i.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),n={};for(const i of t)n[i]=e[i];return i.objectValues(n)},i.objectValues=e=>i.objectKeys(e).map((function(t){return e[t]})),i.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.push(i);return t},i.find=(e,t)=>{for(const i of e)if(t(i))return i},i.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,i.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},i.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(n||(n={})).mergeShapes=(e,t)=>({...e,...t});const s=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),r=e=>{switch(typeof e){case"undefined":return s.undefined;case"string":return s.string;case"number":return isNaN(e)?s.nan:s.number;case"boolean":return s.boolean;case"function":return s.function;case"bigint":return s.bigint;case"symbol":return s.symbol;case"object":return Array.isArray(e)?s.array:null===e?s.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?s.promise:"undefined"!=typeof Map&&e instanceof Map?s.map:"undefined"!=typeof Set&&e instanceof Set?s.set:"undefined"!=typeof Date&&e instanceof Date?s.date:s.object;default:return s.unknown}},o=t.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class a extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},i={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)i._errors.push(t(s));else{let e=i,n=0;for(;n<s.path.length;){const i=s.path[n];n===s.path.length-1?(e[i]=e[i]||{_errors:[]},e[i]._errors.push(t(s))):e[i]=e[i]||{_errors:[]},e=e[i],n++}}};return n(this),i}static assert(e){if(!(e instanceof a))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},i=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}a.create=e=>new a(e);const c=(e,i)=>{let n;switch(e.code){case o.invalid_type:n=e.received===s.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case o.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,t.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:n=`Unrecognized key(s) in object: ${t.joinValues(e.keys,", ")}`;break;case o.invalid_union:n="Invalid input";break;case o.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${t.joinValues(e.options)}`;break;case o.invalid_enum_value:n=`Invalid enum value. Expected ${t.joinValues(e.options)}, received '${e.received}'`;break;case o.invalid_arguments:n="Invalid function arguments";break;case o.invalid_return_type:n="Invalid function return type";break;case o.invalid_date:n="Invalid date";break;case o.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:t.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case o.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case o.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case o.custom:n="Invalid input";break;case o.invalid_intersection_types:n="Intersection results could not be merged";break;case o.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case o.not_finite:n="Number must be finite";break;default:n=i.defaultError,t.assertNever(e)}return{message:n}};let d=c;function l(){return d}const u=e=>{const{data:t,path:i,errorMaps:n,issueData:s}=e,r=[...i,...s.path||[]],o={...s,path:r};if(void 0!==s.message)return{...s,path:r,message:s.message};let a="";const c=n.filter((e=>!!e)).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...s,path:r,message:a}};function h(e,t){const i=l(),n=u({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,i,i===c?void 0:c].filter((e=>!!e))});e.common.issues.push(n)}class p{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const n of t){if("aborted"===n.status)return m;"dirty"===n.status&&e.dirty(),i.push(n.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const n of t){const e=await n.key,t=await n.value;i.push({key:e,value:t})}return p.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return m;if("aborted"===s.status)return m;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(i[t.value]=s.value)}return{status:e.value,value:i}}}const m=Object.freeze({status:"aborted"}),g=e=>({status:"dirty",value:e}),f=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,y=e=>"dirty"===e.status,b=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;function T(e,t,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(e):n?n.value:t.get(e)}function S(e,t,i,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,i):s?s.value=i:t.set(e,i),i}var C,w,E,_;"function"==typeof SuppressedError&&SuppressedError,(w=C||(C={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},w.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class P{constructor(e,t,i,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const R=(e,t)=>{if(b(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new a(e.common.issues);return this._error=t,this._error}}};function x(e){if(!e)return{};const{errorMap:t,invalid_type_error:i,required_error:n,description:s}=e;if(t&&(i||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{var r,o;const{message:a}=e;return"invalid_enum_value"===t.code?{message:null!=a?a:s.defaultError}:void 0===s.data?{message:null!==(r=null!=a?a:n)&&void 0!==r?r:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(o=null!=a?a:i)&&void 0!==o?o:s.defaultError}},description:s}}class O{get description(){return this._def.description}_getType(e){return r(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new p,ctx:{common:e.parent.common,data:e.data,parsedType:r(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const n={common:{issues:[],async:null!==(i=null==t?void 0:t.async)&&void 0!==i&&i,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},s=this._parseSync({data:e,path:n.path,parent:n});return R(n,s)}"~validate"(e){var t,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return b(t)?{value:t.value}:{issues:n.common.issues}}catch(s){(null===(i=null===(t=null==s?void 0:s.message)||void 0===t?void 0:t.toLowerCase())||void 0===i?void 0:i.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>b(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:r(e)},n=this._parse({data:e,path:i.path,parent:i}),s=await(k(n)?n:Promise.resolve(n));return R(i,s)}refine(e,t){const i=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const s=e(t),r=()=>n.addIssue({code:o.custom,...i(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(r(),!1))):!!s||(r(),!1)}))}refinement(e,t){return this._refinement(((i,n)=>!!e(i)||(n.addIssue("function"==typeof t?t(i,n):t),!1)))}_refinement(e){return new Oe({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ie.create(this,this._def)}nullable(){return Ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ue.create(this)}promise(){return xe.create(this,this._def)}or(e){return me.create([this,e],this._def)}and(e){return ye.create(this,e,this._def)}transform(e){return new Oe({...x(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ne({...x(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new Ue({typeName:qe.ZodBranded,type:this,...x(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new De({...x(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return je.create(this,e)}readonly(){return Fe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const I=/^c[^\s-]{8,}$/i,A=/^[0-9a-z]+$/,N=/^[0-9A-HJKMNP-TV-Z]{26}$/i,D=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,M=/^[a-z0-9_-]{21}$/i,L=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,U=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,j=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let F;const $=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,B=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,V=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,q=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,z=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,K=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Z="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",H=new RegExp(`^${Z}$`);function G(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function W(e){let t=`${Z}T${G(e)}`;const i=[];return i.push(e.local?"Z?":"Z"),e.offset&&i.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function J(e,t){if(!L.test(e))return!1;try{const[i]=e.split("."),n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||!s.typ||!s.alg||t&&s.alg!==t)}catch(i){return!1}}function Y(e,t){return!("v4"!==t&&t||!B.test(e))||!("v6"!==t&&t||!q.test(e))}class Q extends O{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==s.string){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.string,received:t.parsedType}),m}const i=new p;let n;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if("max"===s.kind)e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if("length"===s.kind){const t=e.data.length>s.value,r=e.data.length<s.value;(t||r)&&(n=this._getOrReturnCtx(e,n),t?h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):r&&h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),i.dirty())}else if("email"===s.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"email",code:o.invalid_string,message:s.message}),i.dirty());else if("emoji"===s.kind)F||(F=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),F.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"emoji",code:o.invalid_string,message:s.message}),i.dirty());else if("uuid"===s.kind)D.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"uuid",code:o.invalid_string,message:s.message}),i.dirty());else if("nanoid"===s.kind)M.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"nanoid",code:o.invalid_string,message:s.message}),i.dirty());else if("cuid"===s.kind)I.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"cuid",code:o.invalid_string,message:s.message}),i.dirty());else if("cuid2"===s.kind)A.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"cuid2",code:o.invalid_string,message:s.message}),i.dirty());else if("ulid"===s.kind)N.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"ulid",code:o.invalid_string,message:s.message}),i.dirty());else if("url"===s.kind)try{new URL(e.data)}catch(c){n=this._getOrReturnCtx(e,n),h(n,{validation:"url",code:o.invalid_string,message:s.message}),i.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"regex",code:o.invalid_string,message:s.message}),i.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()):"datetime"===s.kind?W(s).test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:"datetime",message:s.message}),i.dirty()):"date"===s.kind?H.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:"date",message:s.message}),i.dirty()):"time"===s.kind?new RegExp(`^${G(s)}$`).test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:o.invalid_string,validation:"time",message:s.message}),i.dirty()):"duration"===s.kind?U.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"duration",code:o.invalid_string,message:s.message}),i.dirty()):"ip"===s.kind?(r=e.data,("v4"!==(a=s.version)&&a||!$.test(r))&&("v6"!==a&&a||!V.test(r))&&(n=this._getOrReturnCtx(e,n),h(n,{validation:"ip",code:o.invalid_string,message:s.message}),i.dirty())):"jwt"===s.kind?J(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"jwt",code:o.invalid_string,message:s.message}),i.dirty()):"cidr"===s.kind?Y(e.data,s.version)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"cidr",code:o.invalid_string,message:s.message}),i.dirty()):"base64"===s.kind?z.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"base64",code:o.invalid_string,message:s.message}),i.dirty()):"base64url"===s.kind?K.test(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{validation:"base64url",code:o.invalid_string,message:s.message}),i.dirty()):t.assertNever(s);var r,a;return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement((t=>e.test(t)),{validation:t,code:o.invalid_string,...C.errToObj(i)})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){var t,i;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(i=null==e?void 0:e.local)&&void 0!==i&&i,...C.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...C.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...C.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...C.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...C.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...C.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...C.errToObj(t)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new Q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Q({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function X(e,t){const i=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=i>n?i:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}Q.create=e=>{var t;return new Q({checks:[],typeName:qe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class ee extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==s.number){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.number,received:t.parsedType}),m}let i;const n=new p;for(const s of this._def.checks)"int"===s.kind?t.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:o.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"multipleOf"===s.kind?0!==X(e.data,s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),h(i,{code:o.not_finite,message:s.message}),n.dirty()):t.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,n){return new ee({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(n)}]})}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&t.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;"min"===i.kind?(null===t||i.value>t)&&(t=i.value):"max"===i.kind&&(null===e||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ee.create=e=>new ee({checks:[],typeName:qe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class te extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(r){return this._getInvalidInput(e)}if(this._getType(e)!==s.bigint)return this._getInvalidInput(e);let i;const n=new p;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),h(i,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):t.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,n){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(n)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}te.create=e=>{var t;return new te({checks:[],typeName:qe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...x(e)})};class ie extends O{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==s.boolean){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.boolean,received:t.parsedType}),m}return f(e.data)}}ie.create=e=>new ie({typeName:qe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...x(e)});class ne extends O{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==s.date){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.date,received:t.parsedType}),m}if(isNaN(e.data.getTime()))return h(this._getOrReturnCtx(e),{code:o.invalid_date}),m;const i=new p;let n;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),h(n,{code:o.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()):t.assertNever(s);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ne({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ne.create=e=>new ne({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:qe.ZodDate,...x(e)});class se extends O{_parse(e){if(this._getType(e)!==s.symbol){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.symbol,received:t.parsedType}),m}return f(e.data)}}se.create=e=>new se({typeName:qe.ZodSymbol,...x(e)});class re extends O{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.undefined,received:t.parsedType}),m}return f(e.data)}}re.create=e=>new re({typeName:qe.ZodUndefined,...x(e)});class oe extends O{_parse(e){if(this._getType(e)!==s.null){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.null,received:t.parsedType}),m}return f(e.data)}}oe.create=e=>new oe({typeName:qe.ZodNull,...x(e)});class ae extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return f(e.data)}}ae.create=e=>new ae({typeName:qe.ZodAny,...x(e)});class ce extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return f(e.data)}}ce.create=e=>new ce({typeName:qe.ZodUnknown,...x(e)});class de extends O{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.never,received:t.parsedType}),m}}de.create=e=>new de({typeName:qe.ZodNever,...x(e)});class le extends O{_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.void,received:t.parsedType}),m}return f(e.data)}}le.create=e=>new le({typeName:qe.ZodVoid,...x(e)});class ue extends O{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),n=this._def;if(t.parsedType!==s.array)return h(t,{code:o.invalid_type,expected:s.array,received:t.parsedType}),m;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(h(t,{code:e?o.too_big:o.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(h(t,{code:o.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(h(t,{code:o.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map(((e,i)=>n.type._parseAsync(new P(t,e,t.path,i))))).then((e=>p.mergeArray(i,e)));const r=[...t.data].map(((e,i)=>n.type._parseSync(new P(t,e,t.path,i))));return p.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new ue({...this._def,minLength:{value:e,message:C.toString(t)}})}max(e,t){return new ue({...this._def,maxLength:{value:e,message:C.toString(t)}})}length(e,t){return new ue({...this._def,exactLength:{value:e,message:C.toString(t)}})}nonempty(e){return this.min(1,e)}}function he(e){if(e instanceof pe){const t={};for(const i in e.shape){const n=e.shape[i];t[i]=Ie.create(he(n))}return new pe({...e._def,shape:()=>t})}return e instanceof ue?new ue({...e._def,type:he(e.element)}):e instanceof Ie?Ie.create(he(e.unwrap())):e instanceof Ae?Ae.create(he(e.unwrap())):e instanceof be?be.create(e.items.map((e=>he(e)))):e}ue.create=(e,t)=>new ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...x(t)});class pe extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),i=t.objectKeys(e);return this._cached={shape:e,keys:i}}_parse(e){if(this._getType(e)!==s.object){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.object,received:t.parsedType}),m}const{status:t,ctx:i}=this._processInputParams(e),{shape:n,keys:r}=this._getCached(),a=[];if(!(this._def.catchall instanceof de&&"strip"===this._def.unknownKeys))for(const s in i.data)r.includes(s)||a.push(s);const c=[];for(const s of r){const e=n[s],t=i.data[s];c.push({key:{status:"valid",value:s},value:e._parse(new P(i,t,i.path,s)),alwaysSet:s in i.data})}if(this._def.catchall instanceof de){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of a)c.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===e)a.length>0&&(h(i,{code:o.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=i.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new P(i,n,i.path,t)),alwaysSet:t in i.data})}}return i.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of c){const i=await t.key,n=await t.value;e.push({key:i,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>p.mergeObjectSync(t,e))):p.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new pe({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,i)=>{var n,s,r,o;const a=null!==(r=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,i).message)&&void 0!==r?r:i.defaultError;return"unrecognized_keys"===t.code?{message:null!==(o=C.errToObj(e).message)&&void 0!==o?o:a}:{message:a}}}:{}})}strip(){return new pe({...this._def,unknownKeys:"strip"})}passthrough(){return new pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new pe({...this._def,catchall:e})}pick(e){const i={};return t.objectKeys(e).forEach((t=>{e[t]&&this.shape[t]&&(i[t]=this.shape[t])})),new pe({...this._def,shape:()=>i})}omit(e){const i={};return t.objectKeys(this.shape).forEach((t=>{e[t]||(i[t]=this.shape[t])})),new pe({...this._def,shape:()=>i})}deepPartial(){return he(this)}partial(e){const i={};return t.objectKeys(this.shape).forEach((t=>{const n=this.shape[t];e&&!e[t]?i[t]=n:i[t]=n.optional()})),new pe({...this._def,shape:()=>i})}required(e){const i={};return t.objectKeys(this.shape).forEach((t=>{if(e&&!e[t])i[t]=this.shape[t];else{let e=this.shape[t];for(;e instanceof Ie;)e=e._def.innerType;i[t]=e}})),new pe({...this._def,shape:()=>i})}keyof(){return _e(t.objectKeys(this.shape))}}pe.create=(e,t)=>new pe({shape:()=>e,unknownKeys:"strip",catchall:de.create(),typeName:qe.ZodObject,...x(t)}),pe.strictCreate=(e,t)=>new pe({shape:()=>e,unknownKeys:"strict",catchall:de.create(),typeName:qe.ZodObject,...x(t)}),pe.lazycreate=(e,t)=>new pe({shape:e,unknownKeys:"strip",catchall:de.create(),typeName:qe.ZodObject,...x(t)});class me extends O{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;if(t.common.async)return Promise.all(i.map((async e=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const i=e.map((e=>new a(e.ctx.common.issues)));return h(t,{code:o.invalid_union,unionErrors:i}),m}));{let e;const n=[];for(const r of i){const i={...t,common:{...t.common,issues:[]},parent:null},s=r._parseSync({data:t.data,path:t.path,parent:i});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new a(e)));return h(t,{code:o.invalid_union,unionErrors:s}),m}}get options(){return this._def.options}}me.create=(e,t)=>new me({options:e,typeName:qe.ZodUnion,...x(t)});const ge=e=>e instanceof we?ge(e.schema):e instanceof Oe?ge(e.innerType()):e instanceof Ee?[e.value]:e instanceof Pe?e.options:e instanceof Re?t.objectValues(e.enum):e instanceof Ne?ge(e._def.innerType):e instanceof re?[void 0]:e instanceof oe?[null]:e instanceof Ie?[void 0,...ge(e.unwrap())]:e instanceof Ae?[null,...ge(e.unwrap())]:e instanceof Ue||e instanceof Fe?ge(e.unwrap()):e instanceof De?ge(e._def.innerType):[];class fe extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return h(t,{code:o.invalid_type,expected:s.object,received:t.parsedType}),m;const i=this.discriminator,n=t.data[i],r=this.optionsMap.get(n);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const n=new Map;for(const s of t){const t=ge(s.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new fe({typeName:qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...x(i)})}}function ve(e,i){const n=r(e),o=r(i);if(e===i)return{valid:!0,data:e};if(n===s.object&&o===s.object){const n=t.objectKeys(i),s=t.objectKeys(e).filter((e=>-1!==n.indexOf(e))),r={...e,...i};for(const t of s){const n=ve(e[t],i[t]);if(!n.valid)return{valid:!1};r[t]=n.data}return{valid:!0,data:r}}if(n===s.array&&o===s.array){if(e.length!==i.length)return{valid:!1};const t=[];for(let n=0;n<e.length;n++){const s=ve(e[n],i[n]);if(!s.valid)return{valid:!1};t.push(s.data)}return{valid:!0,data:t}}return n===s.date&&o===s.date&&+e==+i?{valid:!0,data:e}:{valid:!1}}class ye extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return m;const s=ve(e.value,n.value);return s.valid?((y(e)||y(n))&&t.dirty(),{status:t.value,value:s.data}):(h(i,{code:o.invalid_intersection_types}),m)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ye.create=(e,t,i)=>new ye({left:e,right:t,typeName:qe.ZodIntersection,...x(i)});class be extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.array)return h(i,{code:o.invalid_type,expected:s.array,received:i.parsedType}),m;if(i.data.length<this._def.items.length)return h(i,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&i.data.length>this._def.items.length&&(h(i,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...i.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new P(i,e,i.path,t)):null})).filter((e=>!!e));return i.common.async?Promise.all(n).then((e=>p.mergeArray(t,e))):p.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new be({...this._def,rest:e})}}be.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new be({items:e,typeName:qe.ZodTuple,rest:null,...x(t)})};class ke extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.object)return h(i,{code:o.invalid_type,expected:s.object,received:i.parsedType}),m;const n=[],r=this._def.keyType,a=this._def.valueType;for(const s in i.data)n.push({key:r._parse(new P(i,s,i.path,s)),value:a._parse(new P(i,i.data[s],i.path,s)),alwaysSet:s in i.data});return i.common.async?p.mergeObjectAsync(t,n):p.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,i){return new ke(t instanceof O?{keyType:e,valueType:t,typeName:qe.ZodRecord,...x(i)}:{keyType:Q.create(),valueType:e,typeName:qe.ZodRecord,...x(t)})}}class Te extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.map)return h(i,{code:o.invalid_type,expected:s.map,received:i.parsedType}),m;const n=this._def.keyType,r=this._def.valueType,a=[...i.data.entries()].map((([e,t],s)=>({key:n._parse(new P(i,e,i.path,[s,"key"])),value:r._parse(new P(i,t,i.path,[s,"value"]))})));if(i.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const i of a){const n=await i.key,s=await i.value;if("aborted"===n.status||"aborted"===s.status)return m;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const i of a){const n=i.key,s=i.value;if("aborted"===n.status||"aborted"===s.status)return m;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}Te.create=(e,t,i)=>new Te({valueType:t,keyType:e,typeName:qe.ZodMap,...x(i)});class Se extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==s.set)return h(i,{code:o.invalid_type,expected:s.set,received:i.parsedType}),m;const n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(h(i,{code:o.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(h(i,{code:o.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const r=this._def.valueType;function a(e){const i=new Set;for(const n of e){if("aborted"===n.status)return m;"dirty"===n.status&&t.dirty(),i.add(n.value)}return{status:t.value,value:i}}const c=[...i.data.values()].map(((e,t)=>r._parse(new P(i,e,i.path,t))));return i.common.async?Promise.all(c).then((e=>a(e))):a(c)}min(e,t){return new Se({...this._def,minSize:{value:e,message:C.toString(t)}})}max(e,t){return new Se({...this._def,maxSize:{value:e,message:C.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Se.create=(e,t)=>new Se({valueType:e,minSize:null,maxSize:null,typeName:qe.ZodSet,...x(t)});class Ce extends O{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.function)return h(t,{code:o.invalid_type,expected:s.function,received:t.parsedType}),m;function i(e,i){return u({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l(),c].filter((e=>!!e)),issueData:{code:o.invalid_arguments,argumentsError:i}})}function n(e,i){return u({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l(),c].filter((e=>!!e)),issueData:{code:o.invalid_return_type,returnTypeError:i}})}const r={errorMap:t.common.contextualErrorMap},d=t.data;if(this._def.returns instanceof xe){const e=this;return f((async function(...t){const s=new a([]),o=await e._def.args.parseAsync(t,r).catch((e=>{throw s.addIssue(i(t,e)),s})),c=await Reflect.apply(d,this,o);return await e._def.returns._def.type.parseAsync(c,r).catch((e=>{throw s.addIssue(n(c,e)),s}))}))}{const e=this;return f((function(...t){const s=e._def.args.safeParse(t,r);if(!s.success)throw new a([i(t,s.error)]);const o=Reflect.apply(d,this,s.data),c=e._def.returns.safeParse(o,r);if(!c.success)throw new a([n(o,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ce({...this._def,args:be.create(e).rest(ce.create())})}returns(e){return new Ce({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new Ce({args:e||be.create([]).rest(ce.create()),returns:t||ce.create(),typeName:qe.ZodFunction,...x(i)})}}class we extends O{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}we.create=(e,t)=>new we({getter:e,typeName:qe.ZodLazy,...x(t)});class Ee extends O{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}}function _e(e,t){return new Pe({values:e,typeName:qe.ZodEnum,...x(t)})}Ee.create=(e,t)=>new Ee({value:e,typeName:qe.ZodLiteral,...x(t)});class Pe extends O{constructor(){super(...arguments),E.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const i=this._getOrReturnCtx(e),n=this._def.values;return h(i,{expected:t.joinValues(n),received:i.parsedType,code:o.invalid_type}),m}if(T(this,E,"f")||S(this,E,new Set(this._def.values),"f"),!T(this,E,"f").has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return h(t,{received:t.data,code:o.invalid_enum_value,options:i}),m}return f(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Pe.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}E=new WeakMap,Pe.create=_e;class Re extends O{constructor(){super(...arguments),_.set(this,void 0)}_parse(e){const i=t.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==s.string&&n.parsedType!==s.number){const e=t.objectValues(i);return h(n,{expected:t.joinValues(e),received:n.parsedType,code:o.invalid_type}),m}if(T(this,_,"f")||S(this,_,new Set(t.getValidEnumValues(this._def.values)),"f"),!T(this,_,"f").has(e.data)){const e=t.objectValues(i);return h(n,{received:n.data,code:o.invalid_enum_value,options:e}),m}return f(e.data)}get enum(){return this._def.values}}_=new WeakMap,Re.create=(e,t)=>new Re({values:e,typeName:qe.ZodNativeEnum,...x(t)});class xe extends O{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.promise&&!1===t.common.async)return h(t,{code:o.invalid_type,expected:s.promise,received:t.parsedType}),m;const i=t.parsedType===s.promise?t.data:Promise.resolve(t.data);return f(i.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}xe.create=(e,t)=>new xe({type:e,typeName:qe.ZodPromise,...x(t)});class Oe extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:i,ctx:n}=this._processInputParams(e),s=this._def.effect||null,r={addIssue:e=>{h(n,e),e.fatal?i.abort():i.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),"preprocess"===s.type){const e=s.transform(n.data,r);if(n.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===i.value)return m;const t=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===t.status?m:"dirty"===t.status||"dirty"===i.value?g(t.value):t}));{if("aborted"===i.value)return m;const t=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===t.status?m:"dirty"===t.status||"dirty"===i.value?g(t.value):t}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,r);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const t=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===t.status?m:("dirty"===t.status&&i.dirty(),e(t.value),{status:i.value,value:t.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((t=>"aborted"===t.status?m:("dirty"===t.status&&i.dirty(),e(t.value).then((()=>({status:i.value,value:t.value}))))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!b(e))return e;const t=s.transform(e.value,r);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:t}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((e=>b(e)?Promise.resolve(s.transform(e.value,r)).then((e=>({status:i.value,value:e}))):e))}t.assertNever(s)}}Oe.create=(e,t,i)=>new Oe({schema:e,typeName:qe.ZodEffects,effect:t,...x(i)}),Oe.createWithPreprocess=(e,t,i)=>new Oe({schema:t,effect:{type:"preprocess",transform:e},typeName:qe.ZodEffects,...x(i)});class Ie extends O{_parse(e){return this._getType(e)===s.undefined?f(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:qe.ZodOptional,...x(t)});class Ae extends O{_parse(e){return this._getType(e)===s.null?f(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:qe.ZodNullable,...x(t)});class Ne extends O{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===s.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:qe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...x(t)});class De extends O{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return k(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new a(i.common.issues)},input:i.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new a(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:qe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...x(t)});class Me extends O{_parse(e){if(this._getType(e)!==s.nan){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:s.nan,received:t.parsedType}),m}return{status:"valid",value:e.data}}}Me.create=e=>new Me({typeName:qe.ZodNaN,...x(e)});const Le=Symbol("zod_brand");class Ue extends O{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class je extends O{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?m:"dirty"===e.status?(t.dirty(),g(e.value)):this._def.out._parseAsync({data:e.value,path:i.path,parent:i})})();{const e=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===e.status?m:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:i.path,parent:i})}}static create(e,t){return new je({in:e,out:t,typeName:qe.ZodPipeline})}}class Fe extends O{_parse(e){const t=this._def.innerType._parse(e),i=e=>(b(e)&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then((e=>i(e))):i(t)}unwrap(){return this._def.innerType}}function $e(e,t){const i="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof i?{message:i}:i}function Be(e,t={},i){return e?ae.create().superRefine(((n,s)=>{var r,o;const a=e(n);if(a instanceof Promise)return a.then((e=>{var r,o;if(!e){const e=$e(t,n),a=null===(o=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===o||o;s.addIssue({code:"custom",...e,fatal:a})}}));if(!a){const e=$e(t,n),a=null===(o=null!==(r=e.fatal)&&void 0!==r?r:i)||void 0===o||o;s.addIssue({code:"custom",...e,fatal:a})}})):ae.create()}Fe.create=(e,t)=>new Fe({innerType:e,typeName:qe.ZodReadonly,...x(t)});const Ve={object:pe.lazycreate};var qe,ze;(ze=qe||(qe={})).ZodString="ZodString",ze.ZodNumber="ZodNumber",ze.ZodNaN="ZodNaN",ze.ZodBigInt="ZodBigInt",ze.ZodBoolean="ZodBoolean",ze.ZodDate="ZodDate",ze.ZodSymbol="ZodSymbol",ze.ZodUndefined="ZodUndefined",ze.ZodNull="ZodNull",ze.ZodAny="ZodAny",ze.ZodUnknown="ZodUnknown",ze.ZodNever="ZodNever",ze.ZodVoid="ZodVoid",ze.ZodArray="ZodArray",ze.ZodObject="ZodObject",ze.ZodUnion="ZodUnion",ze.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ze.ZodIntersection="ZodIntersection",ze.ZodTuple="ZodTuple",ze.ZodRecord="ZodRecord",ze.ZodMap="ZodMap",ze.ZodSet="ZodSet",ze.ZodFunction="ZodFunction",ze.ZodLazy="ZodLazy",ze.ZodLiteral="ZodLiteral",ze.ZodEnum="ZodEnum",ze.ZodEffects="ZodEffects",ze.ZodNativeEnum="ZodNativeEnum",ze.ZodOptional="ZodOptional",ze.ZodNullable="ZodNullable",ze.ZodDefault="ZodDefault",ze.ZodCatch="ZodCatch",ze.ZodPromise="ZodPromise",ze.ZodBranded="ZodBranded",ze.ZodPipeline="ZodPipeline",ze.ZodReadonly="ZodReadonly";const Ke=Q.create,Ze=ee.create,He=Me.create,Ge=te.create,We=ie.create,Je=ne.create,Ye=se.create,Qe=re.create,Xe=oe.create,et=ae.create,tt=ce.create,it=de.create,nt=le.create,st=ue.create,rt=pe.create,ot=pe.strictCreate,at=me.create,ct=fe.create,dt=ye.create,lt=be.create,ut=ke.create,ht=Te.create,pt=Se.create,mt=Ce.create,gt=we.create,ft=Ee.create,vt=Pe.create,yt=Re.create,bt=xe.create,kt=Oe.create,Tt=Ie.create,St=Ae.create,Ct=Oe.createWithPreprocess,wt=je.create,Et={string:e=>Q.create({...e,coerce:!0}),number:e=>ee.create({...e,coerce:!0}),boolean:e=>ie.create({...e,coerce:!0}),bigint:e=>te.create({...e,coerce:!0}),date:e=>ne.create({...e,coerce:!0})},_t=m;var Pt=Object.freeze({__proto__:null,defaultErrorMap:c,setErrorMap:function(e){d=e},getErrorMap:l,makeIssue:u,EMPTY_PATH:[],addIssueToContext:h,ParseStatus:p,INVALID:m,DIRTY:g,OK:f,isAborted:v,isDirty:y,isValid:b,isAsync:k,get util(){return t},get objectUtil(){return n},ZodParsedType:s,getParsedType:r,ZodType:O,datetimeRegex:W,ZodString:Q,ZodNumber:ee,ZodBigInt:te,ZodBoolean:ie,ZodDate:ne,ZodSymbol:se,ZodUndefined:re,ZodNull:oe,ZodAny:ae,ZodUnknown:ce,ZodNever:de,ZodVoid:le,ZodArray:ue,ZodObject:pe,ZodUnion:me,ZodDiscriminatedUnion:fe,ZodIntersection:ye,ZodTuple:be,ZodRecord:ke,ZodMap:Te,ZodSet:Se,ZodFunction:Ce,ZodLazy:we,ZodLiteral:Ee,ZodEnum:Pe,ZodNativeEnum:Re,ZodPromise:xe,ZodEffects:Oe,ZodTransformer:Oe,ZodOptional:Ie,ZodNullable:Ae,ZodDefault:Ne,ZodCatch:De,ZodNaN:Me,BRAND:Le,ZodBranded:Ue,ZodPipeline:je,ZodReadonly:Fe,custom:Be,Schema:O,ZodSchema:O,late:Ve,get ZodFirstPartyTypeKind(){return qe},coerce:Et,any:et,array:st,bigint:Ge,boolean:We,date:Je,discriminatedUnion:ct,effect:kt,enum:vt,function:mt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Be((t=>t instanceof e),t),intersection:dt,lazy:gt,literal:ft,map:ht,nan:He,nativeEnum:yt,never:it,null:Xe,nullable:St,number:Ze,object:rt,oboolean:()=>We().optional(),onumber:()=>Ze().optional(),optional:Tt,ostring:()=>Ke().optional(),pipeline:wt,preprocess:Ct,promise:bt,record:ut,set:pt,strictObject:ot,string:Ke,symbol:Ye,transformer:kt,tuple:lt,undefined:Qe,union:at,unknown:tt,void:nt,NEVER:_t,ZodIssueCode:o,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:a});const Rt="https://iamobi.ai/api",xt=Pt.object({apiKey:Pt.string().optional(),enableVoice:Pt.boolean().default(!0),enableScreenCapture:Pt.boolean().default(!0),debug:Pt.boolean().default(!1),user:Pt.object({id:Pt.string(),email:Pt.string().optional(),metadata:Pt.any().optional()}).optional()});var Ot=(e=>(e.READY="ready",e.ERROR="error",e.VOICE_START="voice:start",e.VOICE_STOP="voice:stop",e.SCREEN_CAPTURE_START="screen:start",e.SCREEN_CAPTURE_STOP="screen:stop",e.STATE_CHANGE="state:change",e))(Ot||{}),It=(e=>(e.READY="ready",e.ERROR="error",e.PAUSED="paused",e.LOADING="loading",e.THINKING="thinking",e.RESEARCHING="researching",e.AGENT_SPEAKING="agent_speaking",e.USER_SPEAKING="user_speaking",e.AWAITING_USER_INPUT="awaiting_user_input",e))(It||{});function At(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var Nt=Object.defineProperty,Dt=(e,t,i)=>((e,t,i)=>t in e?Nt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);let Mt=class{constructor(){Dt(this,"_locking"),Dt(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),i=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),i}};function Lt(e,t){if(!e)throw new Error(t)}function Ut(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function jt(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Ft(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const $t=Symbol("@bufbuild/protobuf/enum-type");function Bt(e,t,i,n){e[$t]=Vt(t,i.map((t=>({no:t.no,name:t.name,localName:e[t.no]}))))}function Vt(e,t,i){const n=Object.create(null),s=Object.create(null),r=[];for(const o of t){const e=qt(o);r.push(e),n[o.name]=e,s[o.no]=e}return{typeName:e,values:r,findName:e=>n[e],findNumber:e=>s[e]}}function qt(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class zt{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){const i=this.getType(),n=i.runtime.json,s=n.makeReadOptions(t);return n.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(n){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(n instanceof Error?n.message:String(n)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){const t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Kt(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,!(128&i))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,!(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function Zt(e,t,i){for(let r=0;r<28;r+=7){const n=e>>>r,s=!(n>>>7==0&&0==t),o=255&(s?128|n:n);if(i.push(o),!s)return}const n=e>>>28&15|(7&t)<<4,s=!!(t>>3);if(i.push(255&(s?128|n:n)),s){for(let e=3;e<31;e+=7){const n=t>>>e,s=!(n>>>7==0),r=255&(s?128|n:n);if(i.push(r),!s)return}i.push(t>>>31&1)}}const Ht=4294967296;function Gt(e){const t="-"===e[0];t&&(e=e.slice(1));const i=1e6;let n=0,s=0;function r(t,r){const o=Number(e.slice(t,r));s*=i,n=n*i+o,n>=Ht&&(s+=n/Ht|0,n%=Ht)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?Yt(n,s):Jt(n,s)}function Wt(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(Ht*t+e);const i=16777215&(e>>>24|t<<8),n=t>>16&65535;let s=(16777215&e)+6777216*i+6710656*n,r=i+8147497*n,o=2*n;const a=1e7;return s>=a&&(r+=Math.floor(s/a),s%=a),r>=a&&(o+=Math.floor(r/a),r%=a),o.toString()+Qt(r)+Qt(s)}function Jt(e,t){return{lo:0|e,hi:0|t}}function Yt(e,t){return t=~t,e?e=1+~e:t+=1,Jt(e,t)}const Qt=e=>{const t=String(e);return"0000000".slice(t.length)+t};function Xt(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function ei(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let i=5;128&e&&i<10;i++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const ti=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw new Error("int64 invalid: ".concat(e));return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>s||t<n)throw new Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}const t=e=>Lt(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>Lt(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),Gt(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),Gt(e)),dec:(e,t)=>function(e,t){let i=Jt(e,t);const n=2147483648&i.hi;n&&(i=Yt(i.lo,i.hi));const s=Wt(i.lo,i.hi);return n?"-"+s:s}(e,t),uDec:(e,t)=>Wt(e,t)}}();var ii,ni,si,ri,oi,ai;function ci(e,t,i){if(t===i)return!0;if(e==ii.BYTES){if(!(t instanceof Uint8Array&&i instanceof Uint8Array))return!1;if(t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case ii.UINT64:case ii.FIXED64:case ii.INT64:case ii.SFIXED64:case ii.SINT64:return t==i}return!1}function di(e,t){switch(e){case ii.BOOL:return!1;case ii.UINT64:case ii.FIXED64:case ii.INT64:case ii.SFIXED64:case ii.SINT64:return 0==t?ti.zero:"0";case ii.DOUBLE:case ii.FLOAT:return 0;case ii.BYTES:return new Uint8Array(0);case ii.STRING:return"";default:return 0}}function li(e,t){switch(e){case ii.BOOL:return!1===t;case ii.STRING:return""===t;case ii.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(ni=ii||(ii={}))[ni.DOUBLE=1]="DOUBLE",ni[ni.FLOAT=2]="FLOAT",ni[ni.INT64=3]="INT64",ni[ni.UINT64=4]="UINT64",ni[ni.INT32=5]="INT32",ni[ni.FIXED64=6]="FIXED64",ni[ni.FIXED32=7]="FIXED32",ni[ni.BOOL=8]="BOOL",ni[ni.STRING=9]="STRING",ni[ni.BYTES=12]="BYTES",ni[ni.UINT32=13]="UINT32",ni[ni.SFIXED32=15]="SFIXED32",ni[ni.SFIXED64=16]="SFIXED64",ni[ni.SINT32=17]="SINT32",ni[ni.SINT64=18]="SINT64",(ri=si||(si={}))[ri.BIGINT=0]="BIGINT",ri[ri.STRING=1]="STRING",(ai=oi||(oi={}))[ai.Varint=0]="Varint",ai[ai.Bit64=1]="Bit64",ai[ai.LengthDelimited=2]="LengthDelimited",ai[ai.StartGroup=3]="StartGroup",ai[ai.EndGroup=4]="EndGroup",ai[ai.Bit32=5]="Bit32";class ui{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let n=0;n<this.chunks.length;n++)e+=this.chunks[n].length;let t=new Uint8Array(e),i=0;for(let n=0;n<this.chunks.length;n++)t.set(this.chunks[n],i),i+=this.chunks[n].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(jt(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return Ut(e),Xt(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Ft(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){jt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ut(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ut(e),Xt(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=ti.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=ti.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=ti.enc(e);return Zt(t.lo,t.hi,this.buf),this}sint64(e){let t=ti.enc(e),i=t.hi>>31;return Zt(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=ti.uEnc(e);return Zt(t.lo,t.hi,this.buf),this}}class hi{constructor(e,t){this.varint64=Kt,this.uint32=ei,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case oi.Varint:for(;128&this.buf[this.pos++];);break;case oi.Bit64:this.pos+=4;case oi.Bit32:this.pos+=4;break;case oi.LengthDelimited:let i=this.uint32();this.pos+=i;break;case oi.StartGroup:for(;;){const[e,i]=this.tag();if(i===oi.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(i,e)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return ti.dec(...this.varint64())}uint64(){return ti.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,ti.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ti.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ti.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function pi(e){const t=e.field.localName,i=Object.create(null);return i[t]=function(e){const t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return di(t.T,t.L);case"message":const e=t.T,i=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let mi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),gi=[];for(let mm=0;mm<mi.length;mm++)gi[mi[mm].charCodeAt(0)]=mm;gi["-".charCodeAt(0)]=mi.indexOf("+"),gi["_".charCodeAt(0)]=mi.indexOf("/");const fi={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i,n=new Uint8Array(t),s=0,r=0,o=0;for(let a=0;a<e.length;a++){if(i=gi[e.charCodeAt(a)],void 0===i)switch(e[a]){case"=":r=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=i,r=1;break;case 1:n[s++]=o<<2|(48&i)>>4,o=i,r=2;break;case 2:n[s++]=(15&o)<<4|(60&i)>>2,o=i,r=3;break;case 3:n[s++]=(3&o)<<6|i,r=0}}if(1==r)throw Error("invalid base64 string.");return n.subarray(0,s)},enc(e){let t,i="",n=0,s=0;for(let r=0;r<e.length;r++)switch(t=e[r],n){case 0:i+=mi[t>>2],s=(3&t)<<4,n=1;break;case 1:i+=mi[s|t>>4],s=(15&t)<<2,n=2;break;case 2:i+=mi[s|t>>6],i+=mi[63&t],n=0}return n&&(i+=mi[s],i+="=",1==n&&(i+="=")),i}};function vi(e,t,i){ki(t,e);const n=t.runtime.bin.makeReadOptions(i),s=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter((e=>e.no===t.no))}(e.getType().runtime.bin.listUnknownFields(e),t.field),[r,o]=pi(t);for(const a of s)t.runtime.bin.readField(r,n.readerFactory(a.data),t.field,a.wireType,n);return o()}function yi(e,t,i,n){ki(t,e);const s=t.runtime.bin.makeReadOptions(n),r=t.runtime.bin.makeWriteOptions(n);if(bi(e,t)){const i=e.getType().runtime.bin.listUnknownFields(e).filter((e=>e.no!=t.field.no));e.getType().runtime.bin.discardUnknownFields(e);for(const t of i)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}const o=r.writerFactory();let a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,r);const c=s.readerFactory(o.finish());for(;c.pos<c.len;){const[t,i]=c.tag(),n=c.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}function bi(e,t){const i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find((e=>e.no==t.field.no))}function ki(e,t){Lt(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function Ti(e,t){const i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":return e.opt||e.req?void 0!==t[i]:"enum"==e.kind?t[i]!==e.T.values[0].no:!li(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function Si(e,t){const i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?di(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Ci(e,t){if(null===e||"object"!=typeof e)return!1;if(!Object.getOwnPropertyNames(zt.prototype).every((t=>t in e&&"function"==typeof e[t])))return!1;const i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function wi(e,t){return Ci(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}ii.DOUBLE,ii.FLOAT,ii.INT64,ii.UINT64,ii.INT32,ii.UINT32,ii.BOOL,ii.STRING,ii.BYTES;const Ei={ignoreUnknownFields:!1},_i={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};const Pi=Symbol(),Ri=Symbol();function xi(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function Oi(e,t,i,n,s){let r=i.localName;if(i.repeated){if(Lt("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(xi(t)));const a=e[r];for(const e of t){if(null===e)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(xi(e)));switch(i.kind){case"message":a.push(i.T.fromJson(e,n));break;case"enum":const t=Ni(i.T,e,n.ignoreUnknownFields,!0);t!==Ri&&a.push(t);break;case"scalar":try{a.push(Ai(i.T,e,i.L,!0))}catch(o){let t="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(xi(e));throw o instanceof Error&&o.message.length>0&&(t+=": ".concat(o.message)),new Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(xi(t)));const a=e[r];for(const[e,r]of Object.entries(t)){if(null===r)throw new Error("cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: map value null"));let c;try{c=Ii(i.K,e)}catch(o){let e="cannot decode map key for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(xi(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}switch(i.V.kind){case"message":a[c]=i.V.T.fromJson(r,n);break;case"enum":const e=Ni(i.V.T,r,n.ignoreUnknownFields,!0);e!==Ri&&(a[c]=e);break;case"scalar":try{a[c]=Ai(i.V.T,r,si.BIGINT,!0)}catch(o){let e="cannot decode map value for field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(xi(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:r},r="value"),i.kind){case"message":const a=i.T;if(null===t&&"google.protobuf.Value"!=a.typeName)return;let c=e[r];Ci(c)?c.fromJson(t,n):(e[r]=c=a.fromJson(t,n),a.fieldWrapper&&!i.oneof&&(e[r]=a.fieldWrapper.unwrapField(c)));break;case"enum":const d=Ni(i.T,t,n.ignoreUnknownFields,!1);switch(d){case Pi:Si(i,e);break;case Ri:break;default:e[r]=d}break;case"scalar":try{const n=Ai(i.T,t,i.L,!1);n===Pi?Si(i,e):e[r]=n}catch(o){let e="cannot decode field ".concat(s.typeName,".").concat(i.name," from JSON: ").concat(xi(t));throw o instanceof Error&&o.message.length>0&&(e+=": ".concat(o.message)),new Error(e)}}}function Ii(e,t){if(e===ii.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return Ai(e,t,si.BIGINT,!0).toString()}function Ai(e,t,i,n){if(null===t)return n?di(e,i):Pi;switch(e){case ii.DOUBLE:case ii.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t)break;if("string"==typeof t&&t.trim().length!==t.length)break;if("string"!=typeof t&&"number"!=typeof t)break;const n=Number(t);if(Number.isNaN(n))break;if(!Number.isFinite(n))break;return e==ii.FLOAT&&Ft(n),n;case ii.INT32:case ii.FIXED32:case ii.SFIXED32:case ii.SINT32:case ii.UINT32:let r;if("number"==typeof t?r=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(r=Number(t)),void 0===r)break;return e==ii.UINT32||e==ii.FIXED32?jt(r):Ut(r),r;case ii.INT64:case ii.SFIXED64:case ii.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;const o=ti.parse(t);return i?o.toString():o;case ii.FIXED64:case ii.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;const a=ti.uParse(t);return i?a.toString():a;case ii.BOOL:if("boolean"!=typeof t)break;return t;case ii.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(s){throw new Error("invalid UTF8")}return t;case ii.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return fi.dec(t)}throw new Error}function Ni(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:Pi;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const n=e.findName(t);if(void 0!==n)return n.no;if(i)return Ri}throw new Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(xi(t)))}function Di(e){return!(!e.repeated&&"map"!=e.kind&&(e.oneof||"message"==e.kind||e.opt||e.req))}function Mi(e,t,i){if("map"==e.kind){Lt("object"==typeof t&&null!=t);const n={},s=Object.entries(t);switch(e.V.kind){case"scalar":for(const[i,r]of s)n[i.toString()]=Ui(e.V.T,r);break;case"message":for(const[e,r]of s)n[e.toString()]=r.toJson(i);break;case"enum":const t=e.V.T;for(const[e,r]of s)n[e.toString()]=Li(t,r,i.enumAsInteger)}return i.emitDefaultValues||s.length>0?n:void 0}if(e.repeated){Lt(Array.isArray(t));const n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(Ui(e.T,t[i]));break;case"enum":for(let s=0;s<t.length;s++)n.push(Li(e.T,t[s],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return Ui(e.T,t);case"enum":return Li(e.T,t,i.enumAsInteger);case"message":return wi(e.T,t).toJson(i)}}function Li(e,t,i){var n;if(Lt("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;const s=e.findNumber(t);return null!==(n=null==s?void 0:s.name)&&void 0!==n?n:t}function Ui(e,t){switch(e){case ii.INT32:case ii.SFIXED32:case ii.SINT32:case ii.FIXED32:case ii.UINT32:return Lt("number"==typeof t),t;case ii.FLOAT:case ii.DOUBLE:return Lt("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case ii.STRING:return Lt("string"==typeof t),t;case ii.BOOL:return Lt("boolean"==typeof t),t;case ii.UINT64:case ii.FIXED64:case ii.INT64:case ii.SFIXED64:case ii.SINT64:return Lt("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case ii.BYTES:return Lt(t instanceof Uint8Array),fi.enc(t)}}const ji=Symbol("@bufbuild/protobuf/unknown-fields"),Fi={readUnknownFields:!0,readerFactory:e=>new hi(e)},$i={writeUnknownFields:!0,writerFactory:()=>new ui};function Bi(e,t,i,n,s){let{repeated:r,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":const a="enum"==i.kind?ii.INT32:i.T;let c=zi;if("scalar"==i.kind&&i.L>0&&(c=qi),r){let i=e[o];if(n==oi.LengthDelimited&&a!=ii.STRING&&a!=ii.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(c(t,a))}else i.push(c(t,a))}else e[o]=c(t,a);break;case"message":const d=i.T;r?e[o].push(Vi(t,new d,s,i)):Ci(e[o])?Vi(t,e[o],s,i):(e[o]=Vi(t,new d,s,i),!d.fieldWrapper||i.oneof||i.repeated||(e[o]=d.fieldWrapper.unwrapField(e[o])));break;case"map":let[l,u]=function(e,t,i){const n=t.uint32(),s=t.pos+n;let r,o;for(;t.pos<s;){const[n]=t.tag();switch(n){case 1:r=zi(t,e.K);break;case 2:switch(e.V.kind){case"scalar":o=zi(t,e.V.T);break;case"enum":o=t.int32();break;case"message":o=Vi(t,new e.V.T,i,void 0)}}}if(void 0===r&&(r=di(e.K,si.BIGINT)),"string"!=typeof r&&"number"!=typeof r&&(r=r.toString()),void 0===o)switch(e.V.kind){case"scalar":o=di(e.V.T,si.BIGINT);break;case"enum":o=e.V.T.values[0].no;break;case"message":o=new e.V.T}return[r,o]}(i,t,s);e[o][l]=u}}function Vi(e,t,i,n){const s=t.getType().runtime.bin,r=null==n?void 0:n.delimited;return s.readMessage(t,e,r?n.no:e.uint32(),i,r),t}function qi(e,t){const i=zi(e,t);return"bigint"==typeof i?i.toString():i}function zi(e,t){switch(t){case ii.STRING:return e.string();case ii.BOOL:return e.bool();case ii.DOUBLE:return e.double();case ii.FLOAT:return e.float();case ii.INT32:return e.int32();case ii.INT64:return e.int64();case ii.UINT64:return e.uint64();case ii.FIXED64:return e.fixed64();case ii.BYTES:return e.bytes();case ii.FIXED32:return e.fixed32();case ii.SFIXED32:return e.sfixed32();case ii.SFIXED64:return e.sfixed64();case ii.SINT64:return e.sint64();case ii.UINT32:return e.uint32();case ii.SINT32:return e.sint32()}}function Ki(e,t,i,n){Lt(void 0!==t);const s=e.repeated;switch(e.kind){case"scalar":case"enum":let r="enum"==e.kind?ii.INT32:e.T;if(s)if(Lt(Array.isArray(t)),e.packed)!function(e,t,i,n){if(!n.length)return;e.tag(i,oi.LengthDelimited).fork();let[,s]=Wi(t);for(let r=0;r<n.length;r++)e[s](n[r]);e.join()}(i,r,e.no,t);else for(const n of t)Gi(i,r,e.no,n);else Gi(i,r,e.no,t);break;case"message":if(s){Lt(Array.isArray(t));for(const s of t)Hi(i,n,e,s)}else Hi(i,n,e,t);break;case"map":Lt("object"==typeof t&&null!=t);for(const[s,o]of Object.entries(t))Zi(i,n,e,s,o)}}function Zi(e,t,i,n,s){e.tag(i.no,oi.LengthDelimited),e.fork();let r=n;switch(i.K){case ii.INT32:case ii.FIXED32:case ii.UINT32:case ii.SFIXED32:case ii.SINT32:r=Number.parseInt(n);break;case ii.BOOL:Lt("true"==n||"false"==n),r="true"==n}switch(Gi(e,i.K,1,r),i.V.kind){case"scalar":Gi(e,i.V.T,2,s);break;case"enum":Gi(e,ii.INT32,2,s);break;case"message":Lt(void 0!==s),e.tag(2,oi.LengthDelimited).bytes(s.toBinary(t))}e.join()}function Hi(e,t,i,n){const s=wi(i.T,n);i.delimited?e.tag(i.no,oi.StartGroup).raw(s.toBinary(t)).tag(i.no,oi.EndGroup):e.tag(i.no,oi.LengthDelimited).bytes(s.toBinary(t))}function Gi(e,t,i,n){Lt(void 0!==n);let[s,r]=Wi(t);e.tag(i,s)[r](n)}function Wi(e){let t=oi.Varint;switch(e){case ii.BYTES:case ii.STRING:t=oi.LengthDelimited;break;case ii.DOUBLE:case ii.FIXED64:case ii.SFIXED64:t=oi.Bit64;break;case ii.FIXED32:case ii.SFIXED32:case ii.FLOAT:t=oi.Bit32}return[t,ii[e].toLowerCase()]}function Ji(e){if(void 0===e)return e;if(Ci(e))return e.clone();if(e instanceof Uint8Array){const t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Yi(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class Qi{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const e={};for(const t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){const e={};for(const t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort(((e,t)=>e.no-t.no))),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Xi(e,t){const i=tn(e);return t?i:an(on(i))}const en=tn;function tn(e){let t=!1;const i=[];for(let n=0;n<e.length;n++){let s=e.charAt(n);switch(s){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(s),t=!1;break;default:t&&(t=!1,s=s.toUpperCase()),i.push(s)}}return i.join("")}const nn=new Set(["constructor","toString","toJSON","valueOf"]),sn=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),rn=e=>"".concat(e,"$"),on=e=>sn.has(e)?rn(e):e,an=e=>nn.has(e)?rn(e):e;class cn{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Xi(e,!1)}addField(e){Lt(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}const dn=(ln=e=>new Qi(e,(e=>function(e){var t,i,n,s,r,o;const a=[];let c;for(const d of"function"==typeof e?e():e){const e=d;if(e.localName=Xi(d.name,void 0!==d.oneof),e.jsonName=null!==(t=d.jsonName)&&void 0!==t?t:en(d.name),e.repeated=null!==(i=d.repeated)&&void 0!==i&&i,"scalar"==d.kind&&(e.L=null!==(n=d.L)&&void 0!==n?n:si.BIGINT),e.delimited=null!==(s=d.delimited)&&void 0!==s&&s,e.req=null!==(r=d.req)&&void 0!==r&&r,e.opt=null!==(o=d.opt)&&void 0!==o&&o,void 0===d.packed&&(e.packed="enum"==d.kind||"scalar"==d.kind&&d.T!=ii.BYTES&&d.T!=ii.STRING),void 0!==d.oneof){const t="string"==typeof d.oneof?d.oneof:d.oneof.name;c&&c.name==t||(c=new cn(t)),e.oneof=c,c.addField(e)}a.push(e)}return a}(e))),un=e=>{for(const t of e.getType().fields.byMember()){if(t.opt)continue;const i=t.localName,n=e;if(t.repeated)n[i]=[];else switch(t.kind){case"oneof":n[i]={case:void 0};break;case"enum":n[i]=0;break;case"map":n[i]={};break;case"scalar":n[i]=di(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},Ei),e):Ei},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},_i),e):_i},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(xi(t)));n=null!=n?n:new e;const s=new Map,r=i.typeRegistry;for(const[o,a]of Object.entries(t)){const t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;const i=s.get(t.oneof);if(void 0!==i)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));s.set(t.oneof,o)}Oi(n,a,t,i,e)}else{let t=!1;if((null==r?void 0:r.findExtension)&&o.startsWith("[")&&o.endsWith("]")){const s=r.findExtension(o.substring(1,o.length-1));if(s&&s.extendee.typeName==e.typeName){t=!0;const[e,r]=pi(s);Oi(e,a,s.field,i,s),yi(n,s,r(),i)}}if(!t&&!i.ignoreUnknownFields)throw new Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){const i=e.getType(),n={};let s;try{for(s of i.fields.byNumber()){if(!Ti(s,e)){if(s.req)throw"required field not set";if(!t.emitDefaultValues)continue;if(!Di(s))continue}const i=Mi(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t);void 0!==i&&(n[t.useProtoFieldName?s.name:s.jsonName]=i)}const r=t.typeRegistry;if(null==r?void 0:r.findExtensionFor)for(const s of i.runtime.bin.listUnknownFields(e)){const o=r.findExtensionFor(i.typeName,s.no);if(o&&bi(e,o)){const i=vi(e,o,t),s=Mi(o.field,i,t);void 0!==s&&(n[o.field.jsonName]=s)}}}catch(r){const e=s?"cannot encode field ".concat(i.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(i.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw new Error(e+(t.length>0?": ".concat(t):""))}return n},readScalar:(e,t,i)=>Ai(e,t,null!=i?i:si.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t)return i||li(e,t)?Ui(e,t):void 0},debug:xi},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},Fi),e):Fi},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},$i),e):$i},listUnknownFields(e){var t;return null!==(t=e[ji])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ji]},writeUnknownFields(e,t){const i=e[ji];if(i)for(const n of i)t.tag(n.no,n.wireType).raw(n.data)},onUnknownField(e,t,i,n){const s=e;Array.isArray(s[ji])||(s[ji]=[]),s[ji].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,s){const r=e.getType(),o=s?t.len:t.pos+i;let a,c;for(;t.pos<o&&([a,c]=t.tag(),!0!==s||c!=oi.EndGroup);){const i=r.fields.find(a);if(i)Bi(e,t,i,c,n);else{const i=t.skip(c,a);n.readUnknownFields&&this.onUnknownField(e,a,c,i)}}if(s&&(c!=oi.EndGroup||a!==i))throw new Error("invalid end group tag")},readField:Bi,writeMessage(e,t,i){const n=e.getType();for(const s of n.fields.byNumber())if(Ti(s,e))Ki(s,s.oneof?e[s.oneof.localName].value:e[s.localName],t,i);else if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&Ki(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:Bt,initPartial(e,t){if(void 0===e)return;const i=t.getType();for(const n of i.fields.byMember()){const i=n.localName,s=t,r=e;if(null!=r[i])switch(n.kind){case"oneof":const e=r[i].case;if(void 0===e)continue;const t=n.findField(e);let o=r[i].value;t&&"message"==t.kind&&!Ci(o,t.T)?o=new t.T(o):t&&"scalar"===t.kind&&t.T===ii.BYTES&&(o=Yi(o)),s[i]={case:e,value:o};break;case"scalar":case"enum":let a=r[i];n.T===ii.BYTES&&(a=n.repeated?a.map(Yi):Yi(a)),s[i]=a;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===ii.BYTES)for(const[t,n]of Object.entries(r[i]))s[i][t]=Yi(n);else Object.assign(s[i],r[i]);break;case"message":const e=n.V.T;for(const t of Object.keys(r[i])){let n=r[i][t];e.fieldWrapper||(n=new e(n)),s[i][t]=n}}break;case"message":const c=n.T;if(n.repeated)s[i]=r[i].map((e=>Ci(e,c)?e:new c(e)));else{const e=r[i];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?s[i]=Yi(e):s[i]=e:s[i]=Ci(e,c)?e:new c(e)}}}},equals:(e,t,i)=>t===i||!(!t||!i)&&e.fields.byMember().every((e=>{const n=t[e.localName],s=i[e.localName];if(e.repeated){if(n.length!==s.length)return!1;switch(e.kind){case"message":return n.every(((t,i)=>e.T.equals(t,s[i])));case"scalar":return n.every(((t,i)=>ci(e.T,t,s[i])));case"enum":return n.every(((e,t)=>ci(ii.INT32,e,s[t])))}throw new Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":return e.T.equals(n,s);case"enum":return ci(ii.INT32,n,s);case"scalar":return ci(e.T,n,s);case"oneof":if(n.case!==s.case)return!1;const t=e.findField(n.case);if(void 0===t)return!0;switch(t.kind){case"message":return t.T.equals(n.value,s.value);case"enum":return ci(ii.INT32,n.value,s.value);case"scalar":return ci(t.T,n.value,s.value)}throw new Error("oneof cannot contain ".concat(t.kind));case"map":const i=Object.keys(n).concat(Object.keys(s));switch(e.V.kind){case"message":const t=e.V.T;return i.every((e=>t.equals(n[e],s[e])));case"enum":return i.every((e=>ci(ii.INT32,n[e],s[e])));case"scalar":const r=e.V.T;return i.every((e=>ci(r,n[e],s[e])))}}})),clone(e){const t=e.getType(),i=new t,n=i;for(const s of t.fields.byMember()){const t=e[s.localName];let i;if(s.repeated)i=t.map(Ji);else if("map"==s.kind){i=n[s.localName];for(const[e,n]of Object.entries(t))i[e]=Ji(n)}else i="oneof"==s.kind?s.findField(t.case)?{case:t.case,value:Ji(t.value)}:{case:void 0}:Ji(t);n[s.localName]=i}for(const s of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return i}}),{newFieldList:ln,initFields:un}),makeMessageType(e,t,i){return function(e,t,i,n){var s;const r=null!==(s=null==n?void 0:n.localName)&&void 0!==s?s:t.substring(t.lastIndexOf(".")+1),o={[r]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[r];return Object.setPrototypeOf(o.prototype,new zt),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>(new o).fromBinary(e,t),fromJson:(e,t)=>(new o).fromJson(e,t),fromJsonString:(e,t)=>(new o).fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:function(e,t,i){const n={};for(const s of t){const e=qt(s);n[e.localName]=e.no,n[e.no]=e.localName}return Bt(n,e,t),n},makeEnumType:Vt,getEnumType:function(e){const t=e[$t];return Lt(t,"missing enum type on enum object"),t},makeExtension(e,t,i){return function(e,t,i,n){let s;return{typeName:t,extendee:i,get field(){if(!s){const i="function"==typeof n?n():n;i.name=t.split(".").pop(),i.jsonName="[".concat(t,"]"),s=e.util.newFieldList([i]).list()[0]}return s},runtime:e}}(this,e,t,i)}});var ln,un;class hn extends zt{constructor(e){super(),this.seconds=ti.zero,this.nanos=0,dn.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(dn.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=ti.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return hn.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new hn({seconds:ti.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return(new hn).fromBinary(e,t)}static fromJson(e,t){return(new hn).fromJson(e,t)}static fromJsonString(e,t){return(new hn).fromJsonString(e,t)}static equals(e,t){return dn.util.equals(hn,e,t)}}hn.runtime=dn,hn.typeName="google.protobuf.Timestamp",hn.fields=dn.util.newFieldList((()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]));const pn=dn.makeMessageType("livekit.MetricsBatch",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:hn},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:mn,repeated:!0},{no:5,name:"events",kind:"message",T:fn,repeated:!0}])),mn=dn.makeMessageType("livekit.TimeSeriesMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:gn,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}])),gn=dn.makeMessageType("livekit.MetricSample",(()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:hn},{no:3,name:"value",kind:"scalar",T:2}])),fn=dn.makeMessageType("livekit.EventMetric",(()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:hn},{no:7,name:"normalized_end_timestamp",kind:"message",T:hn,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}])),vn=dn.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),yn=dn.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),bn=dn.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),kn=dn.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Tn=dn.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Sn=dn.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Cn=dn.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"}]),wn=dn.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),En=dn.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),_n=dn.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"}]),Pn=dn.makeMessageType("livekit.Room",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Rn,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:rs}])),Rn=dn.makeMessageType("livekit.Codec",(()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}])),xn=dn.makeMessageType("livekit.ParticipantPermission",(()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:dn.getEnumType(bn),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}])),On=dn.makeMessageType("livekit.ParticipantInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:dn.getEnumType(In)},{no:4,name:"tracks",kind:"message",T:Ln,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:xn},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:dn.getEnumType(An)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:dn.getEnumType(Cn)},{no:18,name:"kind_details",kind:"enum",T:dn.getEnumType(Nn),repeated:!0}])),In=dn.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),An=dn.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Nn=dn.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),Dn=dn.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Mn=dn.makeMessageType("livekit.SimulcastCodecInfo",(()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Un,repeated:!0}])),Ln=dn.makeMessageType("livekit.TrackInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:dn.getEnumType(yn)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:dn.getEnumType(bn)},{no:10,name:"layers",kind:"message",T:Un,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Mn,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:dn.getEnumType(Dn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:rs},{no:19,name:"audio_features",kind:"enum",T:dn.getEnumType(_n),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:dn.getEnumType(vn)}])),Un=dn.makeMessageType("livekit.VideoLayer",(()=>[{no:1,name:"quality",kind:"enum",T:dn.getEnumType(kn)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13}])),jn=dn.makeMessageType("livekit.DataPacket",(()=>[{no:1,name:"kind",kind:"enum",T:dn.getEnumType(Fn)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Vn,oneof:"value"},{no:3,name:"speaker",kind:"message",T:$n,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:qn,oneof:"value"},{no:7,name:"transcription",kind:"message",T:zn,oneof:"value"},{no:8,name:"metrics",kind:"message",T:pn,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Zn,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Hn,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Gn,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Wn,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ds,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ls,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:us,oneof:"value"}])),Fn=dn.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),$n=dn.makeMessageType("livekit.ActiveSpeakerUpdate",(()=>[{no:1,name:"speakers",kind:"message",T:Bn,repeated:!0}])),Bn=dn.makeMessageType("livekit.SpeakerInfo",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}])),Vn=dn.makeMessageType("livekit.UserPacket",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}])),qn=dn.makeMessageType("livekit.SipDTMF",(()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}])),zn=dn.makeMessageType("livekit.Transcription",(()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Kn,repeated:!0}])),Kn=dn.makeMessageType("livekit.TranscriptionSegment",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}])),Zn=dn.makeMessageType("livekit.ChatMessage",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}])),Hn=dn.makeMessageType("livekit.RpcRequest",(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}])),Gn=dn.makeMessageType("livekit.RpcAck",(()=>[{no:1,name:"request_id",kind:"scalar",T:9}])),Wn=dn.makeMessageType("livekit.RpcResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Jn,oneof:"value"}])),Jn=dn.makeMessageType("livekit.RpcError",(()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}])),Yn=dn.makeMessageType("livekit.ParticipantTracks",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}])),Qn=dn.makeMessageType("livekit.ServerInfo",(()=>[{no:1,name:"edition",kind:"enum",T:dn.getEnumType(Xn)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}])),Xn=dn.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),es=dn.makeMessageType("livekit.ClientInfo",(()=>[{no:1,name:"sdk",kind:"enum",T:dn.getEnumType(ts)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}])),ts=dn.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"}]),is=dn.makeMessageType("livekit.ClientConfiguration",(()=>[{no:1,name:"video",kind:"message",T:ns},{no:2,name:"screen",kind:"message",T:ns},{no:3,name:"resume_connection",kind:"enum",T:dn.getEnumType(Sn)},{no:4,name:"disabled_codecs",kind:"message",T:ss},{no:5,name:"force_relay",kind:"enum",T:dn.getEnumType(Sn)}])),ns=dn.makeMessageType("livekit.VideoConfiguration",(()=>[{no:1,name:"hardware_encoder",kind:"enum",T:dn.getEnumType(Sn)}])),ss=dn.makeMessageType("livekit.DisabledCodecs",(()=>[{no:1,name:"codecs",kind:"message",T:Rn,repeated:!0},{no:2,name:"publish",kind:"message",T:Rn,repeated:!0}])),rs=dn.makeMessageType("livekit.TimedVersion",(()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}])),os=dn.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),as=dn.makeMessageType("livekit.DataStream.TextHeader",(()=>[{no:1,name:"operation_type",kind:"enum",T:dn.getEnumType(os)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}]),{localName:"DataStream_TextHeader"}),cs=dn.makeMessageType("livekit.DataStream.ByteHeader",(()=>[{no:1,name:"name",kind:"scalar",T:9}]),{localName:"DataStream_ByteHeader"}),ds=dn.makeMessageType("livekit.DataStream.Header",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:dn.getEnumType(Dn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:as,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:cs,oneof:"content_header"}]),{localName:"DataStream_Header"}),ls=dn.makeMessageType("livekit.DataStream.Chunk",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}]),{localName:"DataStream_Chunk"}),us=dn.makeMessageType("livekit.DataStream.Trailer",(()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]),{localName:"DataStream_Trailer"}),hs=dn.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),ps=dn.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),ms=dn.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),gs=dn.makeMessageType("livekit.SignalRequest",(()=>[{no:1,name:"offer",kind:"message",T:Es,oneof:"message"},{no:2,name:"answer",kind:"message",T:Es,oneof:"message"},{no:3,name:"trickle",kind:"message",T:bs,oneof:"message"},{no:4,name:"add_track",kind:"message",T:ys,oneof:"message"},{no:5,name:"mute",kind:"message",T:ks,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Ps,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Rs,oneof:"message"},{no:8,name:"leave",kind:"message",T:Is,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Ns,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Zs,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Gs,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Js,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ds,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ys,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:xs,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Os,oneof:"message"}])),fs=dn.makeMessageType("livekit.SignalResponse",(()=>[{no:1,name:"join",kind:"message",T:Ts,oneof:"message"},{no:2,name:"answer",kind:"message",T:Es,oneof:"message"},{no:3,name:"offer",kind:"message",T:Es,oneof:"message"},{no:4,name:"trickle",kind:"message",T:bs,oneof:"message"},{no:5,name:"update",kind:"message",T:_s,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Cs,oneof:"message"},{no:8,name:"leave",kind:"message",T:Is,oneof:"message"},{no:9,name:"mute",kind:"message",T:ks,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ls,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Us,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Fs,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Bs,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:zs,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Hs,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ws,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Ss,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Qs,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:tr,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ir,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:sr,oneof:"message"}])),vs=dn.makeMessageType("livekit.SimulcastCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}])),ys=dn.makeMessageType("livekit.AddTrackRequest",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:dn.getEnumType(yn)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:dn.getEnumType(bn)},{no:9,name:"layers",kind:"message",T:Un,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:vs,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:dn.getEnumType(Dn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:dn.getEnumType(vn)}])),bs=dn.makeMessageType("livekit.TrickleRequest",(()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:dn.getEnumType(hs)},{no:3,name:"final",kind:"scalar",T:8}])),ks=dn.makeMessageType("livekit.MuteTrackRequest",(()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}])),Ts=dn.makeMessageType("livekit.JoinResponse",(()=>[{no:1,name:"room",kind:"message",T:Pn},{no:2,name:"participant",kind:"message",T:On},{no:3,name:"other_participants",kind:"message",T:On,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Ms,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:is},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Qn},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Rn,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}])),Ss=dn.makeMessageType("livekit.ReconnectResponse",(()=>[{no:1,name:"ice_servers",kind:"message",T:Ms,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:is}])),Cs=dn.makeMessageType("livekit.TrackPublishedResponse",(()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ln}])),ws=dn.makeMessageType("livekit.TrackUnpublishedResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}])),Es=dn.makeMessageType("livekit.SessionDescription",(()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}])),_s=dn.makeMessageType("livekit.ParticipantUpdate",(()=>[{no:1,name:"participants",kind:"message",T:On,repeated:!0}])),Ps=dn.makeMessageType("livekit.UpdateSubscription",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Yn,repeated:!0}])),Rs=dn.makeMessageType("livekit.UpdateTrackSettings",(()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:dn.getEnumType(kn)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}])),xs=dn.makeMessageType("livekit.UpdateLocalAudioTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:dn.getEnumType(_n),repeated:!0}])),Os=dn.makeMessageType("livekit.UpdateLocalVideoTrack",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}])),Is=dn.makeMessageType("livekit.LeaveRequest",(()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:dn.getEnumType(Cn)},{no:3,name:"action",kind:"enum",T:dn.getEnumType(As)},{no:4,name:"regions",kind:"message",T:Xs}])),As=dn.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Ns=dn.makeMessageType("livekit.UpdateVideoLayers",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Un,repeated:!0}])),Ds=dn.makeMessageType("livekit.UpdateParticipantMetadata",(()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}])),Ms=dn.makeMessageType("livekit.ICEServer",(()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}])),Ls=dn.makeMessageType("livekit.SpeakersChanged",(()=>[{no:1,name:"speakers",kind:"message",T:Bn,repeated:!0}])),Us=dn.makeMessageType("livekit.RoomUpdate",(()=>[{no:1,name:"room",kind:"message",T:Pn}])),js=dn.makeMessageType("livekit.ConnectionQualityInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:dn.getEnumType(Tn)},{no:3,name:"score",kind:"scalar",T:2}])),Fs=dn.makeMessageType("livekit.ConnectionQualityUpdate",(()=>[{no:1,name:"updates",kind:"message",T:js,repeated:!0}])),$s=dn.makeMessageType("livekit.StreamStateInfo",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:dn.getEnumType(ps)}])),Bs=dn.makeMessageType("livekit.StreamStateUpdate",(()=>[{no:1,name:"stream_states",kind:"message",T:$s,repeated:!0}])),Vs=dn.makeMessageType("livekit.SubscribedQuality",(()=>[{no:1,name:"quality",kind:"enum",T:dn.getEnumType(kn)},{no:2,name:"enabled",kind:"scalar",T:8}])),qs=dn.makeMessageType("livekit.SubscribedCodec",(()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Vs,repeated:!0}])),zs=dn.makeMessageType("livekit.SubscribedQualityUpdate",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Vs,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:qs,repeated:!0}])),Ks=dn.makeMessageType("livekit.TrackPermission",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}])),Zs=dn.makeMessageType("livekit.SubscriptionPermission",(()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Ks,repeated:!0}])),Hs=dn.makeMessageType("livekit.SubscriptionPermissionUpdate",(()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}])),Gs=dn.makeMessageType("livekit.SyncState",(()=>[{no:1,name:"answer",kind:"message",T:Es},{no:2,name:"subscription",kind:"message",T:Ps},{no:3,name:"publish_tracks",kind:"message",T:Cs,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Ws,repeated:!0},{no:5,name:"offer",kind:"message",T:Es},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}])),Ws=dn.makeMessageType("livekit.DataChannelInfo",(()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:dn.getEnumType(hs)}])),Js=dn.makeMessageType("livekit.SimulateScenario",(()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:dn.getEnumType(ms),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}])),Ys=dn.makeMessageType("livekit.Ping",(()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}])),Qs=dn.makeMessageType("livekit.Pong",(()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}])),Xs=dn.makeMessageType("livekit.RegionSettings",(()=>[{no:1,name:"regions",kind:"message",T:er,repeated:!0}])),er=dn.makeMessageType("livekit.RegionInfo",(()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}])),tr=dn.makeMessageType("livekit.SubscriptionResponse",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:dn.getEnumType(En)}])),ir=dn.makeMessageType("livekit.RequestResponse",(()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:dn.getEnumType(nr)},{no:3,name:"message",kind:"scalar",T:9}])),nr=dn.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),sr=dn.makeMessageType("livekit.TrackSubscribed",(()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]));function rr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var or,ar,cr,dr,lr,ur,hr,pr,mr={exports:{}},gr=(or||(or=1,cr=mr.exports,dr=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],s={},r=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(n){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var i=this.getLevel(),s=0;s<n.length;s++){var r=n[s];this[r]=s<i?e:this.methodFactory(r,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function l(n,s,r){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?a:void 0!==console[n]?o(console,n):void 0!==console.log?o(console,"log"):e)}(n)||d.apply(this,arguments)}function u(e,i){var o,a,d,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(r){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),s=i.indexOf(n+"=");-1!==s&&(e=/^([^;]+)/.exec(i.slice(s+n.length+1))[1])}catch(r){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||l,u.getLevel=function(){return null!=d?d:null!=a?a:o},u.setLevel=function(e,i){return d=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{return void(window.localStorage[h]=i)}catch(s){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(s){}}}(d),c.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){d=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(r!==u&&(o=m(r.getLevel())),c.call(u),r===u)for(var e in s)s[e].rebuild()},o=m(r?r.getLevel():"WARN");var g=p();null!=g&&(d=m(g)),c.call(u)}(r=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=s[e];return t||(t=s[e]=new u(e,r.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return r.noConflict=function(){return typeof window!==t&&window.log===r&&(window.log=h),r},r.getLoggers=function(){return s},r.default=r,r},(ar=mr).exports?ar.exports=dr():cr.log=dr()),mr.exports);(ur=lr||(lr={}))[ur.trace=0]="trace",ur[ur.debug=1]="debug",ur[ur.info=2]="info",ur[ur.warn=3]="warn",ur[ur.error=4]="error",ur[ur.silent=5]="silent",(pr=hr||(hr={})).Default="livekit",pr.Room="livekit-room",pr.Participant="livekit-participant",pr.Track="livekit-track",pr.Publication="livekit-track-publication",pr.Engine="livekit-engine",pr.Signal="livekit-signal",pr.PCManager="livekit-pc-manager",pr.PCTransport="livekit-pc-transport",pr.E2EE="lk-e2ee";let fr=gr.getLogger("livekit");function vr(e){const t=gr.getLogger(e);return t.setDefaultLevel(fr.getLevel()),t}Object.values(hr).map((e=>gr.getLogger(e))),fr.setDefaultLevel(lr.info);const yr=gr.getLogger("lk-e2ee"),br=7e3,kr=[0,300,1200,2700,4800,br,br,br,br,br];function Tr(e,t,i,n){return new(i||(i=Promise))((function(s,r){function o(e){try{c(n.next(e))}catch(t){r(t)}}function a(e){try{c(n.throw(e))}catch(t){r(t)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}function Sr(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,s){!function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)}(n,s,(t=e[i](t)).done,t.value)}))}}}"function"==typeof SuppressedError&&SuppressedError;var Cr,wr={exports:{}},Er=function(){if(Cr)return wr.exports;Cr=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}wr.exports=s,wr.exports.once=function(e,t){return new Promise((function(i,n){function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,r,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,s)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var r=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var s,r,c,d;if(o(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),c=r[t]),void 0===c)c=r[t]=i,++e._eventsCount;else if("function"==typeof c?c=r[t]=n?[i,c]:[c,i]:n?c.unshift(i):c.push(i),(s=a(e))>0&&c.length>s&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,d=l,console&&console.warn&&console.warn(d)}return e}function d(){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 l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=d.bind(n);return s.listener=i,n.wrapFn=s,s}function u(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):p(s,s.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);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 s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return r},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");r=e}}),s.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},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(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},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s="error"===e,r=this._events;if(void 0!==r)s=s&&void 0===r.error;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var d=c.length,l=p(c,d);for(n=0;n<d;++n)i(l[n],this,t)}return!0},s.prototype.addListener=function(e,t){return c(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return c(this,e,t,!0)},s.prototype.once=function(e,t){return o(t),this.on(e,l(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,l(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,n,s,r,a;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[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},s.prototype.listeners=function(e){return u(this,e,!0)},s.prototype.rawListeners=function(e){return u(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h,s.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},wr.exports}();let _r=!0,Pr=!0;function Rr(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function xr(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return s.apply(this,arguments);const r=e=>{const t=i(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,r),s.apply(this,[e,r])};const r=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return r.apply(this,arguments);if(!this._eventMap[t].has(i))return r.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,r.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 Or(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(_r=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Ir(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Pr=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Ar(){if("object"==typeof window){if(_r)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Nr(e,t){Pr&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Dr(e){return"[object Object]"===Object.prototype.toString.call(e)}function Mr(e){return Dr(e)?Object.keys(e).reduce((function(t,i){const n=Dr(e[i]),s=n?Mr(e[i]):e[i],r=n&&!Object.keys(s).length;return void 0===s||r?t:Object.assign(t,{[i]:s})}),{}):e}function Lr(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach((n=>{n.endsWith("Id")?Lr(e,e.get(t[n]),i):n.endsWith("Ids")&&t[n].forEach((t=>{Lr(e,e.get(t),i)}))})))}function Ur(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",s=new Map;if(null===t)return s;const r=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&r.push(e)})),r.forEach((t=>{e.forEach((i=>{i.type===n&&i.trackId===t.id&&Lr(e,i,s)}))})),s}const jr=Ar;function Fr(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const s=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[s("min",i)]=n.ideal,t.optional.push(e),e={},e[s("max",i)]=n.ideal,t.optional.push(e)):(e[s("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[s("",i)]=n.exact):["min","max"].forEach((e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[s(e,i)]=n[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},s=function(e,s){if(t.version>=61)return s(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=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 r=e.video.facingMode;r=r&&("object"==typeof r?r:{ideal:r});const o=t.version<66;if(r&&("user"===r.exact||"environment"===r.exact||"user"===r.ideal||"environment"===r.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===r.exact||"environment"===r.ideal?t=["back","rear"]:"user"!==r.exact&&"user"!==r.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then((i=>{let o=(i=i.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=r.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),jr("chrome: "+JSON.stringify(e)),s(e)}))}e.video=n(e.video)}return jr("chrome: "+JSON.stringify(e)),s(e)},r=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(i.getUserMedia=function(e,t,n){s(e,(e=>{i.webkitGetUserMedia(e,t,(e=>{n&&n(r(e))}))}))}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return s(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(r(e))))))}}}function $r(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Br(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",(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.track.id)):{track:i.track};const s=new Event("track");s.track=i.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)})),t.stream.getTracks().forEach((i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===i.id)):{track:i};const s=new Event("track");s.track=i,s.receiver=n,s.transceiver={receiver:n},s.streams=[t.stream],this.dispatchEvent(s)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else xr(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function Vr(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 i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let s=i.apply(this,arguments);return s||(s=t(this,e),this._senders.push(s)),s};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 i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.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 qr(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 i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ur(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}),xr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Ur(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,i,n;return this.getSenders().forEach((i=>{i.track===e&&(t?n=!0:t=i)})),this.getReceivers().forEach((t=>(t.track===e&&(i?n=!0:i=t),t.track===e))),n||t&&i?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function zr(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,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=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();i.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 s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),s.apply(this,arguments)}}function Kr(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return zr(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.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 i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const s=e.RTCPeerConnection.prototype.removeStream;function r(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(s.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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,i){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 s=this._streams[i.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=r(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then((e=>r(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 i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const n=e._reverseStreams[t],s=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),s.id)})),new RTCSessionDescription({type:t.type,sdp:i})}(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:r(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((i=>{this._streams[i].getTracks().find((t=>e.track===t))&&(t=this._streams[i])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Zr(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function Hr(e,t){xr(e,"negotiationneeded",(e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e}))}var Gr=Object.freeze({__proto__:null,fixNegotiationNeeded:Hr,shimAddTrackRemoveTrack:Kr,shimAddTrackRemoveTrackWithNative:zr,shimGetSendersWithDtmf:Vr,shimGetUserMedia:Fr,shimMediaStream:$r,shimOnTrack:Br,shimPeerConnection:Zr,shimSenderReceiverGetStats:qr});function Wr(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){Nr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}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 Yr(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 i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={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,s,r]=arguments;return n.apply(this,[e||null]).then((e=>{if(t.version<53&&!s)try{e.forEach((e=>{e.type=i[e.type]||e.type}))}catch(n){if("TypeError"!==n.name)throw n;e.forEach(((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))}))}return e})).then(s,r)}}function Qr(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 i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.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 Xr(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}),xr(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function eo(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Nr("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function to(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function io(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 i=e.length>0;i&&e.forEach((e=>{if("rid"in e&&!/^[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(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return n})}function no(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 so(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 ro(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 oo=Object.freeze({__proto__:null,shimAddTransceiver:io,shimCreateAnswer:ro,shimCreateOffer:so,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:no,shimGetUserMedia:Wr,shimOnTrack:Jr,shimPeerConnection:Yr,shimRTCDataChannel:to,shimReceiverGetStats:Xr,shimRemoveStream:eo,shimSenderGetStats:Qr});function ao(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((i=>t.call(this,i,e))),e.getVideoTracks().forEach((i=>t.call(this,i,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),s=1;s<i;s++)n[s-1]=arguments[s];return n&&n.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 i=e.getTracks();this.getSenders().forEach((e=>{i.includes(e.track)&&this.removeTrack(e)}))})}}function co(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 i=new Event("addstream");i.stream=t,e.dispatchEvent(i)}))}),t.apply(e,arguments)}}}function lo(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,s=t.setLocalDescription,r=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],s=i.apply(this,[n]);return t?(s.then(e,t),Promise.resolve()):s},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],s=n.apply(this,[i]);return t?(s.then(e,t),Promise.resolve()):s};let a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function uo(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(ho(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function ho(e){return e&&void 0!==e.video?Object.assign({},e,{video:Mr(e.video)}):e}function po(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(Nr("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function mo(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 go(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 i=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function fo(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var vo,yo=Object.freeze({__proto__:null,shimAudioContext:fo,shimCallbacksAPI:lo,shimConstraints:ho,shimCreateOfferLegacy:go,shimGetUserMedia:uo,shimLocalStreamsAPI:ao,shimRTCIceServerUrls:po,shimRemoteStreamsAPI:co,shimTrackEventTransceiver:mo}),bo={exports:{}},ko=(vo||(vo=1,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 i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter((e=>0===e.indexOf(i)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={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 n=8;n<t.length;n+=2)switch(t[n]){case"raddr":i.relatedAddress=t[n+1];break;case"rport":i.relatedPort=parseInt(t[n+1],10);break;case"tcptype":i.tcpType=t[n+1];break;case"ufrag":i.ufrag=t[n+1],i.usernameFragment=t[n+1];break;default:void 0===i[t[n]]&&(i[t[n]]=t[n+1])}return i},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),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 i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\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 i;const n=e.substring(e.indexOf(" ")+1).split(";");for(let s=0;s<n.length;s++)i=n[s].trim().split("="),t[i[0].trim()]=i[1];return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=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:"+i+" "+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="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},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 i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.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,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),i},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,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],s=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.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 i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){const s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){const n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{i.headerExtensions.push(t.parseExtmap(e))}));const s=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach((e=>{s.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.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",i.codecs.forEach((e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)}));let s=0;return i.codecs.forEach((e=>{e.maxptime>s&&(s=e.maxptime)})),s>0&&(n+="a=maxptime:"+s+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach((e=>{n+=t.writeExtmap(e)})),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),r=-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}),i.push(t),s&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:r?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&a&&i.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,i.forEach((e=>{e.maxBitrate=l}))),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=0===s.length;const r=t.matchPrefix(e,"a=rtcp-mux");return i.mux=r.length>0,i},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 i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return s.length>0?(i=s[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const r=t.matchPrefix(e,"a=sctp-port:");if(r.length>0)return{port:parseInt(r[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};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:s}}},t.writeSctpDescription=function(e,t){let i=[];return i="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&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){let s;const r=void 0!==i?i:2;return s=e||t.generateSessionId(),"v=0\r\no="+(n||"thisisadapterortc")+" "+s+" "+r+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let t=0;t<n.length;t++)switch(n[t]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[t].substring(2)}return i?t.getDirection(i):"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 i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let t=0;t<i.length;t++)if(i[t].length<2||"="!==i[t].charAt(1))return!1;return!0},e.exports=t}(bo)),bo.exports),To=rr(ko),So=At({__proto__:null,default:To},[ko]);function Co(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 i=new t(e),n=To.parseCandidate(e.candidate);for(const e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,xr(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function wo(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||xr(e,"icecandidate",(e=>{if(e.candidate){const t=To.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function Eo(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 i=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=To.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=To.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 i=parseInt(t[1],10);return i!=i?-1:i}(arguments[0]),i=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i}(e),n=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const s=To.matchPrefix(e.sdp,"a=max-message-size:");return s.length>0?n=parseInt(s[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n}(arguments[0],e);let s;s=0===i&&0===n?Number.POSITIVE_INFINITY:0===i||0===n?Math.max(i,n):Math.min(i,n);const r={};Object.defineProperty(r,"maxMessageSize",{get:()=>s}),this._sctp=r}return i.apply(this,arguments)}}function _o(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],s=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&s>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},xr(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Po(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 i=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 i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}}))}function Ro(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=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:i}):t.sdp=i}return i.apply(this,arguments)}}function xo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.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():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Oo(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.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"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>i.apply(this,[e])))})}var Io=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ro,shimAddIceCandidateNullOrEmpty:xo,shimConnectionState:Po,shimMaxMessageSize:Eo,shimParameterlessSetLocalDescription:Oo,shimRTCIceCandidate:Co,shimRTCIceCandidateRelayProtocol:wo,shimSendThrowTypeError:_o});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=Ar,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:i}=e;if(i.userAgentData&&i.userAgentData.brands){const e=i.userAgentData.brands.find((e=>"Chromium"===e.brand));if(e)return{browser:"chrome",version:parseInt(e.version,10)}}if(i.mozGetUserMedia)t.browser="firefox",t.version=Rr(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=Rr(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=Rr(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),s={browserDetails:n,commonShim:Io,extractVersion:Rr,disableLog:Or,disableWarnings:Ir,sdp:So};switch(n.browser){case"chrome":if(!Gr||!Zr||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),s;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),s;i("adapter.js shimming chrome."),s.browserShim=Gr,xo(e,n),Oo(e),Fr(e,n),$r(e),Zr(e,n),Br(e),Kr(e,n),Vr(e),qr(e),Hr(e,n),Co(e),wo(e),Po(e),Eo(e,n),_o(e),Ro(e,n);break;case"firefox":if(!oo||!Yr||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),s;i("adapter.js shimming firefox."),s.browserShim=oo,xo(e,n),Oo(e),Wr(e,n),Yr(e,n),Jr(e),eo(e),Qr(e),Xr(e),to(e),io(e),no(e),so(e),ro(e),Co(e),Po(e),Eo(e,n),_o(e);break;case"safari":if(!yo||!t.shimSafari)return i("Safari shim is not included in this adapter release."),s;i("adapter.js shimming safari."),s.browserShim=yo,xo(e,n),Oo(e),po(e),go(e),lo(e),ao(e),co(e),mo(e),uo(e),fo(e),Co(e),wo(e),Eo(e,n),_o(e),Ro(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});const Ao="lk_e2ee";var No,Do,Mo,Lo,Uo,jo,Fo,$o,Bo,Vo,qo,zo,Ko,Zo,Ho,Go,Wo,Jo,Yo,Qo;function Xo(){return void 0!==window.RTCRtpScriptTransform}(Do=No||(No={})).SetKey="setKey",Do.RatchetRequest="ratchetRequest",Do.KeyRatcheted="keyRatcheted",(Mo||(Mo={})).KeyRatcheted="keyRatcheted",(Uo=Lo||(Lo={})).ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Uo.EncryptionError="encryptionError",(jo||(jo={})).Error="cryptorError",Er.EventEmitter;class ea extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}($o=Fo||(Fo={}))[$o.NotAllowed=0]="NotAllowed",$o[$o.ServerUnreachable=1]="ServerUnreachable",$o[$o.InternalError=2]="InternalError",$o[$o.Cancelled=3]="Cancelled",$o[$o.LeaveRequest=4]="LeaveRequest";class ta extends ea{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=Fo[t]}}class ia extends ea{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class na extends ea{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class sa extends ea{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class ra extends ea{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class oa extends ea{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class aa extends ea{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class ca extends ea{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:nr[t]}}(Vo=Bo||(Bo={})).PermissionDenied="PermissionDenied",Vo.NotFound="NotFound",Vo.DeviceInUse="DeviceInUse",Vo.Other="Other",function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(Bo||(Bo={})),(zo=qo||(qo={}))[zo.InvalidKey=0]="InvalidKey",zo[zo.MissingKey=1]="MissingKey",zo[zo.InternalError=2]="InternalError",(Zo=Ko||(Ko={})).Connected="connected",Zo.Reconnecting="reconnecting",Zo.SignalReconnecting="signalReconnecting",Zo.Reconnected="reconnected",Zo.Disconnected="disconnected",Zo.ConnectionStateChanged="connectionStateChanged",Zo.MediaDevicesChanged="mediaDevicesChanged",Zo.ParticipantConnected="participantConnected",Zo.ParticipantDisconnected="participantDisconnected",Zo.TrackPublished="trackPublished",Zo.TrackSubscribed="trackSubscribed",Zo.TrackSubscriptionFailed="trackSubscriptionFailed",Zo.TrackUnpublished="trackUnpublished",Zo.TrackUnsubscribed="trackUnsubscribed",Zo.TrackMuted="trackMuted",Zo.TrackUnmuted="trackUnmuted",Zo.LocalTrackPublished="localTrackPublished",Zo.LocalTrackUnpublished="localTrackUnpublished",Zo.LocalAudioSilenceDetected="localAudioSilenceDetected",Zo.ActiveSpeakersChanged="activeSpeakersChanged",Zo.ParticipantMetadataChanged="participantMetadataChanged",Zo.ParticipantNameChanged="participantNameChanged",Zo.ParticipantAttributesChanged="participantAttributesChanged",Zo.RoomMetadataChanged="roomMetadataChanged",Zo.DataReceived="dataReceived",Zo.SipDTMFReceived="sipDTMFReceived",Zo.TranscriptionReceived="transcriptionReceived",Zo.ConnectionQualityChanged="connectionQualityChanged",Zo.TrackStreamStateChanged="trackStreamStateChanged",Zo.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Zo.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Zo.AudioPlaybackStatusChanged="audioPlaybackChanged",Zo.VideoPlaybackStatusChanged="videoPlaybackChanged",Zo.MediaDevicesError="mediaDevicesError",Zo.ParticipantPermissionsChanged="participantPermissionsChanged",Zo.SignalConnected="signalConnected",Zo.RecordingStatusChanged="recordingStatusChanged",Zo.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",Zo.EncryptionError="encryptionError",Zo.DCBufferStatusChanged="dcBufferStatusChanged",Zo.ActiveDeviceChanged="activeDeviceChanged",Zo.ChatMessage="chatMessage",Zo.LocalTrackSubscribed="localTrackSubscribed",Zo.MetricsReceived="metricsReceived",(Go=Ho||(Ho={})).TrackPublished="trackPublished",Go.TrackSubscribed="trackSubscribed",Go.TrackSubscriptionFailed="trackSubscriptionFailed",Go.TrackUnpublished="trackUnpublished",Go.TrackUnsubscribed="trackUnsubscribed",Go.TrackMuted="trackMuted",Go.TrackUnmuted="trackUnmuted",Go.LocalTrackPublished="localTrackPublished",Go.LocalTrackUnpublished="localTrackUnpublished",Go.ParticipantMetadataChanged="participantMetadataChanged",Go.ParticipantNameChanged="participantNameChanged",Go.DataReceived="dataReceived",Go.SipDTMFReceived="sipDTMFReceived",Go.TranscriptionReceived="transcriptionReceived",Go.IsSpeakingChanged="isSpeakingChanged",Go.ConnectionQualityChanged="connectionQualityChanged",Go.TrackStreamStateChanged="trackStreamStateChanged",Go.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",Go.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",Go.MediaDevicesError="mediaDevicesError",Go.AudioStreamAcquired="audioStreamAcquired",Go.ParticipantPermissionsChanged="participantPermissionsChanged",Go.PCTrackAdded="pcTrackAdded",Go.AttributesChanged="attributesChanged",Go.LocalTrackSubscribed="localTrackSubscribed",Go.ChatMessage="chatMessage",(Jo=Wo||(Wo={})).TransportsCreated="transportsCreated",Jo.Connected="connected",Jo.Disconnected="disconnected",Jo.Resuming="resuming",Jo.Resumed="resumed",Jo.Restarting="restarting",Jo.Restarted="restarted",Jo.SignalResumed="signalResumed",Jo.SignalRestarted="signalRestarted",Jo.Closing="closing",Jo.MediaTrackAdded="mediaTrackAdded",Jo.ActiveSpeakersUpdate="activeSpeakersUpdate",Jo.DataPacketReceived="dataPacketReceived",Jo.RTPVideoMapUpdate="rtpVideoMapUpdate",Jo.DCBufferStatusChanged="dcBufferStatusChanged",Jo.ParticipantUpdate="participantUpdate",Jo.RoomUpdate="roomUpdate",Jo.SpeakersChanged="speakersChanged",Jo.StreamStateChanged="streamStateChanged",Jo.ConnectionQualityUpdate="connectionQualityUpdate",Jo.SubscriptionError="subscriptionError",Jo.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",Jo.RemoteMute="remoteMute",Jo.SubscribedQualityUpdate="subscribedQualityUpdate",Jo.LocalTrackUnpublished="localTrackUnpublished",Jo.LocalTrackSubscribed="localTrackSubscribed",Jo.Offline="offline",Jo.SignalRequestResponse="signalRequestResponse",Jo.SignalConnected="signalConnected",(Qo=Yo||(Yo={})).Message="message",Qo.Muted="muted",Qo.Unmuted="unmuted",Qo.Restarted="restarted",Qo.Ended="ended",Qo.Subscribed="subscribed",Qo.Unsubscribed="unsubscribed",Qo.UpdateSettings="updateSettings",Qo.UpdateSubscription="updateSubscription",Qo.AudioPlaybackStarted="audioPlaybackStarted",Qo.AudioPlaybackFailed="audioPlaybackFailed",Qo.AudioSilenceDetected="audioSilenceDetected",Qo.VisibilityChanged="visibilityChanged",Qo.VideoDimensionsChanged="videoDimensionsChanged",Qo.VideoPlaybackStarted="videoPlaybackStarted",Qo.VideoPlaybackFailed="videoPlaybackFailed",Qo.ElementAttached="elementAttached",Qo.ElementDetached="elementDetached",Qo.UpstreamPaused="upstreamPaused",Qo.UpstreamResumed="upstreamResumed",Qo.SubscriptionPermissionChanged="subscriptionPermissionChanged",Qo.SubscriptionStatusChanged="subscriptionStatusChanged",Qo.SubscriptionFailed="subscriptionFailed",Qo.TrackProcessorUpdate="trackProcessorUpdate",Qo.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",Qo.TranscriptionReceived="transcriptionReceived",Qo.TimeSyncUpdate="timeSyncUpdate";const da=/version\/(\d+(\.?_?\d+)+)/i;let la;function ua(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;const i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===la||t){const e=ha.find((e=>{let{test:t}=e;return t.test(i)}));la=null==e?void 0:e.describe(i)}return la}const ha=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:pa(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ma(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:pa(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ma(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:pa(da,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:ma(e)})}];function pa(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;const n=t.match(e);return n&&n.length>=i&&n[i]||""}function ma(e){return e.includes("mac os")?pa(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class ga{}ga.setTimeout=function(){return setTimeout(...arguments)},ga.setInterval=function(){return setInterval(...arguments)},ga.clearTimeout=function(){return clearTimeout(...arguments)},ga.clearInterval=function(){return clearInterval(...arguments)};const fa=[];var va,ya;(ya=va||(va={}))[ya.LOW=0]="LOW",ya[ya.MEDIUM=1]="MEDIUM",ya[ya.HIGH=2]="HIGH";class ba extends Er.EventEmitter{constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};var n;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=ba.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=fr,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout((()=>this.handleAppVisibilityChanged()),5e3):this.handleAppVisibilityChanged()},this.log=vr(null!==(n=i.loggerName)&&void 0!==n?n:hr.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=ba.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),_c(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===ba.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===ba.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(fa.forEach((t=>{null!==t.parentElement||e||(e=t)})),e&&fa.splice(fa.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ka(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),n=i.some((e=>"audio"===e.kind));return e.play().then((()=>{this.emit(n?Yo.AudioPlaybackStarted:Yo.VideoPlaybackStarted)})).catch((t=>{"NotAllowedError"===t.name?this.emit(n?Yo.AudioPlaybackFailed:Yo.VideoPlaybackFailed,t):"AbortError"===t.name?fr.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):fr.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some((e=>"video"===e.kind))&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch((()=>{})))})),this.emit(Yo.ElementAttached,e),e}detach(e){try{if(e){Ta(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Yo.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach((e=>{Ta(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Yo.ElementDetached,e)})),this.attachedElements=[],t}finally{0===this.attachedElements.length&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=vr(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),fa.forEach((e=>{e.parentElement||(t=!1)})),t&&fa.push(e)}}handleAppVisibilityChanged(){return Tr(this,void 0,void 0,(function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==ba.Kind.Video||setTimeout((()=>this.attachedElements.forEach((e=>e.play().catch((()=>{}))))),0)}))}addAppVisibilityListener(){Va()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Va()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ka(e,t){let i,n;i=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream,n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks(),n.includes(e)||(n.forEach((e=>{i.removeTrack(e)})),i.addTrack(e)),$a()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,($a()||Fa())&&t instanceof HTMLVideoElement&&setTimeout((()=>{t.srcObject=i,t.play().catch((()=>{}))}),0))}function Ta(e,t){if(t.srcObject instanceof MediaStream){const i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){let t;var i;let n;var s;let r;var o;(i=t=e.Kind||(e.Kind={})).Audio="audio",i.Video="video",i.Unknown="unknown",(s=n=e.Source||(e.Source={})).Camera="camera",s.Microphone="microphone",s.ScreenShare="screen_share",s.ScreenShareAudio="screen_share_audio",s.Unknown="unknown",(o=r=e.StreamState||(e.StreamState={})).Active="active",o.Paused="paused",o.Unknown="unknown",e.kindToProto=function(e){switch(e){case t.Audio:return yn.AUDIO;case t.Video:return yn.VIDEO;default:return yn.DATA}},e.kindFromProto=function(e){switch(e){case yn.AUDIO:return t.Audio;case yn.VIDEO:return t.Video;default:return t.Unknown}},e.sourceToProto=function(e){switch(e){case n.Camera:return bn.CAMERA;case n.Microphone:return bn.MICROPHONE;case n.ScreenShare:return bn.SCREEN_SHARE;case n.ScreenShareAudio:return bn.SCREEN_SHARE_AUDIO;default:return bn.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case bn.CAMERA:return n.Camera;case bn.MICROPHONE:return n.Microphone;case bn.SCREEN_SHARE:return n.ScreenShare;case bn.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}},e.streamStateFromProto=function(e){switch(e){case ps.ACTIVE:return r.Active;case ps.PAUSED:return r.Paused;default:return r.Unknown}}}(ba||(ba={}));class Sa{constructor(e,t,i,n,s){if("object"==typeof e)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else{if(void 0===t||void 0===i)throw new TypeError("Unsupported options: provide at least width, height and maxBitrate");this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:s}}}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Ca=["vp8","h264"],wa=["vp8","h264","vp9","av1"];function Ea(e){return!!Ca.find((t=>t===e))}var _a,Pa,Ra,xa;(Pa=_a||(_a={}))[Pa.PREFER_REGRESSION=0]="PREFER_REGRESSION",Pa[Pa.SIMULCAST=1]="SIMULCAST",Pa[Pa.REGRESSION=2]="REGRESSION",(xa=Ra||(Ra={})).telephone={maxBitrate:12e3},xa.speech={maxBitrate:24e3},xa.music={maxBitrate:48e3},xa.musicStereo={maxBitrate:64e3},xa.musicHighQuality={maxBitrate:96e3},xa.musicHighQualityStereo={maxBitrate:128e3};const Oa={h90:new Sa(160,90,9e4,20),h180:new Sa(320,180,16e4,20),h216:new Sa(384,216,18e4,20),h360:new Sa(640,360,45e4,20),h540:new Sa(960,540,8e5,25),h720:new Sa(1280,720,17e5,30),h1080:new Sa(1920,1080,3e6,30),h1440:new Sa(2560,1440,5e6,30),h2160:new Sa(3840,2160,8e6,30)},Ia={h120:new Sa(160,120,7e4,20),h180:new Sa(240,180,125e3,20),h240:new Sa(320,240,14e4,20),h360:new Sa(480,360,33e4,20),h480:new Sa(640,480,5e5,20),h540:new Sa(720,540,6e5,25),h720:new Sa(960,720,13e5,30),h1080:new Sa(1440,1080,23e5,30),h1440:new Sa(1920,1440,38e5,30)},Aa={h360fps3:new Sa(640,360,2e5,3,"medium"),h360fps15:new Sa(640,360,4e5,15,"medium"),h720fps5:new Sa(1280,720,8e5,5,"medium"),h720fps15:new Sa(1280,720,15e5,15,"medium"),h720fps30:new Sa(1280,720,2e6,30,"medium"),h1080fps15:new Sa(1920,1080,25e5,15,"medium"),h1080fps30:new Sa(1920,1080,5e6,30,"medium"),original:new Sa(0,0,7e6,30,"medium")},Na="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Da(e){return Tr(this,void 0,void 0,(function*(){return new Promise((t=>ga.setTimeout(t,e)))}))}function Ma(){return"addTransceiver"in RTCPeerConnection.prototype}function La(){return"addTrack"in RTCPeerConnection.prototype}function Ua(e){return"av1"===e||"vp9"===e}function ja(e){return!!document&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function Fa(){var e;return"Firefox"===(null===(e=ua())||void 0===e?void 0:e.name)}function $a(){var e;return"Safari"===(null===(e=ua())||void 0===e?void 0:e.name)}function Ba(){var e,t;return!!Va()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function Va(){return"undefined"!=typeof document}function qa(){return"ReactNative"==navigator.product}function za(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function Ka(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Za(){if(!qa())return;let e=Ka();return e?e.platform:void 0}function Ha(){if(Va())return window.devicePixelRatio;if(qa()){let e=Ka();if(e)return e.devicePixelRatio}return 1}function Ga(e,t){const i=e.split("."),n=t.split("."),s=Math.min(i.length,n.length);for(let r=0;r<s;++r){const e=parseInt(i[r],10),t=parseInt(n[r],10);if(e>t)return 1;if(e<t)return-1;if(r===s-1&&e===t)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function Wa(e){for(const t of e)t.target.handleResize(t)}function Ja(e){for(const t of e)t.target.handleVisibilityChanged(t)}let Ya=null;const Qa=()=>(Ya||(Ya=new ResizeObserver(Wa)),Ya);let Xa=null;const ec=()=>(Xa||(Xa=new IntersectionObserver(Ja,{root:null,rootMargin:"0px"})),Xa);function tc(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d");null==r||r.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(e/2,t/2,50,0,2*Math.PI,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream(),[a]=o.getTracks();if(!a)throw Error("Could not get empty media stream video track");return a.enabled=i,a}let ic;function nc(){if(!ic){const e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);const n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[ic]=n.stream.getAudioTracks(),!ic)throw Error("Could not get empty media stream audio track");ic.enabled=!1}return ic.clone()}class sc{constructor(e,t){this.onFinally=t,this.promise=new Promise(((t,i)=>Tr(this,void 0,void 0,(function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})))).finally((()=>{var e;return null===(e=this.onFinally)||void 0===e?void 0:e.call(this)}))}}function rc(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function oc(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function ac(e){switch(e.reason){case Fo.LeaveRequest:return e.context;case Fo.Cancelled:return Cn.CLIENT_INITIATED;case Fo.NotAllowed:return Cn.USER_REJECTED;case Fo.ServerUnreachable:return Cn.JOIN_FAILURE;default:return Cn.UNKNOWN_REASON}}function cc(e){return void 0!==e?Number(e):void 0}function dc(e){return void 0!==e?BigInt(e):void 0}function lc(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function uc(e){return!!e&&e.kind==ba.Kind.Audio}function hc(e){return!!e&&e.kind==ba.Kind.Video}function pc(e){return lc(e)&&hc(e)}function mc(e){return lc(e)&&uc(e)}function gc(e){return!!e&&!e.isLocal}function fc(e){return!!e&&!e.isLocal}function vc(e){return gc(e)&&hc(e)}function yc(e,t,i){var n,s,r,o;const{optionsWithoutProcessor:a,audioProcessor:c,videoProcessor:d}=Pc(null!=e?e:{}),l=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(bc(h.audio,t),null!==(n=(r=h.audio).deviceId)&&void 0!==n||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=null!=c?c:l)),h.video&&(bc(h.video,i),null!==(s=(o=h.video).deviceId)&&void 0!==s||(o.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=null!=d?d:u)),h}function bc(e,t){return Object.keys(t).forEach((i=>{void 0===e[i]&&(e[i]=t[i])})),e}function kc(e){var t,i,n,s;const r={};if(e.video)if("object"==typeof e.video){const i={},s=i,o=e.video;Object.keys(o).forEach((e=>{"resolution"===e?bc(s,o.resolution):s[e]=o[e]})),r.video=i,null!==(t=(n=r.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else r.video=!!e.video&&{deviceId:{ideal:"default"}};else r.video=!1;return e.audio?"object"==typeof e.audio?(r.audio=e.audio,null!==(i=(s=r.audio).deviceId)&&void 0!==i||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Tc(){var e;const t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){const i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){const e=()=>Tr(this,void 0,void 0,(function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(n){console.warn("Error trying to auto-resume audio context",n)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)}));window.document.body.addEventListener("click",e)}return i}}function Sc(e){return"audioinput"===e?ba.Source.Microphone:"videoinput"===e?ba.Source.Camera:ba.Source.Unknown}function Cc(e){return e===ba.Source.Microphone?"audioinput":e===ba.Source.Camera?"videoinput":void 0}function wc(e){return e.split("/")[1].toLowerCase()}function Ec(e){const t=[];return e.forEach((e=>{void 0!==e.track&&t.push(new Cs({cid:e.track.mediaStreamID,track:e.trackInfo}))})),t}function _c(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?_c(e.track):{})}}function Pc(e){const t=Object.assign({},e);let i,n;return"object"==typeof t.audio&&t.audio.processor&&(i=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),"object"==typeof t.video&&t.video.processor&&(n=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:i,videoProcessor:n,optionsWithoutProcessor:(s=t,void 0===s?s:"function"==typeof structuredClone?structuredClone(s):JSON.parse(JSON.stringify(s)))};var s}class Rc extends Er.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;const{kind:n,data:s}=e.data;switch(n){case"error":fr.error(s.error.message),this.emit(Lo.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)}));break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach((e=>{this.postKey(e)})),this.encryptionEnabled!==s.enabled&&s.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(Lo.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(Lo.ParticipantEncryptionStatusChanged,s.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(No.KeyRatcheted,s.material,s.keyIndex)}},this.onWorkerError=e=>{fr.error("e2ee worker encountered an error:",{error:e.error}),this.emit(Lo.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||Xo()))throw new ia("tried to setup end-to-end encryption on an unsupported browser");if(fr.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:yr.getLevel()}};this.worker&&(fr.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){fr.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):fr.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(Wo.RTPVideoMapUpdate,(e=>{this.postRTPMap(e)}))}setupEventListeners(e,t){e.on(Ko.TrackPublished,((e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==Dn.NONE,t.identity))),e.on(Ko.ConnectionStateChanged,(t=>{t===Zd.Connected&&e.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==Dn.NONE,e.identity)}))}))})).on(Ko.TrackUnsubscribed,((e,t,i)=>{var n;const s={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(s)})).on(Ko.TrackSubscribed,((e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)})).on(Ko.SignalConnected,(()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach((e=>{this.postKey(e)})),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)})),e.localParticipant.on(Ho.LocalTrackPublished,(e=>Tr(this,void 0,void 0,(function*(){this.setupE2EESender(e.track,e.track.sender)})))),t.on(No.SetKey,(e=>this.postKey(e))).on(No.RatchetRequest,((e,t)=>this.postRatchetRequest(e,t)))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:n}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const r={kind:"setKey",data:{participantIdentity:i,isPublisher:i===(null===(s=this.room)||void 0===s?void 0:s.localParticipant.identity),key:t,keyIndex:n}};this.worker.postMessage(r)}postEnable(e,t){if(!this.worker)throw new ReferenceError("failed to enable e2ee, worker is not ready");{const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?wc(i.mimeType):void 0)}}setupE2EESender(e,t){lc(e)&&t?this.handleSender(t,e.mediaStreamID,void 0):t||fr.warn("early return because sender is not ready")}handleReceiver(e,t,i,n){return Tr(this,void 0,void 0,(function*(){if(this.worker){if(Xo()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Ao in e&&n){const e={kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}};return void this.worker.postMessage(e)}let s=e.writableStream,r=e.readableStream;if(!s||!r){const t=e.createEncodedStreams();e.writableStream=t.writable,s=t.writable,e.readableStream=t.readable,r=t.readable}const o={kind:"decode",data:{readableStream:r,writableStream:s,trackId:t,codec:n,participantIdentity:i}};this.worker.postMessage(o,[r,s])}e[Ao]=!0}}))}handleSender(e,t,i){var n;if(!(Ao in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Xo()){fr.info("initialize script transform");const n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{fr.info("initialize encoded streams");const n=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[n.readable,n.writable])}e[Ao]=!0}}}const xc="default";class Oc{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new Oc),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return Tr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;if((null===(n=Oc.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){fr.debug("awaiting getUserMedia promise");try{e?yield Oc.userMediaPromiseMap.get(e):yield Promise.all(Oc.userMediaPromiseMap.values())}catch(r){fr.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&(!$a()||!t.hasDeviceInUse(e))&&(0===s.filter((t=>t.kind===e)).length||s.some((t=>{const i=""===t.label,n=!e||t.kind===e;return i&&n})))){const t={video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}},i=yield navigator.mediaDevices.getUserMedia(t);s=yield navigator.mediaDevices.enumerateDevices(),i.getTracks().forEach((e=>{e.stop()}))}return t._previousDevices=s,e&&(s=s.filter((t=>t.kind===e))),s}()}))}normalizeDeviceId(e,t,i){return Tr(this,void 0,void 0,(function*(){if(t!==xc)return t;const n=yield this.getDevices(e),s=n.find((e=>e.deviceId===xc));if(!s)return void fr.warn("could not reliably determine default device");const r=n.find((e=>e.deviceId!==xc&&e.groupId===(null!=i?i:s.groupId)));if(r)return null==r?void 0:r.deviceId;fr.warn("could not reliably determine default device")}))}hasDeviceInUse(e){return e?Oc.userMediaPromiseMap.has(e):Oc.userMediaPromiseMap.size>0}}var Ic,Ac;Oc.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Oc.userMediaPromiseMap=new Map,(Ac=Ic||(Ic={}))[Ac.WAITING=0]="WAITING",Ac[Ac.RUNNING=1]="RUNNING",Ac[Ac.COMPLETED=2]="COMPLETED";class Nc{constructor(){this.pendingTasks=new Map,this.taskMutex=new Mt,this.nextTaskIndex=0}run(e){return Tr(this,void 0,void 0,(function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Ic.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Ic.RUNNING,yield e()}finally{t.status=Ic.COMPLETED,this.pendingTasks.delete(t.id),i()}}))}flush(){return Tr(this,void 0,void 0,(function*(){return this.run((()=>Tr(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}}function Dc(e,t){return e.pathname="".concat(function(e){return e.endsWith("/")?e:"".concat(e,"/")}(e.pathname)).concat(t),e.toString()}const Mc=["syncState","trickle","offer","answer","simulate","leave"];var Lc,Uc;(Uc=Lc||(Lc={}))[Uc.CONNECTING=0]="CONNECTING",Uc[Uc.CONNECTED=1]="CONNECTED",Uc[Uc.RECONNECTING=2]="RECONNECTING",Uc[Uc.DISCONNECTING=3]="DISCONNECTING",Uc[Uc.DISCONNECTED=4]="DISCONNECTED";class jc{get currentState(){return this.state}get isDisconnected(){return this.state===Lc.DISCONNECTING||this.state===Lc.DISCONNECTED}get isEstablishingConnection(){return this.state===Lc.CONNECTING||this.state===Lc.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;this.rtt=0,this.state=Lc.DISCONNECTED,this.log=fr,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=vr(null!==(i=t.loggerName)&&void 0!==i?i:hr.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Nc,this.queuedRequests=[],this.closingLock=new Mt,this.connectionLock=new Mt,this.state=Lc.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return Tr(this,void 0,void 0,(function*(){return this.state=Lc.CONNECTING,this.options=i,yield this.connect(e,t,i,n)}))}reconnect(e,t,i,n){return Tr(this,void 0,void 0,(function*(){if(this.options)return this.state=Lc.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}));this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext)}))}connect(e,t,i,n){this.connectOptions=i;const s=function(e,t,i){var n;const s=new URLSearchParams;return s.set("access_token",e),i.reconnect&&(s.set("reconnect","1"),i.sid&&s.set("sid",i.sid)),s.set("auto_subscribe",i.autoSubscribe?"1":"0"),s.set("sdk",qa()?"reactnative":"js"),s.set("version",t.version),s.set("protocol",t.protocol.toString()),t.deviceModel&&s.set("device_model",t.deviceModel),t.os&&s.set("os",t.os),t.osVersion&&s.set("os_version",t.osVersion),t.browser&&s.set("browser",t.browser),t.browserVersion&&s.set("browser_version",t.browserVersion),i.adaptiveStream&&s.set("adaptive_stream","1"),i.reconnectReason&&s.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&s.set("network",navigator.connection.type),s}(t,function(){var e;const t=new es({sdk:ts.JS,protocol:15,version:"2.11.4"});return qa()&&(t.os=null!==(e=Za())&&void 0!==e?e:""),t}(),i),r=function(e,t){const i=new URL(function(e){return e.startsWith("http")?e.replace(/^(http)/,"ws"):e}(e));return t.forEach(((e,t)=>{i.searchParams.set(t,e)})),Dc(i,"rtc")}(e,s),o=Dc(new URL(oc(r)),"validate");return new Promise(((e,t)=>Tr(this,void 0,void 0,(function*(){const s=yield this.connectionLock.lock();try{const s=()=>Tr(this,void 0,void 0,(function*(){this.close(),clearTimeout(a),t(new ta("room connection has been cancelled (signal)",Fo.Cancelled))})),a=setTimeout((()=>{this.close(),t(new ta("room connection has timed out (signal)",Fo.ServerUnreachable))}),i.websocketTimeout);(null==n?void 0:n.aborted)&&s(),null==n||n.addEventListener("abort",s);const c=new URL(r);c.searchParams.has("access_token")&&c.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(c),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(a)},this.ws.onerror=e=>Tr(this,void 0,void 0,(function*(){if(this.state===Lc.CONNECTED)this.handleWSError(e);else{this.state=Lc.DISCONNECTED,clearTimeout(a);try{const i=yield fetch(o);if(i.status.toFixed(0).startsWith("4")){const e=yield i.text();t(new ta(e,Fo.NotAllowed,i.status))}else t(new ta("Encountered unknown websocket error during connection: ".concat(e.toString()),Fo.InternalError,i.status))}catch(i){t(new ta(i instanceof Error?i.message:"server was not reachable",Fo.ServerUnreachable))}}})),this.ws.onmessage=r=>Tr(this,void 0,void 0,(function*(){var o,a,c;let d;if("string"==typeof r.data){const e=JSON.parse(r.data);d=fs.fromJson(e,{ignoreUnknownFields:!0})}else{if(!(r.data instanceof ArrayBuffer))return void this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);d=fs.fromBinary(new Uint8Array(r.data))}if(this.state!==Lc.CONNECTED){let r=!1;if("join"===(null===(o=d.message)||void 0===o?void 0:o.case)?(this.state=Lc.CONNECTED,null==n||n.removeEventListener("abort",s),this.pingTimeoutDuration=d.message.value.pingTimeout,this.pingIntervalDuration=d.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(d.message.value)):this.state===Lc.RECONNECTING&&"leave"!==d.message.case?(this.state=Lc.CONNECTED,null==n||n.removeEventListener("abort",s),this.startPingInterval(),"reconnect"===(null===(a=d.message)||void 0===a?void 0:a.case)?e(d.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===d.message.case?t(new ta("Received leave request while trying to (re)connect",Fo.LeaveRequest,void 0,d.message.value.reason)):i.reconnect||t(new ta("did not receive join response, got ".concat(null===(c=d.message)||void 0===c?void 0:c.case," instead"),Fo.InternalError)),!r)return}this.signalLatency&&(yield Da(this.signalLatency)),this.handleSignalResponse(d)})),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new ta("Websocket got closed during a (re)connection attempt",Fo.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{s()}}))))}close(){return Tr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Lc.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const t=new Promise((t=>{e.ws?e.ws.onclose=()=>{t()}:t()}));e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,Da(250)])),e.ws=void 0}}finally{t&&(e.state=Lc.DISCONNECTED),i()}}()}))}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:$c(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:$c(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new bs({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new ks({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return Tr(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){const s=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new Ds({requestId:s,metadata:e,name:t,attributes:n})}),s}()}))}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Ns({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Zs({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ti.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ys({timestamp:ti.parse(Date.now()),rtt:ti.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new xs({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Is({reason:Cn.CLIENT_INITIATED,action:As.DISCONNECT})})}sendRequest(e){return Tr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){const n=!i&&!function(e){const t=Mc.indexOf(e.case)>=0;return fr.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e);if(n&&t.state===Lc.RECONNECTING)return void t.queuedRequests.push((()=>Tr(t,void 0,void 0,(function*(){yield this.sendRequest(e,!0)}))));if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Da(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN)return void t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);const s=new gs({message:e});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(r){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:r}))}}()}))}handleSignalResponse(e){var t,i;const n=e.message;if(null==n)return void this.log.debug("received unsupported message",this.logContext);let s=!1;if("answer"===n.case){const e=Fc(n.value);this.onAnswer&&this.onAnswer(e)}else if("offer"===n.case){const e=Fc(n.value);this.onOffer&&this.onOffer(e)}else if("trickle"===n.case){const e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return Tr(this,void 0,void 0,(function*(){if(this.state===Lc.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)}))}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){this.clearPingTimeout(),this.pingTimeoutDuration?this.pingTimeout=ga.setTimeout((()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")}),1e3*this.pingTimeoutDuration):this.log.warn("ping timeout duration not set",this.logContext)}clearPingTimeout(){this.pingTimeout&&ga.clearTimeout(this.pingTimeout)}startPingInterval(){this.clearPingInterval(),this.resetPingTimeout(),this.pingIntervalDuration?(this.log.debug("start ping interval",this.logContext),this.pingInterval=ga.setInterval((()=>{this.sendPing()}),1e3*this.pingIntervalDuration)):this.log.warn("ping interval duration not set",this.logContext)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ga.clearInterval(this.pingInterval)}}function Fc(e){const t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function $c(e){return new Es({sdp:e.sdp,type:e.type})}var Bc,Vc,qc,zc,Kc,Zc={},Hc={},Gc={exports:{}};function Wc(){if(Bc)return Gc.exports;Bc=1;var e=Gc.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")+(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":"")+(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"]}]};return Object.keys(e).forEach((function(t){e[t].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))})),Gc.exports}function Jc(){if(zc)return qc;zc=1;var e=Wc(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,s=n.length;return e.replace(t,(function(e){if(i>=s)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}}))},n=function(e,t,n){var s=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var r=0;r<t.names.length;r+=1){var o=t.names[r];t.name?s.push(n[t.name][o]):s.push(n[t.names[r]])}else s.push(n[t.name]);return i.apply(null,s)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return qc=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var o=i.outerOrder||s,a=i.innerOrder||r,c=[];return o.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))})),t.media.forEach((function(t){c.push(n("m",e.m[0],t)),a.forEach((function(i){e[i].forEach((function(e){e.name in t&&null!=t[e.name]?c.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach((function(t){c.push(n(i,e,t))}))}))}))})),c.join("\r\n")+"\r\n"}}var Yc=function(){if(Kc)return Zc;Kc=1;var e=(Vc||(Vc=1,function(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var r=e.push?{}:s?i[e.name]:i;!function(e,i,n,s){if(s&&!n)i[s]=t(e[1]);else for(var r=0;r<n.length;r+=1)null!=e[r+1]&&(i[n[r]]=t(e[r+1]))}(n.match(e.reg),r,e.names,e.name),e.push&&i[e.push].push(r)},n=Wc(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},r=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(r.push({rtp:[],fmtp:[]}),o=r[r.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var c=n[t][a];if(c.reg.test(s))return i(c,o,s)}})),t.media=r,t};var r=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(r,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),s=0;s<n.length;s+=3)i.push({component:n[s],ip:n[s+1],port:n[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(r,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}(Hc)),Hc),t=Jc(),i=Wc();return Zc.grammar=i,Zc.write=t,Zc.parse=e.parse,Zc.parseParams=e.parseParams,Zc.parseFmtpConfig=e.parseFmtpConfig,Zc.parsePayloads=e.parsePayloads,Zc.parseRemoteCandidates=e.parseRemoteCandidates,Zc.parseImageAttributes=e.parseImageAttributes,Zc.parseSimulcastStreamList=e.parseSimulcastStreamList,Zc}();function Qc(e,t,i){var n,s,r;void 0===t&&(t=50),void 0===i&&(i={});var o=null!=(n=i.isImmediate)&&n,a=null!=(s=i.callback)&&s,c=i.maxWait,d=Date.now(),l=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise((function(s,u){var h=o&&void 0===r;if(void 0!==r&&clearTimeout(r),r=setTimeout((function(){if(r=void 0,d=Date.now(),!o){var t=e.apply(n,i);a&&a(t),l.forEach((function(e){return(0,e.resolve)(t)})),l=[]}}),function(){if(void 0!==c){var e=Date.now()-d;if(e+t>=c)return c-e}return t}()),h){var p=e.apply(n,i);return a&&a(p),s(p)}l.push({resolve:s,reject:u})}))};return u.cancel=function(e){void 0!==r&&clearTimeout(r),l.forEach((function(t){return(0,t.reject)(e)})),l=[]},u}const Xc="negotiationStarted",ed="negotiationComplete",td="rtpVideoPayloadTypes";class id extends Er.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i;super(),this.log=fr,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Qc((e=>Tr(this,void 0,void 0,(function*(){this.emit(Xc);try{yield this.createAndSendOffer()}catch(t){if(!e)throw t;e(t)}}))),20),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=vr(null!==(i=t.loggerName)&&void 0!==i?i:hr.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return Tr(this,void 0,void 0,(function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)}))}setRemoteDescription(e){return Tr(this,void 0,void 0,(function*(){var t;let i;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;const i=[],n=[],s=Yc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");let r=0;return s.media.forEach((e=>{var t;"audio"===e.type&&(e.rtp.some((e=>"opus"===e.codec&&(r=e.payload,!0))),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some((e=>e.payload===r&&"nack"===e.type)))&&n.push(e.mid),e.fmtp.some((t=>t.payload===r&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0))))})),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){const n=Yc.parse(null!==(t=e.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{"audio"===e.type&&this.trackBitrates.some((t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;let n=!1;for(const s of e.fmtp)if(s.payload===i){s.config=s.config.split(";").filter((e=>!e.includes("maxaveragebitrate"))).join(";"),t.maxbr>0&&(s.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return n||t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0}))})),i=Yc.write(n)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach((e=>{this.pc.addIceCandidate(e)})),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(ed),e.sdp)&&Yc.parse(e.sdp).media.forEach((e=>{"video"===e.type&&this.emit(td,e.rtp)}))}))}createAndSendOffer(e){return Tr(this,void 0,void 0,(function*(){var t;if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){const t=this._pc.remoteDescription;if(!(null==e?void 0:e.iceRestart)||!t)return void(this.renegotiate=!0);yield this._pc.setRemoteDescription(t)}else if(!this._pc||"closed"===this._pc.signalingState)return void this.log.warn("could not createOffer with closed peer connection",this.logContext);this.log.debug("starting to negotiate",this.logContext);const i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const n=Yc.parse(null!==(t=i.sdp)&&void 0!==t?t:"");n.media.forEach((e=>{sd(e),"audio"===e.type?nd(e,[],[]):"video"===e.type&&this.trackBitrates.some((t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some((e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0))),0===i)return!0;if(Ua(t.codec)&&this.ensureVideoDDExtensionForSVC(e,n),"av1"!==t.codec)return!0;const s=Math.round(.7*t.maxbr);for(const n of e.fmtp)if(n.payload===i){n.config.includes("x-google-start-bitrate")||(n.config+=";x-google-start-bitrate=".concat(s));break}return!0}))})),yield this.setMungedSDP(i,Yc.write(n)),this.onOffer(i)}))}createAndSetAnswer(){return Tr(this,void 0,void 0,(function*(){var e;const t=yield this.pc.createAnswer(),i=Yc.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach((e=>{sd(e),"audio"===e.type&&nd(e,this.remoteStereoMids,this.remoteNackMids)})),yield this.setMungedSDP(t,Yc.write(i)),t}))}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new ra("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new ra("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return Tr(this,void 0,void 0,(function*(){var e;if(!this._pc)return;let t="";const i=new Map,n=new Map;if((yield this._pc.getStats()).forEach((e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}})),""===t)return;const s=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;return void 0!==s?n.get(s):void 0}))}setMungedSDP(e,t,i){return Tr(this,void 0,void 0,(function*(){if(t){const s=e.sdp;e.sdp=t;try{return this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),void(i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e))}catch(n){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:n,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(n){let t="unknown error";n instanceof Error?t=n.message:"string"==typeof n&&(t=n);const s={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new oa(t)}}))}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some((e=>e.uri===Na)))){if(0===this.ddExtID){let e=0;t.media.forEach((t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach((t=>{t.value>e&&(e=t.value)})))})),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:Na})}}}function nd(e,t,i){let n=0;e.rtp.some((e=>"opus"===e.codec&&(n=e.payload,!0))),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some((e=>e.payload===n&&"nack"===e.type))&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some((e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0))))}function sd(e){if(e.connection){const t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}const rd="vp8",od={audioPreset:Ra.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Aa.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:rd,backupCodec:!0},ad={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},cd={deviceId:{ideal:"default"},resolution:Oa.h720.resolution},dd={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new class{constructor(e){this._retryDelays=void 0!==e?[...e]:kr}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}},disconnectOnPageLeave:!0,webAudioMix:!1},ld={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ud,hd;(hd=ud||(ud={}))[hd.NEW=0]="NEW",hd[hd.CONNECTING=1]="CONNECTING",hd[hd.CONNECTED=2]="CONNECTED",hd[hd.FAILED=3]="FAILED",hd[hd.CLOSING=4]="CLOSING",hd[hd.CLOSED=5]="CLOSED";class pd{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=ld.peerConnectionTimeout,this.log=fr,this.updateState=()=>{var e;const t=this.state,i=this.requiredTransports.map((e=>e.getConnectionState()));i.every((e=>"connected"===e))?this.state=ud.CONNECTED:i.some((e=>"failed"===e))?this.state=ud.FAILED:i.some((e=>"connecting"===e))?this.state=ud.CONNECTING:i.every((e=>"closed"===e))?this.state=ud.CLOSED:i.some((e=>"closed"===e))?this.state=ud.CLOSING:i.every((e=>"new"===e))&&(this.state=ud.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(ud[t]," to ").concat(ud[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=vr(null!==(n=i.loggerName)&&void 0!==n?n:hr.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new id(e,i),this.subscriber=new id(e,i),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,hs.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,hs.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=e=>{var t;null===(t=this.onPublisherOffer)||void 0===t||t.call(this,e)},this.state=ud.NEW,this.connectionLock=new Mt,this.remoteOfferLock=new Mt}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return Tr(this,void 0,void 0,(function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()}))}triggerIceRestart(){return Tr(this,void 0,void 0,(function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))}))}addIceCandidate(e,t){return Tr(this,void 0,void 0,(function*(){t===hs.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)}))}createSubscriberAnswerFromOffer(e){return Tr(this,void 0,void 0,(function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}}))}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return Tr(this,void 0,void 0,(function*(){var i;const n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map((i=>this.ensureTransportConnected(i,e,t))))}finally{n()}}))}negotiate(e){return Tr(this,void 0,void 0,(function*(){return new Promise(((t,i)=>Tr(this,void 0,void 0,(function*(){const n=setTimeout((()=>{i("negotiation timed out")}),this.peerConnectionTimeout);e.signal.addEventListener("abort",(()=>{clearTimeout(n),i("negotiation aborted")})),this.publisher.once(Xc,(()=>{e.signal.aborted||this.publisher.once(ed,(()=>{clearTimeout(n),t()}))})),yield this.publisher.negotiate((e=>{clearTimeout(n),i(e)}))}))))}))}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===hs.PUBLISHER||e===hs.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return Tr(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise(((e,s)=>Tr(i,void 0,void 0,(function*(){const i=()=>{this.log.warn("abort transport connection",this.logContext),ga.clearTimeout(r),s(new ta("room connection has been cancelled",Fo.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);const r=ga.setTimeout((()=>{null==t||t.signal.removeEventListener("abort",i),s(new ta("could not establish pc connection",Fo.InternalError))}),n);for(;this.state!==ud.CONNECTED;)if(yield Da(50),null==t?void 0:t.signal.aborted)return void s(new ta("room connection has been cancelled",Fo.Cancelled));ga.clearTimeout(r),null==t||t.signal.removeEventListener("abort",i),e()}))))}()}))}}class md extends Error{constructor(e,t,i){super(t),this.code=e,this.message=fd(t,md.MAX_MESSAGE_BYTES),this.data=i?fd(i,md.MAX_DATA_BYTES):void 0}static fromProto(e){return new md(e.code,e.message,e.data)}toProto(){return new Jn({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new md(md.ErrorCode[e],md.ErrorMessage[e],t)}}function gd(e){return(new TextEncoder).encode(e).length}function fd(e,t){if(gd(e)<=t)return e;let i=0,n=e.length;const s=new TextEncoder;for(;i<n;){const r=Math.floor((i+n+1)/2);s.encode(e.slice(0,r)).length<=t?i=r:n=r-1}return e.slice(0,i)}md.MAX_MESSAGE_BYTES=256,md.MAX_DATA_BYTES=15360,md.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},md.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const vd=2e3;function yd(e,t){if(!t)return 0;let i,n;return"bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp?0:8*(i-n)*1e3/(e.timestamp-t.timestamp)}class bd extends ba{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3];super(e,t,arguments.length>4?arguments[4]:void 0),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch((()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext))),this.debouncedTrackMuteHandler=Qc((()=>Tr(this,void 0,void 0,(function*(){yield this.pauseUpstream()}))),5e3),this.handleTrackUnmuteEvent=()=>Tr(this,void 0,void 0,(function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()})),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(Yo.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new Mt,this.pauseUpstreamLock=new Mt,this.processorLock=new Mt,this.restartLock=new Mt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==ba.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();return e&&t?{width:e,height:t}:void 0}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return Tr(this,void 0,void 0,(function*(){var i;if(e===this._mediaStreamTrack&&!t)return;let n;if(this._mediaStreamTrack&&(this.attachedElements.forEach((e=>{Ta(this._mediaStreamTrack,e)})),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints()),this.processor&&e){const t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ka(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&"closed"!==(null===(i=this.sender.transport)||void 0===i?void 0:i.state)&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach((t=>{ka(null!=n?n:e,t)})))}))}waitForDimensions(){return Tr(this,arguments,void 0,(function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===ba.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");"iOS"===(null===(i=ua())||void 0===i?void 0:i.os)&&(yield Da(10));const n=Date.now();for(;Date.now()-n<t;){const t=e.dimensions;if(t)return t;yield Da(50)}throw new na("unable to get track dimensions after timeout")}()}))}setDeviceId(e){return Tr(this,void 0,void 0,(function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===rc(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),rc(e)===this._mediaStreamTrack.getSettings().deviceId))}))}getDeviceId(){return Tr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){if(e.source===ba.Source.ScreenShare)return;const{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),s=e.kind===ba.Kind.Audio?"audioinput":"videoinput";return t?Oc.getInstance().normalizeDeviceId(s,i,n):i}()}))}mute(){return Tr(this,void 0,void 0,(function*(){return this.setTrackMuted(!0),this}))}unmute(){return Tr(this,void 0,void 0,(function*(){return this.setTrackMuted(!1),this}))}replaceTrack(e,t){return Tr(this,void 0,void 0,(function*(){if(!this.sender)throw new na("unable to replace an unpublished track");let i,n;return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this}))}restart(e){return Tr(this,void 0,void 0,(function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===ba.Kind.Video?s.video=!t&&!i||{deviceId:t,facingMode:i}:s.audio=!t||{deviceId:t},this.attachedElements.forEach((e=>{Ta(this.mediaStreamTrack,e)})),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const r=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield r.applyConstraints(n),r.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(r),this._constraints=e,this.emit(Yo.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}}))}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),this.isMuted===e&&this._mediaStreamTrack.enabled!==e||(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Yo.Muted:Yo.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Tr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ba()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),this.isInBackground||!this.needsReAcquisition||this.isUserProvided||this.isMuted||(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))}))}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return Tr(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to pause upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!0,this.emit(Yo.UpstreamPaused,this);const t=ua();if("Safari"===(null==t?void 0:t.name)&&Ga(t.version,"12.0")<0)throw new ia("pauseUpstream is not supported on Safari < 12.");"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(null))}finally{t()}}))}resumeUpstream(){return Tr(this,void 0,void 0,(function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender)return void this.log.warn("unable to resume upstream for an unpublished track",this.logContext);this._isUpstreamPaused=!1,this.emit(Yo.UpstreamResumed,this),"closed"!==(null===(e=this.sender.transport)||void 0===e?void 0:e.state)&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}}))}getRTCStatsReport(){return Tr(this,void 0,void 0,(function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()}))}setProcessor(e){return Tr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var n;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const s=document.createElement(t.kind),r={kind:t.kind,track:t._mediaStreamTrack,element:s,audioContext:t.audioContext};if(yield e.init(r),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(ka(t._mediaStreamTrack,s),s.muted=!0,s.play().catch((e=>t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e})))),t.processor=e,t.processorElement=s,t.processor.processedTrack){for(const e of t.attachedElements)e!==t.processorElement&&i&&(Ta(t._mediaStreamTrack,e),ka(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(Yo.TrackProcessorUpdate,t.processor)}finally{s()}}()}))}getProcessor(){return this.processor}stopProcessor(){return Tr(this,arguments,void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Yo.TrackProcessorUpdate))}()}))}}class kd extends bd{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,ba.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>Tr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(t){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:t}))}e&&this.prevStats&&(this._currentBitrate=yd(e,this.prevStats)),this.prevStats=e})),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(Yo.AudioTrackFeatureUpdate,this,_n.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(Yo.AudioTrackFeatureUpdate,this,_n.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Tr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===ba.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Tr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==rc(this._constraints.deviceId);return this.source!==ba.Source.Microphone||!this.stopOnMute&&"ended"!==this._mediaStreamTrack.readyState&&!t||this.isUserProvided||(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}}))}restartTrack(e){return Tr(this,void 0,void 0,(function*(){let t;if(e){const i=kc({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)}))}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return Tr(this,void 0,void 0,(function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i}))}startMonitor(){Va()&&(this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),vd)))}setProcessor(e){return Tr(this,void 0,void 0,(function*(){var t;const i=yield this.processorLock.lock();try{if(!qa()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield null===(t=this.sender)||void 0===t?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(Yo.TrackProcessorUpdate,this.processor)}finally{i()}}))}setAudioContext(e){this.audioContext=e}getSenderStats(){return Tr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return;let t;return(yield this.sender.getStats()).forEach((e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})})),t}))}checkForSilence(){return Tr(this,void 0,void 0,(function*(){const e=yield function(e){return Tr(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){const i=Tc();if(i){const n=i.createAnalyser();n.fftSize=2048;const s=n.frequencyBinCount,r=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield Da(t),n.getByteTimeDomainData(r);const o=r.some((e=>128!==e&&0!==e));return i.close(),!o}return!1}()}))}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(Yo.AudioSilenceDetected)),e}))}}const Td=Object.values(Oa),Sd=Object.values(Ia),Cd=Object.values(Aa),wd=[Oa.h180,Oa.h360],Ed=[Ia.h180,Ia.h360],_d=["q","h","f"];function Pd(e,t,i,n){var s,r;let o=null==n?void 0:n.videoEncoding;e&&(o=null==n?void 0:n.screenShareEncoding);const a=null==n?void 0:n.simulcast,c=null==n?void 0:n.scalabilityMode,d=null==n?void 0:n.videoCodec;if(!o&&!a&&!c||!t||!i)return[{}];o||(o=function(e,t,i,n){const s=function(e,t,i){if(e)return Cd;const n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?Td:Sd}(e,t,i);let{encoding:r}=s[0];const o=Math.max(t,i);for(let a=0;a<s.length;a+=1){const e=s[a];if(r=e.encoding,e.width>=o)break}if(n)switch(n){case"av1":r=Object.assign({},r),r.maxBitrate=.7*r.maxBitrate;break;case"vp9":r=Object.assign({},r),r.maxBitrate=.85*r.maxBitrate}return r}(e,t,i,d),fr.debug("using video encoding",o));const l=o.maxFramerate,u=new Sa(t,i,o.maxBitrate,o.maxFramerate,o.priority);if(c&&Ua(d)){const e=new Id(c),t=[];if(e.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const i=ua();if($a()||qa()||"Chrome"===(null==i?void 0:i.name)&&Ga(null==i?void 0:i.version,"113")<0){const i="h"==e.suffix?2:3;for(let n=0;n<e.spatial;n+=1)t.push({rid:_d[2-n],maxBitrate:o.maxBitrate/Math.pow(i,n),maxFramerate:u.encoding.maxFramerate});t[0].scalabilityMode=c}else t.push({maxBitrate:o.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),fr.debug("using svc encoding",{encodings:t}),t}if(!a)return[o];let h,p=[];if(p=e?null!==(s=Od(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==s?s:Rd(e,u):null!==(r=Od(null==n?void 0:n.videoSimulcastLayers))&&void 0!==r?r:Rd(e,u),p.length>0){const e=p[0];p.length>1&&([,h]=p);const n=Math.max(t,i);if(n>=960&&h)return xd(t,i,[e,h,u],l);if(n>=480)return xd(t,i,[e,u],l)}return xd(t,i,[u])}function Rd(e,t){if(e)return[{scaleResolutionDownBy:2,fps:(i=t).encoding.maxFramerate}].map((e=>{var t,n;return new Sa(Math.floor(i.width/e.scaleResolutionDownBy),Math.floor(i.height/e.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(e.scaleResolutionDownBy,2)*((null!==(t=i.encoding.maxFramerate)&&void 0!==t?t:30)/(null!==(n=e.fps)&&void 0!==n?n:30))))),e.fps,i.encoding.priority)}));var i;const{width:n,height:s}=t,r=n>s?n/s:s/n;return Math.abs(r-16/9)<Math.abs(r-4/3)?wd:Ed}function xd(e,t,i,n){const s=[];if(i.forEach(((i,r)=>{if(r>=_d.length)return;const o=Math.min(e,t),a={rid:_d[r],scaleResolutionDownBy:Math.max(1,o/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},c=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;c&&(a.maxFramerate=c);const d=Fa()||0===r;i.encoding.priority&&d&&(a.priority=i.encoding.priority,a.networkPriority=i.encoding.priority),s.push(a)})),qa()&&"ios"===Za()){let e;s.forEach((t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate}));let t=!0;s.forEach((i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,fr.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),fr.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)}))}return s}function Od(e){if(e)return e.sort(((e,t)=>{const{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0}))}class Id{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat(null!==(e=this.suffix)&&void 0!==e?e:"")}}class Ad extends bd{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,ba.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>Tr(this,void 0,void 0,(function*(){if(!this.sender)return void(this._currentBitrate=0);let e;try{e=yield this.getSenderStats()}catch(i){return void this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:i}))}const t=new Map(e.map((e=>[e.rid,e])));if(this.prevStats){let e=0;t.forEach(((t,i)=>{var n;const s=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=yd(t,s)})),this._currentBitrate=e}this.prevStats=t})),this.senderLock=new Mt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Va())return;const i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval((()=>{this.monitorSender()}),vd))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach((e=>{e.mediaStreamTrack.stop()})),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return Tr(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.pauseUpstream.call(this);try{for(var o,a=!0,c=Sr(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(null)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return Tr(this,void 0,void 0,(function*(){var t,i,n,s,r;yield e.resumeUpstream.call(this);try{for(var o,a=!0,c=Sr(this.simulcastCodecs.values());!(t=(o=yield c.next()).done);a=!0){s=o.value,a=!1;const e=s;yield null===(r=e.sender)||void 0===r?void 0:r.replaceTrack(e.mediaStreamTrack)}}catch(d){i={error:d}}finally{try{a||t||!(n=c.return)||(yield n.call(c))}finally{if(i)throw i.error}}}))}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return Tr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source!==ba.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}}))}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return Tr(this,void 0,void 0,(function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source!==ba.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}}))}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return Tr(this,void 0,void 0,(function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach((e=>{var n;if("outbound-rtp"===e.type){const s={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},r=i.get(e.remoteId);r&&(s.jitter=r.jitter,s.packetsLost=r.packetsLost,s.roundTripTime=r.roundTripTime),t.push(s)}})),t.sort(((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)})),t}))}setPublishingQuality(e){const t=[];for(let i=va.LOW;i<=va.HIGH;i+=1)t.push(new Vs({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return Tr(this,void 0,void 0,(function*(){var t,i,n,s,r;let o;if(e){const t=kc({video:e});"boolean"!=typeof t.video&&(o=t.video)}yield this.restart(o);try{for(var a,c=!0,d=Sr(this.simulcastCodecs.values());!(t=(a=yield d.next()).done);c=!0){s=a.value,c=!1;const e=s;e.sender&&"closed"!==(null===(r=e.sender.transport)||void 0===r?void 0:r.state)&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(l){i={error:l}}finally{try{c||t||!(n=d.return)||(yield n.call(d))}finally{if(i)throw i.error}}}))}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return Tr(this,arguments,void 0,(function(e){var i=this;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){var s,r,o,a,c,d;if(yield t.setProcessor.call(i,e,n),null===(c=i.processor)||void 0===c?void 0:c.processedTrack)try{for(var l,u=!0,h=Sr(i.simulcastCodecs.values());!(s=(l=yield h.next()).done);u=!0){a=l.value,u=!1;const e=a;yield null===(d=e.sender)||void 0===d?void 0:d.replaceTrack(i.processor.processedTrack)}}catch(p){r={error:p}}finally{try{u||s||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}}()}))}setDegradationPreference(e){return Tr(this,void 0,void 0,(function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}}))}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e))return void this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout((()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)}),5e3))}setPublishingCodecs(e){return Tr(this,void 0,void 0,(function*(){var t,i,n,s,r,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,i=Sr(e);!(s=(n=yield i.next()).done);t=!0){a=n.value,t=!1;const e=a;if(this.codec&&this.codec!==e.codec){const t=this.simulcastCodecs.get(e.codec);if(this.log.debug("try setPublishingCodec for ".concat(e.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),t&&t.sender)t.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(e.codec),this.logContext),yield Nd(t.sender,t.encodings,e.qualities,this.senderLock,this.log,this.logContext));else for(const i of e.qualities)if(i.enabled){c.push(e.codec);break}}else yield this.setPublishingLayers(e.qualities)}}catch(d){r={error:d}}finally{try{t||s||!(o=i.return)||(yield o.call(i))}finally{if(r)throw r.error}}return c}))}setPublishingLayers(e){return Tr(this,void 0,void 0,(function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),this.sender&&this.encodings&&(yield Nd(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))}))}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Tr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),Ba()&&this.isInBackground&&this.source===ba.Source.Camera&&(this._mediaStreamTrack.enabled=!1)}))}}function Nd(e,t,i,n,s,r){return Tr(this,void 0,void 0,(function*(){const o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:e,qualities:i,senderEncodings:t}));try{const n=e.getParameters(),{encodings:o}=n;if(!o)return;if(o.length!==t.length)return void s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:o,senderEncodings:t}));let a=!1;const c=ua();if("Chrome"===(null==c?void 0:c.name)&&Ga(null==c?void 0:c.version,"133")>0&&o[0].scalabilityMode){const e=o[0],n=new Id(e.scalabilityMode);let s=kn.OFF;if(i.forEach((e=>{e.enabled&&(s===kn.OFF||e.quality>s)&&(s=e.quality)})),s===kn.OFF)e.active&&(e.active=!1,a=!0);else if(!e.active||n.spatial!==s+1){a=!0,e.active=!0;const i=new Id(t[0].scalabilityMode);n.spatial=s+1,n.suffix=i.suffix,1===n.spatial&&(n.suffix=void 0),e.scalabilityMode=n.toString(),e.scaleResolutionDownBy=Math.pow(2,2-s),t[0].maxBitrate&&(e.maxBitrate=t[0].maxBitrate/(e.scaleResolutionDownBy*e.scaleResolutionDownBy))}}else o.forEach(((e,n)=>{var o;let c=null!==(o=e.rid)&&void 0!==o?o:"";""===c&&(c="q");const d=Dd(c),l=i.find((e=>e.quality===d));l&&e.active!==l.enabled&&(a=!0,e.active=l.enabled,s.debug("setting layer ".concat(l.quality," to ").concat(e.active?"enabled":"disabled"),r),Fa()&&(l.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}));a&&(n.encodings=o,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:n.encodings})),yield e.setParameters(n))}finally{o()}}))}function Dd(e){switch(e){case"f":default:return va.HIGH;case"h":return va.MEDIUM;case"q":return va.LOW}}function Md(e,t,i,n){if(!i)return[new Un({quality:va.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){const n=i[0].scalabilityMode,s=new Id(n),r=[],o="h"==s.suffix?1.5:2,a="h"==s.suffix?2:3;for(let c=0;c<s.spatial;c+=1)r.push(new Un({quality:Math.min(va.HIGH,s.spatial-1)-c,width:Math.ceil(e/Math.pow(o,c)),height:Math.ceil(t/Math.pow(o,c)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return r}return i.map((i=>{var n,s,r;const o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;let a=Dd(null!==(s=i.rid)&&void 0!==s?s:"");return new Un({quality:a,width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(r=i.maxBitrate)&&void 0!==r?r:0,ssrc:0})}))}const Ld="_lossy",Ud="_reliable",jd="leave-reconnect";var Fd,$d,Bd,Vd,qd,zd,Kd,Zd,Hd,Gd,Wd;($d=Fd||(Fd={}))[$d.New=0]="New",$d[$d.Connected=1]="Connected",$d[$d.Disconnected=2]="Disconnected",$d[$d.Reconnecting=3]="Reconnecting",$d[$d.Closed=4]="Closed";class Jd extends Er.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=ld.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Fd.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=fr,this.handleDataChannel=e=>Tr(this,[e],void 0,(function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===Ud)t.reliableDCSub=i;else{if(i.label!==Ld)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()})),this.handleDataMessage=e=>Tr(this,void 0,void 0,(function*(){var t,i;const n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else{if(!(e.data instanceof Blob))return void this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));n=yield e.data.arrayBuffer()}const s=jn.fromBinary(new Uint8Array(n));"speaker"===(null===(t=s.value)||void 0===t?void 0:t.case)?this.emit(Wo.ActiveSpeakersUpdate,s.value.value.speakers):("user"===(null===(i=s.value)||void 0===i?void 0:i.case)&&function(e,t){const i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;const n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(s,s.value.value),this.emit(Wo.DataPacketReceived,s))}finally{n()}})),this.handleDataError=e=>{const t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){const{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{const t=0===e.currentTarget.maxRetransmits?Fn.LOSSY:Fn.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());const i=Date.now()-this.reconnectStart;let n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});null!==n?(e===jd&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=ga.setTimeout((()=>this.attemptReconnect(t).finally((()=>this.reconnectTimeout=void 0))),n)):(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(Wo.Disconnected),this.close()})(i)},this.waitForRestarted=()=>new Promise(((e,t)=>{this.pcState===Fd.Connected&&e();const i=()=>{this.off(Wo.Disconnected,n),e()},n=()=>{this.off(Wo.Restarted,i),t()};this.once(Wo.Restarted,i),this.once(Wo.Disconnected,n)})),this.updateAndEmitDCBufferStatus=e=>{const t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(Wo.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{const t=this.dataChannelForKind(e);if(t)return t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Lc.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(wn.RR_SIGNAL_DISCONNECTED))},this.log=vr(null!==(t=e.loggerName)&&void 0!==t?t:hr.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Mt,this.dataProcessLock=new Mt,this.dcBufferStatus=new Map([[Fn.LOSSY,!0],[Fn.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(Wo.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(Wo.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(Wo.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Wo.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Wo.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Wo.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Wo.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Wo.SignalRequestResponse,e)}get logContext(){var e,t,i,n,s,r,o,a;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(r=null===(s=this.latestJoinResponse)||void 0===s?void 0:s.participant)||void 0===r?void 0:r.identity,pID:null===(a=null===(o=this.latestJoinResponse)||void 0===o?void 0:o.participant)||void 0===a?void 0:a.sid}}join(e,t,i,n){return Tr(this,void 0,void 0,(function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),this.subscriberPrimary&&!s.fastPublish||this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout((()=>{this.emit(Wo.SignalConnected)}),10),s}catch(s){if(s instanceof ta&&s.reason===Fo.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,i,n);throw s}}))}close(){return Tr(this,void 0,void 0,(function*(){const e=yield this.closingLock.lock();if(this.isClosed)e();else try{this._isClosed=!0,this.joinAttempts=0,this.emit(Wo.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}}))}cleanupPeerConnections(){return Tr(this,void 0,void 0,(function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;const t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0}))}cleanupClient(){return Tr(this,void 0,void 0,(function*(){yield this.client.close(),this.client.resetCallbacks()}))}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new na("a track with the same ID has already been published");return new Promise(((t,i)=>{const n=setTimeout((()=>{delete this.pendingTrackResolvers[e.cid],i(new ta("publication of local track timed out, no response from server",Fo.InternalError))}),1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)}))}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return Tr(this,void 0,void 0,(function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()}))}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return Tr(this,void 0,void 0,(function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==ud.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;const n=this.makeRTCConfiguration(e);var s;this.pcManager=new pd(n,e.subscriberPrimary,this.loggerOptions),this.emit(Wo.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=e=>{this.client.sendOffer(e)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>Tr(this,void 0,void 0,(function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===ud.CONNECTED){const t=this.pcState===Fd.New;this.pcState=Fd.Connected,t&&this.emit(Wo.Connected,e)}else t===ud.FAILED&&this.pcState===Fd.Connected&&(this.pcState=Fd.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?wn.RR_SUBSCRIBER_FAILED:wn.RR_PUBLISHER_FAILED));const s=this.client.isDisconnected||this.client.currentState===Lc.RECONNECTING,r=[ud.FAILED,ud.CLOSING,ud.CLOSED].includes(t);s&&r&&!this._isClosed&&this.emit(Wo.Offline)})),this.pcManager.onTrack=e=>{this.emit(Wo.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(s=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&s>13||this.createDataChannels()}))}setupSignalClientCallbacks(){this.client.onAnswer=e=>Tr(this,void 0,void 0,(function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))})),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>Tr(this,void 0,void 0,(function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)})),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?void 0:t.sid})),!this.pendingTrackResolvers[e.cid])return void this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Wo.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Wo.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Wo.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Wo.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",wn.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case As.DISCONNECT:this.emit(Wo.Disconnected,null==e?void 0:e.reason),this.close();break;case As.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(jd);break;case As.RESUME:this.handleDisconnect(jd)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const t=[];e.iceServers.forEach((e=>{const i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)})),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Sn.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ld,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Ud,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,i){return Tr(this,void 0,void 0,(function*(){if(Ma())return yield this.createTransceiverRTCRtpSender(e,t,i);if(La())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ra("Required webRTC APIs not supported on this device")}))}createSimulcastSender(e,t,i,n){return Tr(this,void 0,void 0,(function*(){if(Ma())return this.createSimulcastTransceiverSender(e,t,i,n);if(La())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ra("Cannot stream on this device")}))}createTransceiverRTCRtpSender(e,t,i){return Tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ra("publisher is closed");const n=[];e.mediaStream&&n.push(e.mediaStream),hc(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:n};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender}))}createSimulcastTransceiverSender(e,t,i,n){return Tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ra("publisher is closed");const s={direction:"sendonly"};n&&(s.sendEncodings=n);const r=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,r.sender),r.sender}))}createRTCRtpSender(e){return Tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ra("publisher is closed");return this.pcManager.addPublisherTrack(e)}))}attemptReconnect(e){return Tr(this,void 0,void 0,(function*(){var t,i,n;if(!this._isClosed)if(this.attemptingReconnect)fr.warn("already attempting reconnect, returning early",this.logContext);else{(null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)!==Sn.DISABLED&&(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:ud.NEW)!==ud.NEW||(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let e=!0;s instanceof ra?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),e=!1):s instanceof Yd||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",wn.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(Wo.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}}))}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return Tr(this,void 0,void 0,(function*(){var t,i,n;try{if(!this.url||!this.token)throw new ra("could not reconnect, url or token not saved");let i;this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(Wo.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Yd;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(s){if(s instanceof ta&&s.reason===Fo.NotAllowed)throw new ra("could not reconnect, token might be expired");throw new Yd}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(Wo.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==Lc.CONNECTED)throw new Yd("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(Wo.Restarted)}catch(r){const e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e)return void(yield this.restartConnection(e));throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),r}}))}resumeConnection(e){return Tr(this,void 0,void 0,(function*(){var t;if(!this.url||!this.token)throw new ra("could not reconnect, url or token not saved");if(!this.pcManager)throw new ra("publisher and subscriber connections unset");let i;this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(Wo.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(n){let e="";if(n instanceof Error&&(e=n.message,this.log.error(n.message,Object.assign(Object.assign({},this.logContext),{error:n}))),n instanceof ta&&n.reason===Fo.NotAllowed)throw new ra("could not reconnect, token might be expired");if(n instanceof ta&&n.reason===Fo.LeaveRequest)throw n;throw new Yd(e)}if(this.emit(Wo.SignalResumed),i){const e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Lc.CONNECTED)throw new Yd("Signal connection got severed during reconnect");this.client.setReconnected(),"open"===(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)&&null===this.reliableDC.id&&this.createDataChannels(),this.emit(Wo.Resumed)}))}waitForPCInitialConnection(e,t){return Tr(this,void 0,void 0,(function*(){if(!this.pcManager)throw new ra("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)}))}waitForPCReconnected(){return Tr(this,void 0,void 0,(function*(){this.pcState=Fd.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Da(2e3),!this.pcManager)throw new ra("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Fd.Connected}catch(e){throw this.pcState=Fd.Disconnected,new ta("could not establish PC connection, ".concat(e.message),Fo.InternalError)}}))}publishRpcResponse(e,t,i,n){return Tr(this,void 0,void 0,(function*(){const s=new jn({destinationIdentities:[e],kind:Fn.RELIABLE,value:{case:"rpcResponse",value:new Wn({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(s,Fn.RELIABLE)}))}publishRpcAck(e,t){return Tr(this,void 0,void 0,(function*(){const i=new jn({destinationIdentities:[e],kind:Fn.RELIABLE,value:{case:"rpcAck",value:new Gn({requestId:t})}});yield this.sendDataPacket(i,Fn.RELIABLE)}))}sendDataPacket(e,t){return Tr(this,void 0,void 0,(function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const n=this.dataChannelForKind(t);n&&n.send(i),this.updateAndEmitDCBufferStatus(t)}))}waitForBufferStatusLow(e){return new Promise(((t,i)=>Tr(this,void 0,void 0,(function*(){if(this.isBufferStatusLow(e))t();else{const n=()=>i("Engine closed");for(this.once(Wo.Closing,n);!this.dcBufferStatus.get(e);)yield Da(10);this.off(Wo.Closing,n),t()}}))))}ensureDataTransportConnected(e){return Tr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new ra("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,r=i?"Subscriber":"Publisher";if(!s)throw new ta("".concat(r," connection not set"),Fo.InternalError);let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate();const a=t.dataChannelForKind(e,i);if("open"===(null==a?void 0:a.readyState))return;const c=(new Date).getTime()+t.peerConnectionTimeout;for(;(new Date).getTime()<c;){if(s.isICEConnected&&"open"===(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState))return;yield Da(50)}throw new ta("could not establish ".concat(r," connection, state: ").concat(s.getICEConnectionState()),Fo.InternalError)}()}))}ensurePublisherConnected(e){return Tr(this,void 0,void 0,(function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise}))}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===ud.CONNECTED&&!(!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return Tr(this,void 0,void 0,(function*(){return new Promise(((e,t)=>Tr(this,void 0,void 0,(function*(){if(!this.pcManager)return void t(new oa("PC manager is closed"));this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();const i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(Wo.Closing,n),this.pcManager.publisher.once(td,(e=>{const t=new Map;e.forEach((e=>{const i=e.codec.toLowerCase();var n;n=i,wa.includes(n)&&t.set(e.payload,i)})),this.emit(Wo.RTPVideoMapUpdate,t)}));try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof oa&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",wn.RR_UNKNOWN),t(s)}finally{this.off(Wo.Closing,n)}}))))}))}dataChannelForKind(e,t){if(t){if(e===Fn.LOSSY)return this.lossyDCSub;if(e===Fn.RELIABLE)return this.reliableDCSub}else{if(e===Fn.LOSSY)return this.lossyDC;if(e===Fn.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager)return void this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);const s=this.pcManager.subscriber.getLocalDescription(),r=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=new Array,c=new Array;e.forEach((e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||c.push(e.trackSid)})),this.client.sendSyncState(new Gs({answer:s?$c({sdp:s.sdp,type:s.type}):void 0,offer:r?$c({sdp:r.sdp,type:r.type}):void 0,subscription:new Ps({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:Ec(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(t,i)=>{void 0!==(null==t?void 0:t.id)&&null!==t.id&&e.push(new Ws({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(Fn.LOSSY),hs.PUBLISHER),t(this.dataChannelForKind(Fn.RELIABLE),hs.PUBLISHER),t(this.dataChannelForKind(Fn.LOSSY,!0),hs.SUBSCRIBER),t(this.dataChannelForKind(Fn.RELIABLE,!0),hs.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ga.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Va()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Va()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Yd extends Error{}class Qd{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return za(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return Tr(this,void 0,void 0,(function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter((e=>!this.attemptedRegions.find((t=>t.url===e.url))));if(t.length>0){const e=t[0];return this.attemptedRegions.push(e),fr.debug("next region: ".concat(e.region)),e.url}return null}))}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return Tr(this,void 0,void 0,(function*(){const t=yield fetch("".concat((i=this.serverUrl,"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});var i;if(t.ok){const e=yield t.json();return this.lastUpdateAt=Date.now(),e}throw new ta("Could not fetch region settings: ".concat(t.statusText),401===t.status?Fo.NotAllowed:Fo.InternalError,t.status)}))}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class Xd{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class el extends Xd{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>Tr(this,void 0,void 0,(function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch(t){return{done:!0,value:void 0}}})),return(){return Tr(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return Tr(this,void 0,void 0,(function*(){var e,t,i,n;let s=new Set;try{for(var r,o=!0,a=Sr(this);!(e=(r=yield a.next()).done);o=!0){n=r.value,o=!1;const e=n;s.add(e)}}catch(c){t={error:c}}finally{try{o||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return Array.from(s)}))}}class tl extends Xd{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=cc(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>Tr(this,void 0,void 0,(function*(){try{const{done:i,value:n}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)})}catch(i){return{done:!0,value:void 0}}})),return(){return Tr(this,void 0,void 0,(function*(){return e.releaseLock(),{done:!0,value:void 0}}))}}}readAll(){return Tr(this,void 0,void 0,(function*(){var e,t,i,n;let s="";try{for(var r,o=!0,a=Sr(this);!(e=(r=yield a.next()).done);o=!0)n=r.value,o=!1,s+=n}catch(c){t={error:c}}finally{try{o||e||!(i=a.return)||(yield i.call(a))}finally{if(t)throw t.error}}return s}))}}class il{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return Tr(this,void 0,void 0,(function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)}))}}class nl extends il{}class sl extends il{}class rl extends ba{constructor(e,t,i,n,s){super(e,i,s),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Yo.Muted:Yo.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Yo.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return Tr(this,void 0,void 0,(function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()}))}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval((()=>this.monitorReceiver()),vd)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame((()=>e()));const i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(Yo.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class ol extends rl{constructor(e,t,i,n,s,r){super(e,t,ba.Kind.Audio,i,r),this.monitorReceiver=()=>Tr(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=yd(e,this.prevStats)),this.prevStats=e})),this.audioContext=n,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;qa()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(qa())return 1;let e=0;return this.attachedElements.forEach((t=>{t.volume>e&&(e=t.volume)})),e}setSinkId(e){return Tr(this,void 0,void 0,(function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map((t=>{if(ja(t))return t.setSinkId(e)})))}))}attach(e){const t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&ja(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach((e=>{i.connect(e),i=e})),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then((()=>{"running"!==e.state&&this.emit(Yo.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))})).catch((e=>{this.emit(Yo.AudioPlaybackFailed,e)}))}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return Tr(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;let e;return(yield this.receiver.getStats()).forEach((t=>{"inbound-rtp"===t.type&&(e={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})})),e}))}}class al extends rl{constructor(e,t,i,n,s){super(e,t,ba.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>Tr(this,void 0,void 0,(function*(){if(!this.receiver)return void(this._currentBitrate=0);const e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=yd(e,this.prevStats)),this.prevStats=e})),this.debouncedHandleResize=Qc((()=>{this.updateDimensions()}),100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach((t=>{e?Ta(this._mediaStreamTrack,t):ka(this._mediaStreamTrack,t)}))}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t.element===e))){const t=new cl(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find((t=>t===e))?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream)return void this.log.warn("stopObservingElementInfo ignored",this.logContext);const t=this.elementInfos.filter((t=>t===e));for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter((t=>t!==e)),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return Tr(this,void 0,void 0,(function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",n=new Map;return e.forEach((e=>{"inbound-rtp"===e.type?(i=e.codecId,t={type:"video",streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):"codec"===e.type&&n.set(e.id,e)})),t&&""!==i&&n.get(i)&&(t.mimeType=n.get(i).mimeType),t}))}stopObservingElement(e){const t=this.elementInfos.filter((t=>t.element===e));for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return Tr(this,void 0,void 0,(function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()}))}updateVisibility(){var e,t;const i=this.elementInfos.reduce(((e,t)=>Math.max(e,t.visibilityChangedAt||0)),0),n=!(null!==(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)&&void 0!==t&&!t)&&this.isInBackground,s=this.elementInfos.some((e=>e.pictureInPicture)),r=this.elementInfos.some((e=>e.visible))&&!n||s;this.lastVisible!==r&&(!r&&Date.now()-i<100?ga.setTimeout((()=>{this.updateVisibility()}),100):(this.lastVisible=r,this.emit(Yo.VisibilityChanged,r,this)))}updateDimensions(){var e,t;let i=0,n=0;const s=this.getPixelDensity();for(const r of this.elementInfos){const e=r.width()*s,t=r.height()*s;e+t>i+n&&(i=e,n=t)}(null===(e=this.lastDimensions)||void 0===e?void 0:e.width)===i&&(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)===n||(this.lastDimensions={width:i,height:n},this.emit(Yo.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?Ha():t||(Ha()>2?2:1)}}class cl{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;const{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=dl(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=dl(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=dl(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:ll(e),this.isPiP=Va()&&dl(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=ll(this.element),this.isPiP=dl(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,ec().observe(this.element),Qa().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,s;null===(e=ec())||void 0===e||e.unobserve(this.element),null===(t=Qa())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(s=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===s||s.removeEventListener("pagehide",this.onLeavePiP)}}function dl(e){var t,i;return document.pictureInPictureElement===e||!!(null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)&&ll(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function ll(e,t){const i=t||window;let n=e.offsetTop,s=e.offsetLeft;const r=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:c}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,s+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&s<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&s+r>i.pageXOffset&&!a&&"none"!==c}class ul extends Er.EventEmitter{constructor(e,t,i,n){var s;super(),this.metadataMuted=!1,this.encryption=Dn.NONE,this.log=fr,this.handleMuted=()=>{this.emit(Yo.Muted)},this.handleUnmuted=()=>{this.emit(Yo.Unmuted)},this.log=vr(null!==(s=null==n?void 0:n.loggerName)&&void 0!==s?s:hr.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=ba.Source.Unknown}setTrack(e){this.track&&(this.track.off(Yo.Muted,this.handleMuted),this.track.off(Yo.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Yo.Muted,this.handleMuted),e.on(Yo.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),_c(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==Dn.NONE}get audioTrack(){if(uc(this.track))return this.track}get videoTrack(){if(hc(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=ba.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===ba.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(Vd=(Bd=ul||(ul={})).SubscriptionStatus||(Bd.SubscriptionStatus={})).Desired="desired",Vd.Subscribed="subscribed",Vd.Unsubscribed="unsubscribed",(qd=Bd.PermissionStatus||(Bd.PermissionStatus={})).Allowed="allowed",qd.NotAllowed="not_allowed";class hl extends ul{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Yo.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(Yo.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(Yo.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return Tr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()}))}unmute(){return Tr(this,void 0,void 0,(function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()}))}pauseUpstream(){return Tr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()}))}resumeUpstream(){return Tr(this,void 0,void 0,(function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()}))}getTrackFeatures(){var e;if(uc(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(_n.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(_n.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(_n.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(_n.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(_n.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(_n.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}return[]}}function pl(e,t){return Tr(this,void 0,void 0,(function*(){null!=e||(e={});let i=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=Pc(e);let o=r.audio,a=r.video;if(n&&"object"==typeof r.audio&&(r.audio.processor=n),s&&"object"==typeof r.video&&(r.video.processor=s),e.audio&&"object"==typeof r.audio&&"string"==typeof r.audio.deviceId){const e=r.audio.deviceId;r.audio.deviceId={exact:e},i=!0,o=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:e}})}if(r.video&&"object"==typeof r.video&&"string"==typeof r.video.deviceId){const e=r.video.deviceId;r.video.deviceId={exact:e},i=!0,a=Object.assign(Object.assign({},r.video),{deviceId:{ideal:e}})}(!0===r.audio||"object"==typeof r.audio&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),(!0===r.video||"object"==typeof r.video&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=yc(r,ad,cd),d=kc(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(Oc.userMediaPromiseMap.set("audioinput",l),l.catch((()=>Oc.userMediaPromiseMap.delete("audioinput")))),r.video&&(Oc.userMediaPromiseMap.set("videoinput",l),l.catch((()=>Oc.userMediaPromiseMap.delete("videoinput"))));try{const e=yield l;return yield Promise.all(e.getTracks().map((i=>Tr(this,void 0,void 0,(function*(){const r="audio"===i.kind;let o,a=r?c.audio:c.video;"boolean"!=typeof a&&a||(a={});const l=r?d.audio:d.video;"boolean"!=typeof l&&(o=l);const u=i.getSettings().deviceId;(null==o?void 0:o.deviceId)&&rc(o.deviceId)!==u?o.deviceId=u:o||(o={deviceId:u});const h=function(e,t,i){switch(e.kind){case"audio":return new kd(e,t,!1,void 0,i);case"video":return new Ad(e,t,!1,i);default:throw new na("unsupported track type: ".concat(e.kind))}}(i,o,t);return h.kind===ba.Kind.Video?h.source=ba.Source.Camera:h.kind===ba.Kind.Audio&&(h.source=ba.Source.Microphone),h.mediaStream=e,uc(h)&&n?yield h.setProcessor(n):hc(h)&&s&&(yield h.setProcessor(s)),h})))))}catch(u){if(!i)throw u;return pl(Object.assign(Object.assign({},e),{audio:o,video:a}),t)}}))}(Kd=zd||(zd={})).Excellent="excellent",Kd.Good="good",Kd.Poor="poor",Kd.Lost="lost",Kd.Unknown="unknown";class ml extends Er.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every((e=>e.isEncrypted))}get isAgent(){var e;return(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===An.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,s,r){let o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:An.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=zd.Unknown,this.log=fr,this.log=vr(null!==(a=null==r?void 0:r.loggerName)&&void 0!==a?a:hr.Participant),this.loggerOptions=r,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=null!=s?s:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(ba.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(ba.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(ba.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){return!(this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version||(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),0))}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(Ho.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(Ho.ParticipantNameChanged,e)}_setAttributes(e){const t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});const n=[...Object.keys(t),...Object.keys(e)],s={};for(const r of n)e[r]!==t[r]&&(s[r]=null!==(i=t[r])&&void 0!==i?i:"");return s}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(Ho.AttributesChanged,t)}setPermissions(e){var t,i,n,s,r,o;const a=this.permissions,c=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(s=this.permissions)||void 0===s?void 0:s.hidden)||e.recorder!==(null===(r=this.permissions)||void 0===r?void 0:r.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some(((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])}))||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(Ho.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(Ho.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case Tn.EXCELLENT:return zd.Excellent;case Tn.GOOD:return zd.Good;case Tn.POOR:return zd.Poor;case Tn.LOST:return zd.Lost;default:return zd.Unknown}}(e),t!==this._connectionQuality&&this.emit(Ho.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach((t=>uc(t.track)&&t.track.setAudioContext(e)))}addTrackPublication(e){e.on(Yo.Muted,(()=>{this.emit(Ho.TrackMuted,e)})),e.on(Yo.Unmuted,(()=>{this.emit(Ho.TrackUnmuted,e)}));const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case ba.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case ba.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class gl extends ml{constructor(e,t,i,n,s){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Dn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sc)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var e,t;this.reconnectFuture&&(this.reconnectFuture.promise.catch((e=>this.log.warn(e.message,this.logContext))),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=e=>{const{requestId:t,reason:i,message:n}=e,s=this.pendingSignalRequests.get(t);s&&(i!==nr.OK&&s.reject(new ca(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=md.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let s=e.value.value;this.handleIncomingRpcAck(s.requestId)}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map((e=>function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ks({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})}(e))))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{void 0===t&&(t=!0),e.sid?this.engine.updateMuteStatus(e.sid,t):this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),_c(e)))},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),_c(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),_c(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{const t=this.audioTrackPublications.get(e.sid);t?this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures()):this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext)},this.handleSubscribedQualityUpdate=e=>Tr(this,void 0,void 0,(function*(){var t,i,n,s,r,o;if(!(null===(r=this.roomOptions)||void 0===r?void 0:r.dynacast))return;const a=this.videoTrackPublications.get(e.trackSid);if(a)if(e.subscribedCodecs.length>0){if(!a.videoTrack)return;const r=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var c,d=!0,l=Sr(r);!(t=(c=yield l.next()).done);d=!0){s=c.value,d=!1;const e=s;Ea(e)&&(this.log.debug("publish ".concat(e," for ").concat(a.videoTrack.sid),Object.assign(Object.assign({},this.logContext),_c(a))),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(u){i={error:u}}finally{try{d||t||!(n=l.return)||(yield n.call(l))}finally{if(i)throw i.error}}}else e.subscribedQualities.length>0&&(yield null===(o=a.videoTrack)||void 0===o?void 0:o.setPublishingLayers(e.subscribedQualities));else this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))})),this.handleLocalTrackUnpublished=e=>{const t=this.trackPublications.get(e.trackSid);t?this.unpublishTrack(t.track):this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}))},this.handleTrackEnded=e=>Tr(this,void 0,void 0,(function*(){if(e.source===ba.Source.ScreenShare||e.source===ba.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),_c(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(mc(e)||pc(e))try{if(Va())try{const t=yield null===navigator||void 0===navigator?void 0:navigator.permissions.query({name:e.source===ba.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),_c(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},new Error("GetUserMedia Permission denied")}catch(t){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),_c(e))),mc(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),_c(e))),yield e.mute()}})),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Dn.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(Wo.RemoteMute,((e,t)=>{const i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())})),this.engine.on(Wo.Connected,this.handleReconnected).on(Wo.SignalRestarted,this.handleReconnected).on(Wo.SignalResumed,this.handleReconnected).on(Wo.Restarting,this.handleReconnecting).on(Wo.Resuming,this.handleReconnecting).on(Wo.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Wo.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Wo.Disconnected,this.handleDisconnected).on(Wo.SignalRequestResponse,this.handleSignalRequestResponse).on(Wo.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return Tr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({metadata:e})}))}setName(e){return Tr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({name:e})}))}setAttributes(e){return Tr(this,void 0,void 0,(function*(){yield this.requestMetadataUpdate({attributes:e})}))}requestMetadataUpdate(e){return Tr(this,arguments,void 0,(function(e){var t=this;let{metadata:i,name:n,attributes:s}=e;return function*(){return new Promise(((e,r)=>Tr(t,void 0,void 0,(function*(){var t,o;try{let a=!1;const c=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",s),d=performance.now();for(this.pendingSignalRequests.set(c,{resolve:e,reject:e=>{r(e),a=!0},values:{name:n,metadata:i,attributes:s}});performance.now()-d<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every((e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))))return this.pendingSignalRequests.delete(c),void e();yield Da(50)}r(new ca("Request to update local metadata timed out","TimeoutError"))}catch(a){a instanceof Error&&r(a)}}))))}()}))}setCameraEnabled(e,t,i){return this.setTrackEnabled(ba.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(ba.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(ba.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(Ho.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return Tr(this,void 0,void 0,(function*(){this.encryptionType=e?Dn.GCM:Dn.NONE,yield this.republishAllTracks(void 0,!1)}))}setTrackEnabled(e,t,i,n){return Tr(this,void 0,void 0,(function*(){var s,r;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let t;if(this.pendingPublishing.has(e)){const t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case ba.Source.Camera:t=yield this.createTracks({video:null===(s=i)||void 0===s||s});break;case ba.Source.Microphone:t=yield this.createTracks({audio:null===(r=i)||void 0===r||r});break;case ba.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new na(e)}}catch(a){throw null==t||t.forEach((e=>{e.stop()})),a instanceof Error&&this.emit(Ho.MediaDevicesError,a),this.pendingPublishing.delete(e),a}try{const e=[];for(const s of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),_c(s))),e.push(this.publishTrack(s,n));const i=yield Promise.all(e);[o]=i}catch(a){throw null==t||t.forEach((e=>{e.stop()})),a}finally{this.pendingPublishing.delete(e)}}else if(!(null==o?void 0:o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===ba.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const e=this.getTrackPublication(ba.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield o.mute();return o}))}enableCameraAndMicrophone(){return Tr(this,void 0,void 0,(function*(){if(!this.pendingPublishing.has(ba.Source.Camera)&&!this.pendingPublishing.has(ba.Source.Microphone)){this.pendingPublishing.add(ba.Source.Camera),this.pendingPublishing.add(ba.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map((e=>this.publishTrack(e))))}finally{this.pendingPublishing.delete(ba.Source.Camera),this.pendingPublishing.delete(ba.Source.Microphone)}}}))}createTracks(e){return Tr(this,void 0,void 0,(function*(){var t,i;null!=e||(e={});const n=yc(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield pl(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map((e=>(uc(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=ba.Source.Microphone,this.emit(Ho.AudioStreamAcquired)),hc(e)&&(this.cameraError=void 0,e.source=ba.Source.Camera),e)))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}}))}createScreenTracks(e){return Tr(this,void 0,void 0,(function*(){if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ia("getDisplayMedia not supported");void 0!==e.resolution||function(){const e=ua();return"Safari"===(null==e?void 0:e.name)&&e.version.startsWith("17.")}()||(e.resolution=Aa.h1080fps30.resolution);const t=function(e){var t,i;let n=null===(t=e.video)||void 0===t||t;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(n="boolean"==typeof n?{}:n,n=$a()?Object.assign(Object.assign({},n),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},n),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:null!==(i=e.audio)&&void 0!==i&&i,video:n,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}(e),i=yield navigator.mediaDevices.getDisplayMedia(t),n=i.getVideoTracks();if(0===n.length)throw new na("no video track found");const s=new Ad(n[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=ba.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const r=[s];if(i.getAudioTracks().length>0){this.emit(Ho.AudioStreamAcquired);const e=new kd(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=ba.Source.ScreenShareAudio,r.push(e)}return r}))}publishTrack(e,t){return Tr(this,void 0,void 0,(function*(){return this.publishOrRepublishTrack(e,t)}))}publishOrRepublishTrack(e,t){return Tr(this,arguments,void 0,(function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var s,r,o,a;let c,d;if(mc(e)&&e.setAudioContext(i.audioContext),yield null===(s=i.reconnectFuture)||void 0===s?void 0:s.promise,i.republishPromise&&!n&&(yield i.republishPromise),lc(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)c=e.getConstraints();else{let t;switch(c=e.constraints,e.source){case ba.Source.Microphone:t="audioinput";break;case ba.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(c=Object.assign(Object.assign({},c),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new kd(e,c,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new Ad(e,c,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new na("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach((t=>{t.track&&t.track===e&&(d=t)})),d)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),_c(d))),d;const l="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(r=null==t?void 0:t.forceStereo)&&void 0!==r?r:l;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),_c(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=t.dtx)&&void 0!==o||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));const h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){const e=ua(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&Ga(t,e.osVersion)>=0)||"Safari"===e.name&&Ga(t,e.version)>=0}()&&i.roomOptions.e2ee&&(i.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);const p=new Promise(((t,n)=>Tr(i,void 0,void 0,(function*(){try{if(this.engine.client.currentState!==Lc.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:_c(e)}));const i=()=>Tr(this,void 0,void 0,(function*(){try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}));setTimeout((()=>{this.engine.off(Wo.SignalConnected,i),n(new aa("publishing rejected as engine not connected within timeout",408))}),15e3),this.engine.once(Wo.SignalConnected,i),this.engine.on(Wo.Closing,(()=>{this.engine.off(Wo.SignalConnected,i),n(new aa("publishing rejected as engine closed",499))}))}else try{const i=yield this.publish(e,h,u);t(i)}catch(i){n(i)}}catch(i){n(i)}}))));i.pendingPublishPromises.set(e,p);try{return yield p}catch(m){throw m}finally{i.pendingPublishPromises.delete(e)}}()}))}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),_c(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return!(!t||0!==i.length&&!i.map((e=>function(e){switch(e){case bn.CAMERA:return ba.Source.Camera;case bn.MICROPHONE:return ba.Source.Microphone;case bn.SCREEN_SHARE:return ba.Source.ScreenShare;case bn.SCREEN_SHARE_AUDIO:return ba.Source.ScreenShareAudio;default:return ba.Source.Unknown}}(e))).includes(e.source))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),_c(e))),!1)}publish(e,t,i){return Tr(this,void 0,void 0,(function*(){var n,s,r,o,a,c,d,l,u,h;if(!this.hasPermissionsToPublish(e))throw new aa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find((t=>lc(e)&&t.source===e.source))&&e.source!==ba.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),_c(e))),t.stopMicTrackOnMute&&uc(e)&&(e.stopOnMute=!0),e.source===ba.Source.ScreenShare&&Fa()&&(t.simulcast=!1),"av1"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if($a())return!1;const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),"vp9"!==t.videoCodec||function(){if(!("getCapabilities"in RTCRtpSender))return!1;if(Fa())return!1;if($a()){const e=ua();if((null==e?void 0:e.version)&&Ga(e.version,"16")<0)return!1}const e=RTCRtpSender.getCapabilities("video");let t=!1;if(e)for(const i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}return t}()||(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec=rd),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some((e=>t.videoCodec===wc(e.mime)))||(t.videoCodec=wc(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(Yo.Muted,this.onTrackMuted),e.on(Yo.Unmuted,this.onTrackUnmuted),e.on(Yo.Ended,this.handleTrackEnded),e.on(Yo.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Yo.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Yo.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new ys({cid:e.mediaStreamTrack.id,name:t.name,type:ba.kindToProto(e.kind),muted:e.isMuted,source:ba.sourceToProto(e.source),disableDtx:!(null===(n=t.dtx)||void 0===n||n),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(s=t.red)||void 0===s||s),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy});let g;if(e.kind===ba.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(b){const t=null!==(o=null===(r=this.roomOptions.videoCaptureDefaults)||void 0===r?void 0:r.resolution)&&void 0!==o?o:Oa.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),_c(e)),{dims:i}))}m.width=i.width,m.height=i.height,pc(e)&&(Ua(p)&&(e.source===ba.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),_c(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),m.simulcastCodecs=[new vs({codec:p,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:rd}),t.backupCodec&&p!==t.backupCodec.codec&&m.encryption===Dn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new vs({codec:t.backupCodec.codec,cid:""})))),g=Pd(e.source===ba.Source.ScreenShare,m.width,m.height,t),m.layers=Md(m.width,m.height,g,Ua(t.videoCodec))}else e.kind===ba.Kind.Audio&&(g=[{maxBitrate:null===(c=t.audioPreset)||void 0===c?void 0:c.maxBitrate,priority:null!==(l=null===(d=t.audioPreset)||void 0===d?void 0:d.priority)&&void 0!==l?l:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ra("cannot publish track when not connected");const f=()=>Tr(this,void 0,void 0,(function*(){var i,n,s;if(!this.engine.pcManager)throw new ra("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,g),pc(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=function(e){return e.source===ba.Source.ScreenShare||e.constraints.height&&rc(e.constraints.height)>=1080?"maintain-resolution":"balanced"}(e)),e.setDegradationPreference(t.degradationPreference)),g)if(Fa()&&e.kind===ba.Kind.Audio){let t;for(const i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=g[0])||void 0===n?void 0:n.maxBitrate)?g[0].maxBitrate/1e3:0})}else e.codec&&Ua(e.codec)&&(null===(s=g[0])||void 0===s?void 0:s.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:g[0].maxBitrate/1e3});yield this.engine.negotiate()}));let v;if(this.enabledPublishVideoCodecs.length>0)v=(yield Promise.all([this.engine.addTrack(m),f()]))[0];else{let i;if(v=yield this.engine.addTrack(m),v.codecs.forEach((e=>{void 0===i&&(i=e.mimeType)})),i&&e.kind===ba.Kind.Video){const n=wc(i);n!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),_c(e)),{codec:n})),t.videoCodec=n,g=Pd(e.source===ba.Source.ScreenShare,m.width,m.height,t))}yield f()}const y=new hl(e.kind,v,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return y.options=t,e.sid=v.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:g,trackInfo:v})),pc(e)?e.startMonitor(this.engine.client):mc(e)&&e.startMonitor(),this.addTrackPublication(y),this.emit(Ho.LocalTrackPublished,y),y}))}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return Tr(this,void 0,void 0,(function*(){var n;if(this.encryptionType!==Dn.NONE)return;let s;if(this.trackPublications.forEach((t=>{t.track&&t.track===e&&(s=t)})),!s)throw new na("track is not published");if(!pc(e))throw new na("track is not a video track");const r=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,s,r,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&fr.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;const a=e.mediaStreamTrack.getSettings(),c=null!==(n=a.width)&&void 0!==n?n:null===(s=e.dimensions)||void 0===s?void 0:s.width,d=null!==(r=a.height)&&void 0!==r?r:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===ba.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),Pd(e.source===ba.Source.ScreenShare,c,d,i)}(e,t,r);if(!o)return void this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),_c(e)));const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new ys({cid:a.mediaStreamTrack.id,type:ba.kindToProto(e.kind),muted:e.isMuted,source:ba.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:r.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Md(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new ra("cannot publish track when not connected");const d=(yield Promise.all([this.engine.addTrack(c),(()=>Tr(this,void 0,void 0,(function*(){yield this.engine.createSimulcastSender(e,a,r,o),yield this.engine.negotiate()})))()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))}))}unpublishTrack(e,t){return Tr(this,void 0,void 0,(function*(){var i,n;if(lc(e)){const t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),_c(e))),yield t)}const s=this.getPublicationForTrack(e),r=s?_c(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),r)),!s||!s.track)return void this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),r));(e=s.track).off(Yo.Muted,this.onTrackMuted),e.off(Yo.Unmuted,this.onTrackUnmuted),e.off(Yo.Ended,this.handleTrackEnded),e.off(Yo.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Yo.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Yo.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ud.FAILED&&a)try{for(const e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),pc(e)){for(const[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),r),{error:c}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case ba.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case ba.Kind.Video:this.videoTrackPublications.delete(s.trackSid)}return this.emit(Ho.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s}))}unpublishTracks(e){return Tr(this,void 0,void 0,(function*(){return(yield Promise.all(e.map((e=>this.unpublishTrack(e))))).filter((e=>!!e))}))}republishAllTracks(e){return Tr(this,arguments,void 0,(function(e){var t=this;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise(((n,s)=>Tr(t,void 0,void 0,(function*(){try{const t=[];this.trackPublications.forEach((i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))})),yield Promise.all(t.map((e=>Tr(this,void 0,void 0,(function*(){const t=e.track;yield this.unpublishTrack(t,!1),!i||t.isMuted||t.source===ba.Source.ScreenShare||t.source===ba.Source.ScreenShareAudio||!mc(t)&&!pc(t)||t.isUserProvided||(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))))),n()}catch(t){s(t)}finally{this.republishPromise=void 0}})))),yield t.republishPromise}()}))}publishData(e){return Tr(this,arguments,void 0,(function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){const n=i.reliable?Fn.RELIABLE:Fn.LOSSY,s=i.destinationIdentities,r=i.topic,o=new jn({kind:n,value:{case:"user",value:new Vn({participantIdentity:t.identity,payload:e,destinationIdentities:s,topic:r})}});yield t.engine.sendDataPacket(o,n)}()}))}publishDtmf(e,t){return Tr(this,void 0,void 0,(function*(){const i=new jn({kind:Fn.RELIABLE,value:{case:"sipDtmf",value:new qn({code:e,digit:t})}});yield this.engine.sendDataPacket(i,Fn.RELIABLE)}))}sendChatMessage(e,t){return Tr(this,void 0,void 0,(function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new jn({value:{case:"chatMessage",value:new Zn(Object.assign(Object.assign({},i),{timestamp:ti.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,Fn.RELIABLE),this.emit(Ho.ChatMessage,i),i}))}editChatMessage(e,t){return Tr(this,void 0,void 0,(function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new jn({value:{case:"chatMessage",value:new Zn(Object.assign(Object.assign({},i),{timestamp:ti.parse(i.timestamp),editTimestamp:ti.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,Fn.RELIABLE),this.emit(Ho.ChatMessage,i),i}))}sendText(e,t){return Tr(this,void 0,void 0,(function*(){var i;const n=crypto.randomUUID(),s=(new TextEncoder).encode(e).byteLength,r=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map((()=>crypto.randomUUID())),o=new Array(r?r.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;const s=o.reduce(((e,t)=>e+t),0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,s)},c=yield this.streamText({streamId:n,totalSize:s,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:r,attributes:null==t?void 0:t.attributes});return yield c.write(e),a(1,0),yield c.close(),(null==t?void 0:t.attachments)&&r&&(yield Promise.all(t.attachments.map(((e,i)=>Tr(this,void 0,void 0,(function*(){return this._sendFile(r[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))))),c.info}))}streamText(e){return Tr(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),s={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},r=new ds({streamId:n,mimeType:s.mimeType,topic:s.topic,timestamp:dc(s.timestamp),totalLength:dc(null==e?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new as({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:"update"===(null==e?void 0:e.type)?os.UPDATE:os.CREATE})}}),o=null==e?void 0:e.destinationIdentities,a=new jn({destinationIdentities:o,value:{case:"streamHeader",value:r}});yield this.engine.sendDataPacket(a,Fn.RELIABLE);let c=0;const d=this,l=new WritableStream({write(e){return Tr(this,void 0,void 0,(function*(){for(const t of function(e){const t=[];let i=(new TextEncoder).encode(e);for(;i.length>15e3;){let e=15e3;for(;e>0;){const t=i[e];if(void 0!==t&&128!=(192&t))break;e--}t.push(i.slice(0,e)),i=i.slice(e)}return i.length>0&&t.push(i),t}(e)){yield d.engine.waitForBufferStatusLow(Fn.RELIABLE);const e=new ls({content:t,streamId:n,chunkIndex:dc(c)}),i=new jn({destinationIdentities:o,value:{case:"streamChunk",value:e}});yield d.engine.sendDataPacket(i,Fn.RELIABLE),c+=1}}))},close(){return Tr(this,void 0,void 0,(function*(){const e=new us({streamId:n}),t=new jn({destinationIdentities:o,value:{case:"streamTrailer",value:e}});yield d.engine.sendDataPacket(t,Fn.RELIABLE)}))},abort(e){console.log("Sink error:",e)}});let u=()=>Tr(this,void 0,void 0,(function*(){yield h.close()}));d.engine.once(Wo.Closing,u);const h=new nl(l,s,(()=>this.engine.off(Wo.Closing,u)));return h}))}sendFile(e,t){return Tr(this,void 0,void 0,(function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}}))}_sendFile(e,t,i){return Tr(this,void 0,void 0,(function*(){var n;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),r=t.stream().getReader();for(;;){const{done:e,value:t}=yield r.read();if(e)break;yield s.write(t)}return yield s.close(),s.info}))}streamBytes(e){return Tr(this,void 0,void 0,(function*(){var t,i,n,s,r;const o=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,c={id:o,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(s=null==e?void 0:e.name)&&void 0!==s?s:"unknown"},d=new ds({totalLength:dc(null!==(r=c.size)&&void 0!==r?r:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:dc(Date.now()),contentHeader:{case:"byteHeader",value:new cs({name:c.name})}}),l=new jn({destinationIdentities:a,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(l,Fn.RELIABLE);let u=0;const h=new Mt,p=this.engine,m=this.log,g=new WritableStream({write(e){return Tr(this,void 0,void 0,(function*(){const t=yield h.lock();let i=0;try{for(;i<e.byteLength;){const t=e.slice(i,i+15e3);yield p.waitForBufferStatusLow(Fn.RELIABLE);const n=new jn({destinationIdentities:a,value:{case:"streamChunk",value:new ls({content:t,streamId:o,chunkIndex:dc(u)})}});yield p.sendDataPacket(n,Fn.RELIABLE),u+=1,i+=t.byteLength}}finally{t()}}))},close(){return Tr(this,void 0,void 0,(function*(){const e=new us({streamId:o}),t=new jn({destinationIdentities:a,value:{case:"streamTrailer",value:e}});yield p.sendDataPacket(t,Fn.RELIABLE)}))},abort(e){m.error("Sink error:",e)}});return new sl(g,c)}))}performRpc(e){return Tr(this,arguments,void 0,(function(e){var t=this;let{destinationIdentity:i,method:n,payload:s,responseTimeout:r=1e4}=e;return function*(){return new Promise(((e,o)=>Tr(t,void 0,void 0,(function*(){var t,a,c,d;if(gd(s)>15360)return void o(md.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&Ga(null===(d=null===(c=this.engine.latestJoinResponse)||void 0===c?void 0:c.serverInfo)||void 0===d?void 0:d.version,"1.8.0")<0)return void o(md.builtIn("UNSUPPORTED_SERVER"));const l=crypto.randomUUID();yield this.publishRpcRequest(i,l,n,s,r-2e3);const u=setTimeout((()=>{this.pendingAcks.delete(l),o(md.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(l),clearTimeout(h)}),2e3);this.pendingAcks.set(l,{resolve:()=>{clearTimeout(u)},participantIdentity:i});const h=setTimeout((()=>{this.pendingResponses.delete(l),o(md.builtIn("RESPONSE_TIMEOUT"))}),r);this.pendingResponses.set(l,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(l)&&(console.warn("RPC response received before ack",l),this.pendingAcks.delete(l),clearTimeout(u)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))))}()}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,s){return Tr(this,void 0,void 0,(function*(){const r=new jn({destinationIdentities:[e],kind:Fn.RELIABLE,value:{case:"rpcRequest",value:new Hn({id:t,method:i,payload:n,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(r,Fn.RELIABLE)}))}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,md.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter((e=>"video"===e.mime.split("/")[0].toLowerCase()))}updateInfo(e){return e.sid===this.sid&&!!super.updateInfo(e)&&(e.tracks.forEach((e=>{var t,i;const n=this.trackPublications.get(e.sid);if(n){const s=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;s!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),_c(n)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(e.sid,s))}})),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach((i=>{const n=i.track;n&&(e instanceof MediaStreamTrack?(mc(n)||pc(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))})),t}waitForPendingPublicationOfSource(e){return Tr(this,void 0,void 0,(function*(){const t=Date.now();for(;Date.now()<t+1e4;){const t=Array.from(this.pendingPublishPromises.entries()).find((t=>{let[i]=t;return i.source===e}));if(t)return t[1];yield Da(20)}}))}}class fl extends ul{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=va.HIGH,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Yo.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.disabled=!e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensions=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const n=new Ps({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Yn({participantSid:"",trackSids:[this.trackSid]})]});this.emit(Yo.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?ul.SubscriptionStatus.Unsubscribed:super.isSubscribed?ul.SubscriptionStatus.Subscribed:ul.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?ul.PermissionStatus.Allowed:ul.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.disabled!==!e&&(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.currentVideoQuality!==e&&(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.videoDimensions)||void 0===t?void 0:t.width)===e.width&&(null===(i=this.videoDimensions)||void 0===i?void 0:i.height)===e.height||(vc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&vc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(Yo.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(Yo.VisibilityChanged,this.handleVisibilityChange),n.off(Yo.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(Yo.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Yo.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Yo.VisibilityChanged,this.handleVisibilityChange),e.on(Yo.Ended,this.handleEnded),this.emit(Yo.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Yo.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Yo.Muted:Yo.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(Yo.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Yo.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===ba.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return vc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Rs({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):void 0!==this.currentVideoQuality?e.quality=this.currentVideoQuality:e.quality=va.HIGH,this.emit(Yo.UpdateSettings,e)}}class vl extends ml{static fromParticipantInfo(e,t,i){return new vl(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,n,s,r,o){super(t,i||"",n,s,r,o,arguments.length>7&&void 0!==arguments[7]?arguments[7]:An.STANDARD),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(Yo.UpdateSettings,(t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),_c(e))),this.signalClient.sendUpdateTrackSettings(t)})),e.on(Yo.UpdateSubscription,(e=>{e.participantTracks.forEach((e=>{e.participantSid=this.sid})),this.signalClient.sendUpdateSubscription(e)})),e.on(Yo.SubscriptionPermissionChanged,(t=>{this.emit(Ho.TrackSubscriptionPermissionChanged,e,t)})),e.on(Yo.SubscriptionStatusChanged,(t=>{this.emit(Ho.TrackSubscriptionStatusChanged,e,t)})),e.on(Yo.Subscribed,(t=>{this.emit(Ho.TrackSubscribed,t,e)})),e.on(Yo.Unsubscribed,(t=>{this.emit(Ho.TrackUnsubscribed,t,e)})),e.on(Yo.SubscriptionFailed,(t=>{this.emit(Ho.TrackSubscriptionFailed,e.trackSid,t)}))}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ba.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ba.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,s,r){let o,a=this.getTrackPublicationBySid(t);return a||t.startsWith("TR")||this.trackPublications.forEach((t=>{a||e.kind!==t.kind.toString()||(a=t)})),a?"ended"===e.readyState?(this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),_c(a))),void this.emit(Ho.TrackSubscriptionFailed,t)):(o="video"===e.kind?new al(e,t,n,s):new ol(e,t,n,this.audioContext,this.audioOutput),o.source=a.source,o.isMuted=a.isMuted,o.setMediaStream(i),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&gc(o)&&uc(o)&&o.setVolume(this.volumeMap.get(a.source)),a):0===r?(this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),void this.emit(Ho.TrackSubscriptionFailed,t)):(void 0===r&&(r=20),void setTimeout((()=>{this.addSubscribedMediaTrack(e,t,i,n,s,r-1)}),150))}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach((e=>{var n,s;let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{const t=ba.kindFromProto(e.type);if(!t)return;r=new fl(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(s=this.loggerOptions)||void 0===s?void 0:s.loggerName}),r.updateInfo(e),i.set(e.sid,r);const o=Array.from(this.trackPublications.values()).find((e=>e.source===(null==r?void 0:r.source)));o&&r.source!==ba.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(r.source),Object.assign(Object.assign({},this.logContext),{oldTrack:_c(o),newTrack:_c(r)})),this.addTrackPublication(r)}t.set(e.sid,r)})),this.trackPublications.forEach((e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),_c(e))),this.unpublishTrack(e.trackSid,!0))})),i.forEach((e=>{this.emit(Ho.TrackPublished,e)})),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case ba.Kind.Audio:this.audioTrackPublications.delete(e);break;case ba.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(Ho.TrackUnpublished,i)}setAudioOutput(e){return Tr(this,void 0,void 0,(function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach((i=>{var n;uc(i.track)&&gc(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))})),yield Promise.all(t)}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}(Hd=Zd||(Zd={})).Disconnected="disconnected",Hd.Connecting="connecting",Hd.Connected="connected",Hd.Reconnecting="reconnecting",Hd.SignalReconnecting="signalReconnecting";class yl extends Er.EventEmitter{constructor(e){var t,i,n,s;if(super(),t=this,this.state=Zd.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=fr,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(e,t,i)=>Tr(this,void 0,void 0,(function*(){var n;if("undefined"==typeof RTCPeerConnection||!Ma()&&!La())throw qa()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const s=yield this.disconnectLock.lock();if(this.state===Zd.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),s(),Promise.resolve();if(this.connectFuture)return s(),this.connectFuture.promise;this.setAndEmitConnectionState(Zd.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),za(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new Qd(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then((e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)})).catch((e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))})));const r=(n,o,a)=>Tr(this,void 0,void 0,(function*(){var c,d;this.abortController&&this.abortController.abort();const l=new AbortController;this.abortController=l,null==s||s();try{yield this.attemptConnection(null!=a?a:e,t,i,l),this.abortController=void 0,n()}catch(u){if(this.regionUrlProvider&&u instanceof ta&&u.reason!==Fo.Cancelled&&u.reason!==Fo.NotAllowed){let e=null;try{e=yield this.regionUrlProvider.getNextBestRegionUrl(null===(c=this.abortController)||void 0===c?void 0:c.signal)}catch(h){if(h instanceof ta&&(401===h.status||h.reason===Fo.Cancelled))return this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),void o(h)}e&&!(null===(d=this.abortController)||void 0===d?void 0:d.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(u.message,". Retrying with another region: ").concat(e),this.logContext),this.recreateEngine(),yield r(n,o,e)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ac(u)),o(u))}else{let e=Cn.UNKNOWN_REASON;u instanceof ta&&(e=ac(u)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(u)}}})),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sc(((e,t)=>{r(e,t,o)}),(()=>{this.clearConnectionFutures()})),this.connectFuture.promise})),this.connectSignal=(e,t,i,n,s,r)=>Tr(this,void 0,void 0,(function*(){var o,a,c;const d=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof s.adaptiveStream||s.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},r.signal);let l=d.serverInfo;if(l||(l={version:d.serverVersion,region:d.serverRegion}),this.serverInfo=l,this.log.debug("connected to Livekit Server ".concat(Object.entries(l).map((e=>{let[t,i]=e;return"".concat(t,": ").concat(i)})).join(", ")),{room:null===(o=d.room)||void 0===o?void 0:o.name,roomSid:null===(a=d.room)||void 0===a?void 0:a.sid,identity:null===(c=d.participant)||void 0===c?void 0:c.identity}),!l.version)throw new sa("unknown server version");return"0.15.1"===l.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),s.dynacast=!1),d})),this.applyJoinResponse=e=>{const t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(i){this.log.error(i instanceof Error?i.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:i}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>Tr(this,void 0,void 0,(function*(){var s,r;this.state===Zd.Reconnecting||this.isResuming||(null===(s=this.engine)||void 0===s?void 0:s.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(r=this.regionUrlProvider)||void 0===r?void 0:r.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},ld),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(Ko.SignalConnected)}catch(o){yield this.engine.close(),this.recreateEngine();const e=new ta("could not establish signal connection",Fo.ServerUnreachable);throw o instanceof Error&&(e.message="".concat(e.message,": ").concat(o.message)),o instanceof ta&&(e.reason=o.reason,e.status=o.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:o})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new ta("Connection attempt aborted",Fo.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(a){throw yield this.engine.close(),this.recreateEngine(),a}Va()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Va()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Zd.Connected),this.emit(Ko.Connected),this.registerConnectionReconcile()})),this.disconnect=function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return Tr(t,[...i],void 0,(function(){var e=this;let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return function*(){var i,n,s,r;const o=yield e.disconnectLock.lock();try{if(e.state===Zd.Disconnected)return void e.log.debug("already disconnected",e.logContext);e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===Zd.Connecting||e.state===Zd.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(s=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===s||s.call(n,new ta("Client initiated disconnect",Fo.Cancelled)),e.connectFuture=void 0),(null===(r=e.engine)||void 0===r?void 0:r.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,Cn.CLIENT_INITIATED),e.engine=void 0}finally{o()}}()}))},this.onPageLeave=()=>Tr(this,void 0,void 0,(function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()})),this.startAudio=()=>Tr(this,void 0,void 0,(function*(){const e=[],t=ua();if(t&&"iOS"===t.os){const t="livekit-dummy-audio-el";let i=document.getElementById(t);if(!i){i=document.createElement("audio"),i.id=t,i.autoplay=!0,i.hidden=!0;const e=nc();e.enabled=!0;const n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",(()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))})),document.body.append(i),this.once(Ko.Disconnected,(()=>{null==i||i.remove(),i=null}))}e.push(i)}this.remoteParticipants.forEach((t=>{t.audioTrackPublications.forEach((t=>{t.track&&t.track.attachedElements.forEach((t=>{e.push(t)}))}))}));try{yield Promise.all([this.acquireAudioContext(),...e.map((e=>(e.muted=!1,e.play())))]),this.handleAudioPlaybackStarted()}catch(i){throw this.handleAudioPlaybackFailed(i),i}})),this.startVideo=()=>Tr(this,void 0,void 0,(function*(){const e=[];for(const t of this.remoteParticipants.values())t.videoTrackPublications.forEach((t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach((t=>{e.includes(t)||e.push(t)}))}));yield Promise.all(e.map((e=>e.play()))).then((()=>{this.handleVideoPlaybackStarted()})).catch((e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)}))})),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(Zd.Reconnecting)&&this.emit(Ko.Reconnecting)},this.handleSignalRestarted=e=>Tr(this,void 0,void 0,(function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(t){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:t}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(i){return}this.setAndEmitConnectionState(Zd.Connected),this.emit(Ko.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()})),this.handleParticipantUpdates=e=>{e.forEach((e=>{var t;if(e.identity===this.localParticipant.identity)return void this.localParticipant.updateInfo(e);""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===In.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)}))},this.handleActiveSpeakersUpdate=e=>{const t=[],i={};e.forEach((e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{const i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}})),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach((e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))})),this.activeSpeakers=t,this.emitWhenConnected(Ko.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{const t=new Map;this.activeSpeakers.forEach((e=>{const i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)})),e.forEach((e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))}));const i=Array.from(t.values());i.sort(((e,t)=>t.audioLevel-e.audioLevel)),this.activeSpeakers=i,this.emitWhenConnected(Ko.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach((e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;const n=ba.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(Ho.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(Ko.TrackStreamStateChanged,i,i.track.streamState,t))}))},this.handleSubscriptionPermissionUpdate=e=>{const t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{const t=Array.from(this.remoteParticipants.values()).find((t=>t.trackPublications.has(e.trackSid)));if(!t)return;const i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{const t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){const t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(Ko.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(Ho.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(Ko.SipDTMFReceived,t,e),null==e||e.emit(Ho.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{const i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),s=function(e,t){return e.segments.map((e=>{let{id:i,text:n,language:s,startTime:r,endTime:o,final:a}=e;var c;const d=null!==(c=t.get(i))&&void 0!==c?c:Date.now(),l=Date.now();return a?t.delete(i):t.set(i,d),{id:i,text:n,startTime:Number.parseInt(r.toString()),endTime:Number.parseInt(o.toString()),final:a,language:s,firstReceivedTime:d,lastReceivedTime:l}}))}(t,this.transcriptionReceivedTimes);null==n||n.emit(Yo.TranscriptionReceived,s),null==i||i.emit(Ho.TranscriptionReceived,s,n),this.emit(Ko.TranscriptionReceived,s,i,n)},this.handleChatMessage=(e,t)=>{const i=function(e){const{id:t,timestamp:i,message:n,editTimestamp:s}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}(t);this.emit(Ko.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(Ko.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Ko.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Ko.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Ko.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Ko.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>Tr(this,void 0,void 0,(function*(){var e,t,i;const n=Oc.getInstance().previousDevices,s=yield Oc.getInstance().getDevices(void 0,!1),r=ua();if("Chrome"===(null==r?void 0:r.name)&&"iOS"!==r.os)for(let a of s){const e=n.find((e=>e.deviceId===a.deviceId));e&&""!==e.label&&e.kind===a.kind&&e.label!==a.label&&"default"===this.getActiveDevice(a.kind)&&this.emit(Ko.ActiveDeviceChanged,a.kind,a.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let a of o){const r=Sc(a),o=this.localParticipant.getTrackPublication(r);if(o&&(null===(e=o.track)||void 0===e?void 0:e.isUserProvided))continue;const c=s.filter((e=>e.kind===a)),d=this.getActiveDevice(a);d===(null===(t=n.filter((e=>e.kind===a))[0])||void 0===t?void 0:t.deviceId)&&c.length>0&&(null===(i=c[0])||void 0===i?void 0:i.deviceId)!==d?yield this.switchActiveDevice(a,c[0].deviceId):"audioinput"===a&&!$a()||"videoinput"===a||c.length>0&&!c.find((e=>e.deviceId===this.getActiveDevice(a)))&&(yield this.switchActiveDevice(a,c[0].deviceId))}this.emit(Ko.MediaDevicesChanged)})),this.handleRoomUpdate=e=>{const t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Ko.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(Ko.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach((e=>{if(e.participantSid===this.localParticipant.sid)return void this.localParticipant.setConnectionQuality(e.quality);const t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)}))},this.onLocalParticipantMetadataChanged=e=>{this.emit(Ko.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Ko.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Ko.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Ko.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Ko.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>Tr(this,void 0,void 0,(function*(){var t,i,n,s,r,o;null===(t=e.track)||void 0===t||t.on(Yo.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(Yo.Restarted,this.onLocalTrackRestarted),null===(r=null===(s=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===s?void 0:s.onPublish)||void 0===r||r.call(s,this),this.emit(Ko.LocalTrackPublished,e,this.localParticipant),mc(e.track)&&(yield e.track.checkForSilence())&&this.emit(Ko.LocalAudioSilenceDetected,e);const a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),c=Cc(e.source);c&&a&&a!==this.localParticipant.activeDeviceMap.get(c)&&(this.localParticipant.activeDeviceMap.set(c,a),this.emit(Ko.ActiveDeviceChanged,c,a))})),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(Yo.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(Yo.Restarted,this.onLocalTrackRestarted),this.emit(Ko.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>Tr(this,void 0,void 0,(function*(){const t=yield e.getDeviceId(!1),i=Cc(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(Ko.ActiveDeviceChanged,i,t))})),this.onLocalConnectionQualityChanged=e=>{this.emit(Ko.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=e=>{this.emit(Ko.MediaDevicesError,e)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Ko.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Ko.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},dd),e),this.log=vr(null!==(i=this.options.loggerName)&&void 0!==i?i:hr.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ad),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},cd),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},od),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Mt,this.localParticipant=new gl("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",rc(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",rc(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",rc(this.options.audioOutput.deviceId)).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),this.options.e2ee&&this.setupE2EE(),Va()){const e=new AbortController;null===(s=navigator.mediaDevices)||void 0===s||s.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),yl.cleanupRegistry&&yl.cleanupRegistry.register(this,(()=>{e.abort()}))}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,i,n,s,r){return Tr(this,void 0,void 0,(function*(){if(yield this.engine.publishRpcAck(e,t),1!==r)return void(yield this.engine.publishRpcResponse(e,t,null,md.builtIn("UNSUPPORTED_VERSION")));const o=this.rpcHandlers.get(i);if(!o)return void(yield this.engine.publishRpcResponse(e,t,null,md.builtIn("UNSUPPORTED_METHOD")));let a=null,c=null;try{const r=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:s});gd(r)>15360?(a=md.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):c=r}catch(d){d instanceof md?a=d:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),d),a=md.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)}))}setE2EEEnabled(e){return Tr(this,void 0,void 0,(function*(){if(!this.e2eeManager)throw Error("e2ee not configured, please set e2ee settings within the room options");yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),""!==this.localParticipant.identity&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity)}))}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new Rc(this.options.e2ee),this.e2eeManager.on(Lo.ParticipantEncryptionStatusChanged,((e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(Ko.ParticipantEncryptionStatusChanged,e,t)})),this.e2eeManager.on(Lo.EncryptionError,(e=>this.emit(Ko.EncryptionError,e))),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return Tr(this,void 0,void 0,(function*(){return this.state===Zd.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise(((e,t)=>{const i=t=>{""!==t.sid&&(this.engine.off(Wo.RoomUpdate,i),e(t.sid))};this.engine.on(Wo.RoomUpdate,i),this.once(Ko.Disconnected,(()=>{this.engine.off(Wo.RoomUpdate,i),t("Room disconnected before room server id was available")}))}))}))}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Jd(this.options),this.engine.on(Wo.ParticipantUpdate,this.handleParticipantUpdates).on(Wo.RoomUpdate,this.handleRoomUpdate).on(Wo.SpeakersChanged,this.handleSpeakersChanged).on(Wo.StreamStateChanged,this.handleStreamStateUpdate).on(Wo.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Wo.SubscriptionError,this.handleSubscriptionError).on(Wo.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Wo.MediaTrackAdded,((e,t,i)=>{this.onTrackAdded(e,t,i)})).on(Wo.Disconnected,(e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)})).on(Wo.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Wo.DataPacketReceived,this.handleDataPacket).on(Wo.Resuming,(()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Zd.SignalReconnecting)&&this.emit(Ko.SignalReconnecting)})).on(Wo.Resumed,(()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Zd.Connected)&&this.emit(Ko.Reconnected)})).on(Wo.SignalResumed,(()=>{this.bufferedEvents=[],(this.state===Zd.Reconnecting||this.isResuming)&&this.sendSyncState()})).on(Wo.Restarting,this.handleRestarting).on(Wo.SignalRestarted,this.handleSignalRestarted).on(Wo.Offline,(()=>{this.setAndEmitConnectionState(Zd.Reconnecting)&&this.emit(Ko.Reconnecting)})).on(Wo.DCBufferStatusChanged,((e,t)=>{this.emit(Ko.DCBufferStatusChanged,e,t)})).on(Wo.LocalTrackSubscribed,(e=>{const t=this.localParticipant.getTrackPublications().find((t=>{let{trackSid:i}=t;return i===e}));t?(this.localParticipant.emit(Ho.LocalTrackSubscribed,t),this.emitWhenConnected(Ko.LocalTrackSubscribed,t,this.localParticipant)):this.log.warn("could not find local track subscription for subscribed event",this.logContext)})),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Oc.getInstance().getDevices(e,t)}prepareConnection(e,t){return Tr(this,void 0,void 0,(function*(){if(this.state===Zd.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(za(new URL(e))&&t){this.regionUrlProvider=new Qd(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Zd.Disconnected&&(this.regionUrl=i,yield fetch(oc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(oc(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}}))}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return Tr(this,void 0,void 0,(function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Js({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Js({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Js({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Js({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>Tr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Js({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>Tr(this,void 0,void 0,(function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")})),i=new Js({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new Js({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>Tr(this,void 0,void 0,(function*(){const e=this.engine.client.onLeave;e&&e(new Is({reason:Cn.CLIENT_INITIATED,action:As.RECONNECT}))}));break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw new Error("subscriber-bandwidth requires a number as argument");i=new Js({scenario:{case:"subscriberBandwidth",value:dc(t)}});break;case"leave-full-reconnect":i=new Js({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())}))}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return Tr(this,arguments,void 0,(function(e,t){var i=this;let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return function*(){var s,r,o,a,c,d,l,u;let h=!0,p=!1;const m=n?{exact:t}:t;if("audioinput"===e){p=0===i.localParticipant.audioTrackPublications.size;const t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.audioTrackPublications.values()).filter((e=>e.source===ba.Source.Microphone));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.audioCaptureDefaults.deviceId=t,g}}else if("videoinput"===e){p=0===i.localParticipant.videoTrackPublications.size;const t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=m;const n=Array.from(i.localParticipant.videoTrackPublications.values()).filter((e=>e.source===ba.Source.Camera));try{h=(yield Promise.all(n.map((e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(m)})))).every((e=>!0===e))}catch(g){throw i.options.videoCaptureDefaults.deviceId=t,g}}else if("audiooutput"===e){if(!ja()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");i.options.webAudioMix&&(t=null!==(o=yield Oc.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(u=i.options).audioOutput)&&void 0!==a||(u.audioOutput={});const n=null!==(c=i.getActiveDevice(e))&&void 0!==c?c:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(d=i.audioContext)||void 0===d||d.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map((e=>e.setAudioOutput({deviceId:t}))))}catch(g){throw i.options.audioOutput.deviceId=n,g}}return(p||"audiooutput"===e)&&(i.localParticipant.activeDeviceMap.set(e,"audiooutput"===e&&(null===(l=i.options.audioOutput)||void 0===l?void 0:l.deviceId)||t),i.emit(Ko.ActiveDeviceChanged,e,t)),h}()}))}setupLocalParticipantEvents(){this.localParticipant.on(Ho.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(Ho.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(Ho.AttributesChanged,this.onLocalAttributesChanged).on(Ho.TrackMuted,this.onLocalTrackMuted).on(Ho.TrackUnmuted,this.onLocalTrackUnmuted).on(Ho.LocalTrackPublished,this.onLocalTrackPublished).on(Ho.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(Ho.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(Ho.MediaDevicesError,this.onMediaDevicesError).on(Ho.AudioStreamAcquired,this.startAudio).on(Ho.ChatMessage,this.onLocalChatMessageSent).on(Ho.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===Zd.Connecting||this.state===Zd.Reconnecting){const n=()=>{this.onTrackAdded(e,t,i),s()},s=()=>{this.off(Ko.Reconnected,n),this.off(Ko.Connected,n),this.off(Ko.Disconnected,s)};return this.once(Ko.Reconnected,n),this.once(Ko.Connected,n),void this.once(Ko.Disconnected,s)}if(this.state===Zd.Disconnected)return void this.log.warn("skipping incoming track after Room disconnected",this.logContext);if("ended"===e.readyState)return void this.log.info("skipping incoming track as it already ended",this.logContext);const n=function(e){const t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=n[0];let r=n[1],o=e.id;if(r&&r.startsWith("TR")&&(o=r),s===this.localParticipant.sid)return void this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);const a=Array.from(this.remoteParticipants.values()).find((e=>e.sid===s));if(!a)return void this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);let c;this.options.adaptiveStream&&(c="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),a.addSubscribedMediaTrack(e,o,t,i,c)}handleDisconnect(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Zd.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach((e=>{e.trackPublications.forEach((t=>{e.unpublishTrack(t.trackSid)}))})),this.localParticipant.trackPublications.forEach((t=>{var i,n,s;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?(null===(i=t.track)||void 0===i||i.detach(),null===(n=t.track)||void 0===n||n.stop()):null===(s=t.track)||void 0===s||s.stopMonitor()})),this.localParticipant.off(Ho.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(Ho.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(Ho.AttributesChanged,this.onLocalAttributesChanged).off(Ho.TrackMuted,this.onLocalTrackMuted).off(Ho.TrackUnmuted,this.onLocalTrackUnmuted).off(Ho.LocalTrackPublished,this.onLocalTrackPublished).off(Ho.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(Ho.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(Ho.MediaDevicesError,this.onMediaDevicesError).off(Ho.AudioStreamAcquired,this.startAudio).off(Ho.ChatMessage,this.onLocalChatMessageSent).off(Ho.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),Va()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(i=navigator.mediaDevices)||void 0===i||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Zd.Disconnected),this.emit(Ko.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach((e=>{t.unpublishTrack(e.trackSid,!0)})),this.emit(Ko.ParticipantDisconnected,t),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return Tr(this,void 0,void 0,(function*(){var i;if("byteHeader"===e.contentHeader.case){const n=this.byteStreamHandlers.get(e.topic);if(!n)return void this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);let s;const r={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:cc(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:t=>{s=t,this.byteStreamControllers.set(e.streamId,{info:r,controller:s,startTime:Date.now()})}});n(new el(r,o,cc(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){const i=this.textStreamHandlers.get(e.topic);if(!i)return void this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);let n;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},r=new ReadableStream({start:t=>{n=t,this.textStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});i(new tl(s,r,cc(e.totalLength)),{identity:t})}}))}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return Tr(this,void 0,void 0,(function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=Tc())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach((e=>e.setAudioContext(this.audioContext))),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),Da(200)])}catch(n){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:n}))}const i="running"===(null===(t=this.audioContext)||void 0===t?void 0:t.state);i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(Ko.AudioPlaybackStatusChanged,i))}))}createParticipant(e,t){var i;let n;return n=t?vl.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new vl(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch((e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext))),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Ko.ParticipantConnected,i),i.on(Ho.TrackPublished,(e=>{this.emitWhenConnected(Ko.TrackPublished,e,i)})).on(Ho.TrackSubscribed,((e,t)=>{e.kind===ba.Kind.Audio?(e.on(Yo.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Yo.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===ba.Kind.Video&&(e.on(Yo.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Yo.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(Ko.TrackSubscribed,e,t,i)})).on(Ho.TrackUnpublished,(e=>{this.emit(Ko.TrackUnpublished,e,i)})).on(Ho.TrackUnsubscribed,((e,t)=>{this.emit(Ko.TrackUnsubscribed,e,t,i)})).on(Ho.TrackMuted,(e=>{this.emitWhenConnected(Ko.TrackMuted,e,i)})).on(Ho.TrackUnmuted,(e=>{this.emitWhenConnected(Ko.TrackUnmuted,e,i)})).on(Ho.ParticipantMetadataChanged,(e=>{this.emitWhenConnected(Ko.ParticipantMetadataChanged,e,i)})).on(Ho.ParticipantNameChanged,(e=>{this.emitWhenConnected(Ko.ParticipantNameChanged,e,i)})).on(Ho.AttributesChanged,(e=>{this.emitWhenConnected(Ko.ParticipantAttributesChanged,e,i)})).on(Ho.ConnectionQualityChanged,(e=>{this.emitWhenConnected(Ko.ConnectionQualityChanged,e,i)})).on(Ho.ParticipantPermissionsChanged,(e=>{this.emitWhenConnected(Ko.ParticipantPermissionsChanged,e,i)})).on(Ho.TrackSubscriptionStatusChanged,((e,t)=>{this.emitWhenConnected(Ko.TrackSubscriptionStatusChanged,e,t,i)})).on(Ho.TrackSubscriptionFailed,((e,t)=>{this.emit(Ko.TrackSubscriptionFailed,e,i,t)})).on(Ho.TrackSubscriptionPermissionChanged,((e,t)=>{this.emitWhenConnected(Ko.TrackSubscriptionPermissionChanged,e,t,i)})),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce(((e,t)=>(e.push(...t.getTrackPublications()),e)),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&fc(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ga.setInterval((()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Cn.STATE_MISMATCH)))}),4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&ga.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(Ko.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach((e=>{let[t,i]=e;this.emit(t,...i)})),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===Zd.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Zd.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return Tr(this,void 0,void 0,(function*(){var t,i;const n=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Pn({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ti.parse((new Date).getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new On({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(Ko.SignalConnected),this.emit(Ko.Connected),this.setAndEmitConnectionState(Zd.Connected),n.video){const e=new hl(ba.Kind.Video,new Ln({source:bn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO,name:"video-dummy"}),new Ad(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:tc(160*(null!==(t=s.aspectRatios[0])&&void 0!==t?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Ho.LocalTrackPublished,e)}if(n.audio){const e=new hl(ba.Kind.Audio,new Ln({source:bn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO}),new kd(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:nc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(Ho.LocalTrackPublished,e)}for(let e=0;e<s.count-1;e+=1){let t=new On({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:In.ACTIVE,tracks:[],joinedAt:ti.parse(Date.now())});const n=this.getOrCreateParticipant(t.identity,t);if(s.video){const r=tc(160*(null!==(i=s.aspectRatios[e%s.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),o=new Ln({source:bn.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO});n.addSubscribedMediaTrack(r,o.sid,new MediaStream([r]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(s.audio){const e=nc(),i=new Ln({source:bn.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:yn.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}}))}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==Ko.ActiveSpeakersChanged&&e!==Ko.TranscriptionReceived){const t=bl(i).filter((e=>void 0!==e));this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}function bl(e){return e.map((e=>{if(e)return Array.isArray(e)?bl(e):"object"==typeof e?"logContext"in e?e.logContext:void 0:e}))}function kl(e){return{all:e=e||new Map,on:function(t,i){var n=e.get(t);n?n.push(i):e.set(t,[i])},off:function(t,i){var n=e.get(t);n&&(i?n.splice(n.indexOf(i)>>>0,1):e.set(t,[]))},emit:function(t,i){var n=e.get(t);n&&n.slice().map((function(e){e(i)})),(n=e.get("*"))&&n.slice().map((function(e){e(t,i)}))}}}yl.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry((e=>{e()})),(Wd=Gd||(Gd={}))[Wd.IDLE=0]="IDLE",Wd[Wd.RUNNING=1]="RUNNING",Wd[Wd.SKIPPED=2]="SKIPPED",Wd[Wd.SUCCESS=3]="SUCCESS",Wd[Wd.FAILED=4]="FAILED",Er.EventEmitter,Er.EventEmitter;const Tl=Symbol.for("@ts-pattern/matcher"),Sl=Symbol.for("@ts-pattern/isVariadic"),Cl="@ts-pattern/anonymous-select-key",wl=e=>Boolean(e&&"object"==typeof e),El=e=>e&&!!e[Tl],_l=(e,t,i)=>{if(El(e)){const n=e[Tl](),{matched:s,selections:r}=n.match(t);return s&&r&&Object.keys(r).forEach((e=>i(e,r[e]))),s}if(wl(e)){if(!wl(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=[],s=[],r=[];for(const t of e.keys()){const i=e[t];El(i)&&i[Sl]?r.push(i):r.length?s.push(i):n.push(i)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(t.length<n.length+s.length)return!1;const e=t.slice(0,n.length),o=0===s.length?[]:t.slice(-s.length),a=t.slice(n.length,0===s.length?1/0:-s.length);return n.every(((t,n)=>_l(t,e[n],i)))&&s.every(((e,t)=>_l(e,o[t],i)))&&(0===r.length||_l(r[0],a,i))}return e.length===t.length&&e.every(((e,n)=>_l(e,t[n],i)))}return Reflect.ownKeys(e).every((n=>{const s=e[n];return(n in t||El(r=s)&&"optional"===r[Tl]().matcherType)&&_l(s,t[n],i);var r}))}return Object.is(t,e)},Pl=e=>{var t,i,n;return wl(e)?El(e)?null!=(t=null==(i=(n=e[Tl]()).getSelectionKeys)?void 0:i.call(n))?t:[]:Array.isArray(e)?Rl(e,Pl):Rl(Object.values(e),Pl):[]},Rl=(e,t)=>e.reduce(((e,i)=>e.concat(t(i))),[]);function xl(e){return Object.assign(e,{optional:()=>Il(e),and:t=>Dl(e,t),or:t=>Ml(e,t),select:t=>void 0===t?Ul(e):Ul(t,e)})}function Ol(e){return Object.assign((t=e,Object.assign(t,{[Symbol.iterator](){let e=0;const i=[{value:Object.assign(t,{[Sl]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var t;return null!=(t=i[e++])?t:i.at(-1)}}}})),{optional:()=>Ol(Il(e)),select:t=>Ol(void 0===t?Ul(e):Ul(t,e))});var t}function Il(e){return xl({[Tl]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return void 0===t?(Pl(e).forEach((e=>n(e,void 0))),{matched:!0,selections:i}):{matched:_l(e,t,n),selections:i}},getSelectionKeys:()=>Pl(e),matcherType:"optional"})})}const Al=(e,t)=>{for(const i of e)if(!t(i))return!1;return!0},Nl=(e,t)=>{for(const[i,n]of e.entries())if(!t(n,i))return!1;return!0};function Dl(...e){return xl({[Tl]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return{matched:e.every((e=>_l(e,t,n))),selections:i}},getSelectionKeys:()=>Rl(e,Pl),matcherType:"and"})})}function Ml(...e){return xl({[Tl]:()=>({match:t=>{let i={};const n=(e,t)=>{i[e]=t};return Rl(e,Pl).forEach((e=>n(e,void 0))),{matched:e.some((e=>_l(e,t,n))),selections:i}},getSelectionKeys:()=>Rl(e,Pl),matcherType:"or"})})}function Ll(e){return{[Tl]:()=>({match:t=>({matched:Boolean(e(t))})})}}function Ul(...e){const t="string"==typeof e[0]?e[0]:void 0,i=2===e.length?e[1]:"string"==typeof e[0]?void 0:e[0];return xl({[Tl]:()=>({match:e=>{let n={[null!=t?t:Cl]:e};return{matched:void 0===i||_l(i,e,((e,t)=>{n[e]=t})),selections:n}},getSelectionKeys:()=>[null!=t?t:Cl].concat(void 0===i?[]:Pl(i))})})}function jl(e){return"number"==typeof e}function Fl(e){return"string"==typeof e}function $l(e){return"bigint"==typeof e}const Bl=xl(Ll((function(e){return!0}))),Vl=Bl,ql=e=>Object.assign(xl(e),{startsWith:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.startsWith(i))))));var i},endsWith:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.endsWith(i))))));var i},minLength:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.length>=i)))));var i},length:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.length===i)))));var i},maxLength:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.length<=i)))));var i},includes:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&e.includes(i))))));var i},regex:t=>{return ql(Dl(e,(i=t,Ll((e=>Fl(e)&&Boolean(e.match(i)))))));var i}}),zl=ql(Ll(Fl)),Kl=e=>Object.assign(xl(e),{between:(t,i)=>{return Kl(Dl(e,(n=t,s=i,Ll((e=>jl(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Kl(Dl(e,(i=t,Ll((e=>jl(e)&&e<i)))));var i},gt:t=>{return Kl(Dl(e,(i=t,Ll((e=>jl(e)&&e>i)))));var i},lte:t=>{return Kl(Dl(e,(i=t,Ll((e=>jl(e)&&e<=i)))));var i},gte:t=>{return Kl(Dl(e,(i=t,Ll((e=>jl(e)&&e>=i)))));var i},int:()=>Kl(Dl(e,Ll((e=>jl(e)&&Number.isInteger(e))))),finite:()=>Kl(Dl(e,Ll((e=>jl(e)&&Number.isFinite(e))))),positive:()=>Kl(Dl(e,Ll((e=>jl(e)&&e>0)))),negative:()=>Kl(Dl(e,Ll((e=>jl(e)&&e<0))))}),Zl=Kl(Ll(jl)),Hl=e=>Object.assign(xl(e),{between:(t,i)=>{return Hl(Dl(e,(n=t,s=i,Ll((e=>$l(e)&&n<=e&&s>=e)))));var n,s},lt:t=>{return Hl(Dl(e,(i=t,Ll((e=>$l(e)&&e<i)))));var i},gt:t=>{return Hl(Dl(e,(i=t,Ll((e=>$l(e)&&e>i)))));var i},lte:t=>{return Hl(Dl(e,(i=t,Ll((e=>$l(e)&&e<=i)))));var i},gte:t=>{return Hl(Dl(e,(i=t,Ll((e=>$l(e)&&e>=i)))));var i},positive:()=>Hl(Dl(e,Ll((e=>$l(e)&&e>0)))),negative:()=>Hl(Dl(e,Ll((e=>$l(e)&&e<0))))}),Gl=Hl(Ll($l)),Wl=xl(Ll((function(e){return"boolean"==typeof e}))),Jl=xl(Ll((function(e){return"symbol"==typeof e}))),Yl=xl(Ll((function(e){return null==e}))),Ql=xl(Ll((function(e){return null!=e})));var Xl={__proto__:null,matcher:Tl,optional:Il,array:function(...e){return Ol({[Tl]:()=>({match:t=>{if(!Array.isArray(t))return{matched:!1};if(0===e.length)return{matched:!0};const i=e[0];let n={};if(0===t.length)return Pl(i).forEach((e=>{n[e]=[]})),{matched:!0,selections:n};const s=(e,t)=>{n[e]=(n[e]||[]).concat([t])};return{matched:t.every((e=>_l(i,e,s))),selections:n}},getSelectionKeys:()=>0===e.length?[]:Pl(e[0])})})},set:function(...e){return xl({[Tl]:()=>({match:t=>{if(!(t instanceof Set))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};if(0===e.length)return{matched:!0};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])},s=e[0];return{matched:Al(t,(e=>_l(s,e,n))),selections:i}},getSelectionKeys:()=>0===e.length?[]:Pl(e[0])})})},map:function(...e){return xl({[Tl]:()=>({match:t=>{if(!(t instanceof Map))return{matched:!1};let i={};if(0===t.size)return{matched:!0,selections:i};const n=(e,t)=>{i[e]=(i[e]||[]).concat([t])};if(0===e.length)return{matched:!0};var s;if(1===e.length)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${null==(s=e[0])?void 0:s.toString()}`);const[r,o]=e;return{matched:Nl(t,((e,t)=>{const i=_l(r,t,n),s=_l(o,e,n);return i&&s})),selections:i}},getSelectionKeys:()=>0===e.length?[]:[...Pl(e[0]),...Pl(e[1])]})})},intersection:Dl,union:Ml,not:function(e){return xl({[Tl]:()=>({match:t=>({matched:!_l(e,t,(()=>{}))}),getSelectionKeys:()=>[],matcherType:"not"})})},when:Ll,select:Ul,any:Bl,_:Vl,string:zl,number:Zl,bigint:Gl,boolean:Wl,symbol:Jl,nullish:Yl,nonNullable:Ql,instanceOf:function(e){return xl(Ll((t=e,e=>e instanceof t)));var t},shape:function(e){return xl(Ll(function(...e){if(1===e.length){const[t]=e;return e=>_l(t,e,(()=>{}))}if(2===e.length){const[t,i]=e;return _l(t,i,(()=>{}))}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${e.length}.`)}(e)))}};let eu=class extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch(i){t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}};const tu={matched:!1,value:void 0};function iu(e){return new nu(e,tu)}let nu=class e{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...t){if(this.state.matched)return this;const i=t[t.length-1],n=[t[0]];let s;3===t.length&&"function"==typeof t[1]?s=t[1]:t.length>2&&n.push(...t.slice(1,t.length-1));let r=!1,o={};const a=(e,t)=>{r=!0,o[e]=t},c=!n.some((e=>_l(e,this.input,a)))||s&&!Boolean(s(this.input))?tu:{matched:!0,value:i(r?Cl in o?o[Cl]:o:this.input,this.input)};return new e(this.input,c)}when(t,i){if(this.state.matched)return this;const n=Boolean(t(this.input));return new e(this.input,n?{matched:!0,value:i(this.input,this.input)}:tu)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=su){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function su(e){throw new eu(e)}class ru{constructor(e={}){this.currentState=It.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=kl(),this.apiBaseUrl=e.apiBaseUrl||"/api",this.token=e.token}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async connect(e={}){if(this.token=e.token??this.token??new URLSearchParams(window.location.search).get("token")??void 0,!this.token)return console.error("No token found"),void this.emitter.emit("error",{session:this,error:new Error("No session token provided")});await this.requestMicrophone();try{this.room=new yl({adaptiveStream:!0,dynacast:!0}),this.room.on(Ko.LocalTrackUnpublished,(e=>{console.log("Local track unpublished",e.source),e.source===ba.Source.ScreenShare&&(this.screenStream=void 0)})),this.room.on(Ko.Disconnected,(()=>{console.log("LiveKit room disconnected"),this.disconnect()})),this.room.on(Ko.ParticipantDisconnected,(()=>{this.disconnect()})),this.room.on(Ko.TrackSubscribed,((e,t,i)=>{if("audio"===e.kind&&e.attach(),e.source===ba.Source.Microphone&&i.identity.includes("agent-")){const t=e.mediaStream;if(!t)return void console.error("No media stream available for assistant track");const i=new AudioContext,n=i.createAnalyser();i.createMediaStreamSource(t).connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"ASSISTANT"),this.assistantAudioContext=i}})),this.room.on(Ko.ParticipantAttributesChanged,(e=>{if(!e["lk.agent.state"])return;if(this.currentState===It.RESEARCHING||this.currentState===It.PAUSED)return;const t=iu(e["lk.agent.state"]).with("listening",(()=>It.USER_SPEAKING)).with("speaking",(()=>It.AGENT_SPEAKING)).with("thinking",(()=>It.AGENT_SPEAKING)).otherwise((()=>{}));t&&this.setState(t)})),this.room.on(Ko.DataReceived,(async e=>{try{const t=JSON.parse((new TextDecoder).decode(e));iu(t.status||t.request).with("using_tool",(()=>{const e=this.currentState;this.currentState=It.RESEARCHING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("using_tool_ended",(()=>{const e=this.currentState;this.currentState=It.AGENT_SPEAKING,this.emitter.emit("stateChanged",{session:this,newState:this.currentState,oldState:e})})).with("share_screen",(()=>{this.shareScreen()})).with("prompt_user",(()=>{this.promptContinue()})).with("capture_page_html",(()=>{this.emitter.emit("capturePageHTML",{session:this})})).otherwise((()=>{console.warn("Unknown data received:",t)}))}catch(t){console.error("Error parsing data:",t)}}));const e=`${this.apiBaseUrl}/join-token?token=${this.token}`,t=await fetch(e).then((e=>e.json()));if(await this.room.connect(t.url,t.token),this.microphoneStream){const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:ba.Source.Microphone})}}catch(t){throw console.error("Failed to connect to LiveKit:",t),this.disconnect(),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))}),t}}disconnect(){this.room&&this.room.disconnect(!0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach((e=>e.stop())),this.setState(It.READY)}setState(e){if(e===this.currentState)return;const t=this.currentState;this.currentState=e,this.emitter.emit("stateChanged",{session:this,newState:e,oldState:t})}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),n=t.createMediaStreamSource(e),s=t.createGain();s.gain.value=1.5,n.connect(s),s.connect(i),i.fftSize=2048;const r=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,r,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{session:this});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream)return void console.warn("Failed to share screen");await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{session:this,error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){this.room&&(this.setState(It.PAUSED),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!1))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!1)),this.screenStream?.track?.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){this.room&&(this.setState(It.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach((e=>{e.handleUnmuted(),e.track?.mediaStream?.getTracks().forEach((e=>e.enabled=!0))})),this.microphoneStream?.getTracks().forEach((e=>e.enabled=!0)),this.screenStream?.track?.unmute())}async promptContinue(){await this.room.localParticipant.publishData((new TextEncoder).encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const n=t.reduce(((e,t)=>e+t),0)/t.length,s=Math.max(.01,Math.min(1,n/128));"USER"===i&&this.currentState===It.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:s}):"ASSISTANT"===i&&this.currentState===It.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:s}),setTimeout((()=>this.analyzeAudio(e,t,i)),50)}async sendHTML(e){if(this.room)try{const t={type:"page_content",html:e,timestamp:(new Date).toISOString()},i=JSON.stringify(t),n=(new TextEncoder).encode(i);await this.room.localParticipant.publishData(n,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{session:this,error:t instanceof Error?t:new Error(String(t))})}else console.log("Cannot send HTML: Not connected to LiveKit room")}}const ou=Object.freeze(Object.defineProperty({__proto__:null,ObiSession:ru},Symbol.toStringTag,{value:"Module"}));class au{constructor(e={}){this.state=It.READY,this.emitter=kl(),this.voiceEnabled=!1,this.screenCaptureEnabled=!1,this.config=xt.parse(e),this.config.debug&&console.log("ObiSDK initialized with config:",this.config)}async init(){try{this.config.enableVoice&&await this.initVoice(),this.config.enableScreenCapture&&await this.initScreenCapture(),this.setState(It.READY),this.emitter.emit(Ot.READY),this.config.debug&&console.log("ObiSDK ready")}catch(e){const t={code:"init_failed",message:"Failed to initialize SDK",details:e};this.handleError(t)}}async initVoice(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getUserMedia)throw new Error("Voice recording not supported in this browser");try{await window.navigator.mediaDevices.getUserMedia({audio:!0}),this.voiceEnabled=!0,this.config.debug&&console.log("Voice capabilities initialized")}catch(e){throw new Error(`Microphone access denied: ${e}`)}}async initScreenCapture(){if(!window.navigator.mediaDevices||!window.navigator.mediaDevices.getDisplayMedia)throw new Error("Screen capture not supported in this browser");this.screenCaptureEnabled=!0,this.config.debug&&console.log("Screen capture capabilities initialized")}setState(e){this.state=e,this.emitter.emit(Ot.STATE_CHANGE,e)}handleError(e){this.setState(It.ERROR),this.emitter.emit(Ot.ERROR,e),this.config.debug&&console.error("ObiSDK error:",e)}async startVoiceRecording(){if(this.voiceEnabled)try{this.setState(It.AGENT_SPEAKING),this.emitter.emit(Ot.VOICE_START),this.config.debug&&console.log("Voice recording started")}catch(e){this.handleError({code:"voice_start_failed",message:"Failed to start voice recording",details:e})}else this.handleError({code:"voice_disabled",message:"Voice recording is not enabled or available"})}async stopVoiceRecording(){if(this.state===It.READY)return{transcript:void 0};try{const e={transcript:"Sample transcript"};return this.setState(It.READY),this.emitter.emit(Ot.VOICE_STOP,e),this.config.debug&&console.log("Voice recording stopped:",e),e}catch(e){return this.handleError({code:"voice_stop_failed",message:"Failed to stop voice recording",details:e}),{transcript:void 0}}}async startScreenCapture(){if(this.screenCaptureEnabled)try{this.setState(It.AGENT_SPEAKING),this.emitter.emit(Ot.SCREEN_CAPTURE_START),this.config.debug&&console.log("Screen capture started")}catch(e){this.handleError({code:"screen_capture_start_failed",message:"Failed to start screen capture",details:e})}else this.handleError({code:"screen_capture_disabled",message:"Screen capture is not enabled or available"})}async stopScreenCapture(){if(this.state===It.READY)return{screenshot:void 0};try{const e={screenshot:"data:image/png;base64,..."};return this.setState(It.READY),this.emitter.emit(Ot.SCREEN_CAPTURE_STOP,e),this.config.debug&&console.log("Screen capture stopped"),e}catch(e){return this.handleError({code:"screen_capture_stop_failed",message:"Failed to stop screen capture",details:e}),{screenshot:void 0}}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getState(){return this.state}dispose(){this.emitter.all.clear(),this.config.debug&&console.log("ObiSDK disposed")}}const cu=globalThis,du=cu.ShadowRoot&&(void 0===cu.ShadyCSS||cu.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,lu=Symbol(),uu=new WeakMap;let hu=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==lu)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(du&&void 0===e){const i=void 0!==t&&1===t.length;i&&(e=uu.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&uu.set(t,e))}return e}toString(){return this.cssText}};const pu=(e,...t)=>{const i=1===e.length?e[0]:t.reduce(((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1]),e[0]);return new hu(i,e,lu)},mu=du?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new hu("string"==typeof e?e:e+"",void 0,lu))(t)})(e):e,{is:gu,defineProperty:fu,getOwnPropertyDescriptor:vu,getOwnPropertyNames:yu,getOwnPropertySymbols:bu,getPrototypeOf:ku}=Object,Tu=globalThis,Su=Tu.trustedTypes,Cu=Su?Su.emptyScript:"",wu=Tu.reactiveElementPolyfillSupport,Eu=(e,t)=>e,_u={toAttribute(e,t){switch(t){case Boolean:e=e?Cu:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(n){i=null}}return i}},Pu=(e,t)=>!gu(e,t),Ru={attribute:!0,type:String,converter:_u,reflect:!1,useDefault:!1,hasChanged:Pu};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Tu.litPropertyMetadata??(Tu.litPropertyMetadata=new WeakMap);let xu=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Ru){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&fu(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:s}=vu(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const r=n?.call(this);s?.call(this,t),this.requestUpdate(e,r,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Ru}static _$Ei(){if(this.hasOwnProperty(Eu("elementProperties")))return;const e=ku(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Eu("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Eu("properties"))){const e=this.properties,t=[...yu(e),...bu(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const e=this._$Eu(t,i);void 0!==e&&this._$Eh.set(e,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(mu(e))}else void 0!==e&&t.push(mu(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??(this._$EO=new Set)).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(du)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const i of t){const t=document.createElement("style"),n=cu.litNonce;void 0!==n&&t.setAttribute("nonce",n),t.textContent=i.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const s=(void 0!==i.converter?.toAttribute?i.converter:_u).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(n):this.setAttribute(n,s),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:_u;this._$Em=n,this[n]=s.fromAttribute(t,e.type)??this._$Ej?.get(n)??null,this._$Em=null}}requestUpdate(e,t,i){if(void 0!==e){const n=this.constructor,s=this[e];if(i??(i=n.getPropertyOptions(e)),!((i.hasChanged??Pu)(s,t)||i.useDefault&&i.reflect&&s===this._$Ej?.get(e)&&!this.hasAttribute(n._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:s},r){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,r??t??this[e]),!0!==s||void 0!==r)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach((e=>this._$ET(e,this[e])))),this._$EM()}updated(e){}firstUpdated(e){}};xu.elementStyles=[],xu.shadowRootOptions={mode:"open"},xu[Eu("elementProperties")]=new Map,xu[Eu("finalized")]=new Map,wu?.({ReactiveElement:xu}),(Tu.reactiveElementVersions??(Tu.reactiveElementVersions=[])).push("2.1.0");const Ou=globalThis,Iu=Ou.trustedTypes,Au=Iu?Iu.createPolicy("lit-html",{createHTML:e=>e}):void 0,Nu="$lit$",Du=`lit$${Math.random().toFixed(9).slice(2)}$`,Mu="?"+Du,Lu=`<${Mu}>`,Uu=document,ju=()=>Uu.createComment(""),Fu=e=>null===e||"object"!=typeof e&&"function"!=typeof e,$u=Array.isArray,Bu="[ \t\n\f\r]",Vu=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,qu=/-->/g,zu=/>/g,Ku=RegExp(`>|${Bu}(?:([^\\s"'>=/]+)(${Bu}*=${Bu}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),Zu=/'/g,Hu=/"/g,Gu=/^(?:script|style|textarea|title)$/i,Wu=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),Ju=Wu(1),Yu=Wu(2),Qu=Symbol.for("lit-noChange"),Xu=Symbol.for("lit-nothing"),eh=new WeakMap,th=Uu.createTreeWalker(Uu,129);function ih(e,t){if(!$u(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==Au?Au.createHTML(t):t}let nh=class e{constructor({strings:t,_$litType$:i},n){let s;this.parts=[];let r=0,o=0;const a=t.length-1,c=this.parts,[d,l]=((e,t)=>{const i=e.length-1,n=[];let s,r=2===t?"<svg>":3===t?"<math>":"",o=Vu;for(let a=0;a<i;a++){const t=e[a];let i,c,d=-1,l=0;for(;l<t.length&&(o.lastIndex=l,c=o.exec(t),null!==c);)l=o.lastIndex,o===Vu?"!--"===c[1]?o=qu:void 0!==c[1]?o=zu:void 0!==c[2]?(Gu.test(c[2])&&(s=RegExp("</"+c[2],"g")),o=Ku):void 0!==c[3]&&(o=Ku):o===Ku?">"===c[0]?(o=s??Vu,d=-1):void 0===c[1]?d=-2:(d=o.lastIndex-c[2].length,i=c[1],o=void 0===c[3]?Ku:'"'===c[3]?Hu:Zu):o===Hu||o===Zu?o=Ku:o===qu||o===zu?o=Vu:(o=Ku,s=void 0);const u=o===Ku&&e[a+1].startsWith("/>")?" ":"";r+=o===Vu?t+Lu:d>=0?(n.push(i),t.slice(0,d)+Nu+t.slice(d)+Du+u):t+Du+(-2===d?a:u)}return[ih(e,r+(e[i]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),n]})(t,i);if(this.el=e.createElement(d,n),th.currentNode=this.el.content,2===i||3===i){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(s=th.nextNode())&&c.length<a;){if(1===s.nodeType){if(s.hasAttributes())for(const e of s.getAttributeNames())if(e.endsWith(Nu)){const t=l[o++],i=s.getAttribute(e).split(Du),n=/([.?@])?(.*)/.exec(t);c.push({type:1,index:r,name:n[2],strings:i,ctor:"."===n[1]?ch:"?"===n[1]?dh:"@"===n[1]?lh:ah}),s.removeAttribute(e)}else e.startsWith(Du)&&(c.push({type:6,index:r}),s.removeAttribute(e));if(Gu.test(s.tagName)){const e=s.textContent.split(Du),t=e.length-1;if(t>0){s.textContent=Iu?Iu.emptyScript:"";for(let i=0;i<t;i++)s.append(e[i],ju()),th.nextNode(),c.push({type:2,index:++r});s.append(e[t],ju())}}}else if(8===s.nodeType)if(s.data===Mu)c.push({type:2,index:r});else{let e=-1;for(;-1!==(e=s.data.indexOf(Du,e+1));)c.push({type:7,index:r}),e+=Du.length-1}r++}}static createElement(e,t){const i=Uu.createElement("template");return i.innerHTML=e,i}};function sh(e,t,i=e,n){if(t===Qu)return t;let s=void 0!==n?i._$Co?.[n]:i._$Cl;const r=Fu(t)?void 0:t._$litDirective$;return s?.constructor!==r&&(s?._$AO?.(!1),void 0===r?s=void 0:(s=new r(e),s._$AT(e,i,n)),void 0!==n?(i._$Co??(i._$Co=[]))[n]=s:i._$Cl=s),void 0!==s&&(t=sh(e,s._$AS(e,t.values),s,n)),t}let rh=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,n=(e?.creationScope??Uu).importNode(t,!0);th.currentNode=n;let s=th.nextNode(),r=0,o=0,a=i[0];for(;void 0!==a;){if(r===a.index){let t;2===a.type?t=new oh(s,s.nextSibling,this,e):1===a.type?t=new a.ctor(s,a.name,a.strings,this,e):6===a.type&&(t=new uh(s,this,e)),this._$AV.push(t),a=i[++o]}r!==a?.index&&(s=th.nextNode(),r++)}return th.currentNode=Uu,n}p(e){let t=0;for(const i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}},oh=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,n){this.type=2,this._$AH=Xu,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=sh(this,e,t),Fu(e)?e===Xu||null==e||""===e?(this._$AH!==Xu&&this._$AR(),this._$AH=Xu):e!==this._$AH&&e!==Qu&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>$u(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==Xu&&Fu(this._$AH)?this._$AA.nextSibling.data=e:this.T(Uu.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=nh.createElement(ih(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new rh(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=eh.get(e.strings);return void 0===t&&eh.set(e.strings,t=new nh(e)),t}k(t){$u(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let n,s=0;for(const r of t)s===i.length?i.push(n=new e(this.O(ju()),this.O(ju()),this,this.options)):n=i[s],n._$AI(r),s++;s<i.length&&(this._$AR(n&&n._$AB.nextSibling,s),i.length=s)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e&&e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}};class ah{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,n,s){this.type=1,this._$AH=Xu,this._$AN=void 0,this.element=e,this.name=t,this._$AM=n,this.options=s,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Xu}_$AI(e,t=this,i,n){const s=this.strings;let r=!1;if(void 0===s)e=sh(this,e,t,0),r=!Fu(e)||e!==this._$AH&&e!==Qu,r&&(this._$AH=e);else{const n=e;let o,a;for(e=s[0],o=0;o<s.length-1;o++)a=sh(this,n[i+o],t,o),a===Qu&&(a=this._$AH[o]),r||(r=!Fu(a)||a!==this._$AH[o]),a===Xu?e=Xu:e!==Xu&&(e+=(a??"")+s[o+1]),this._$AH[o]=a}r&&!n&&this.j(e)}j(e){e===Xu?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}let ch=class extends ah{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Xu?void 0:e}},dh=class extends ah{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Xu)}},lh=class extends ah{constructor(e,t,i,n,s){super(e,t,i,n,s),this.type=5}_$AI(e,t=this){if((e=sh(this,e,t,0)??Xu)===Qu)return;const i=this._$AH,n=e===Xu&&i!==Xu||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==Xu&&(i===Xu||n);n&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},uh=class{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){sh(this,e)}};const hh=Ou.litHtmlPolyfillSupport;hh?.(nh,oh),(Ou.litHtmlVersions??(Ou.litHtmlVersions=[])).push("3.3.0");const ph=globalThis;let mh=class extends xu{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,i)=>{const n=i?.renderBefore??t;let s=n._$litPart$;if(void 0===s){const e=i?.renderBefore??null;n._$litPart$=s=new oh(t.insertBefore(ju(),e),e,void 0,i??{})}return s._$AI(e),s})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Qu}};mh._$litElement$=!0,mh.finalized=!0,ph.litElementHydrateSupport?.({LitElement:mh});const gh=ph.litElementPolyfillSupport;gh?.({LitElement:mh}),(ph.litElementVersions??(ph.litElementVersions=[])).push("4.2.0");const fh={attribute:!0,type:String,converter:_u,reflect:!1,hasChanged:Pu},vh=(e=fh,t,i)=>{const{kind:n,metadata:s}=i;let r=globalThis.litPropertyMetadata.get(s);if(void 0===r&&globalThis.litPropertyMetadata.set(s,r=new Map),"setter"===n&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),"accessor"===n){const{name:n}=i;return{set(i){const s=t.get.call(this);t.set.call(this,i),this.requestUpdate(n,s,e)},init(t){return void 0!==t&&this.C(n,void 0,e,t),t}}}if("setter"===n){const{name:n}=i;return function(i){const s=this[n];t.call(this,i),this.requestUpdate(n,s,e)}}throw Error("Unsupported decorator location: "+n)};function yh(e){return(t,i)=>"object"==typeof i?vh(e,t,i):((e,t,i)=>{const n=t.hasOwnProperty(i);return t.constructor.createProperty(i,e),n?Object.getOwnPropertyDescriptor(t,i):void 0})(e,t,i)}function bh(e){return yh({...e,state:!0,attribute:!1})}var kh=Object.defineProperty,Th=Object.getOwnPropertyDescriptor,Sh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Th(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&kh(t,i,r),r};class Ch extends mh{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return Ju`
2
2
  <button
3
3
  id="obi-nav-${this.id}"
4
4
  class=${this.isSpecial?"special":""}
@@ -8,7 +8,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
8
8
  >
9
9
  <slot></slot>
10
10
  </button>
11
- `}}Sh.styles=hu`
11
+ `}}Ch.styles=pu`
12
12
  :host {
13
13
  display: block;
14
14
  }
@@ -60,7 +60,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
60
60
  width: 18px;
61
61
  height: 18px;
62
62
  }
63
- `,Th([vh({type:String})],Sh.prototype,"id",2),Th([vh({type:Boolean})],Sh.prototype,"isActive",2),Th([vh({type:Boolean})],Sh.prototype,"isSpecial",2),Th([vh({type:Function})],Sh.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",Sh);const Ch=Object.freeze(Object.defineProperty({__proto__:null,NavIcon:Sh},Symbol.toStringTag,{value:"Module"})),wh=e=>Wu`
63
+ `,Sh([yh({type:String})],Ch.prototype,"id",2),Sh([yh({type:Boolean})],Ch.prototype,"isActive",2),Sh([yh({type:Boolean})],Ch.prototype,"isSpecial",2),Sh([yh({type:Function})],Ch.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",Ch);const wh=Object.freeze(Object.defineProperty({__proto__:null,NavIcon:Ch},Symbol.toStringTag,{value:"Module"})),Eh=e=>Ju`
64
64
  <svg
65
65
  xmlns="http://www.w3.org/2000/svg"
66
66
  width="24"
@@ -76,31 +76,31 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
76
76
  >
77
77
  ${e}
78
78
  </svg>
79
- `,Eh=wh(Ju`
79
+ `,_h=Eh(Yu`
80
80
  <rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>
81
- `),_h=wh(Ju`<polygon points="6 3 20 12 6 21 6 3"/>`),Ph=wh(Ju`
81
+ `),Ph=Eh(Yu`<polygon points="6 3 20 12 6 21 6 3"/>`),Rh=Eh(Yu`
82
82
  <path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>
83
- `),Rh=wh(Ju`
83
+ `),xh=Eh(Yu`
84
84
  <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
85
- `),xh=wh(Ju`
85
+ `),Oh=Eh(Yu`
86
86
  <path d="M12 7v14" />
87
87
  <path
88
88
  d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"
89
89
  />
90
- `),Oh=Wu`
90
+ `),Ih=Ju`
91
91
  <img
92
92
  class="widget-icon"
93
93
  src="data:image/svg+xml;base64,${btoa('<?xml version="1.0" encoding="UTF-8"?>\n <svg width="32" height="32" viewBox="0 0 32 34" fill="none" xmlns="http://www.w3.org/2000/svg">\n <g id="obi-icon">\n <g id="Subtract">\n <path d="M15.5845 9.29177L8.20527 5.00637L8.20527 13.4502L15.5845 17.7356L15.5845 9.29177Z" fill="white" />\n <path d="M15.5896 27.7146L8.21035 31.9994L8.21032 23.4698L15.5896 19.1843L15.5896 27.7146Z" fill="white" />\n <path d="M16.4104 27.7146L16.4104 19.1786L23.7897 23.4641L23.7897 32L16.4104 27.7146Z" fill="white" />\n <path d="M32 27.7142L24.6207 31.9996L24.6207 23.47L32 19.1846L32 27.7142Z" fill="white" />\n <path d="M24.2048 22.748L31.5911 18.4585L24.2845 14.2154L16.8983 18.5048L24.2048 22.748Z" fill="white" />\n <path d="M23.7948 5.01235L23.7948 13.4564L16.4156 17.7418L16.4156 9.29775L23.7948 5.01235Z" fill="white" />\n <path d="M16.0052 0L23.3865 4.2866L16.0003 8.57606L8.61897 4.28946L16.0052 0Z" fill="white" />\n <path d="M7.72042 14.2182L15.1017 18.5048L7.79445 22.7477L0.413699 18.4615L7.72042 14.2182Z" fill="white" />\n <path d="M7.37926 31.9997L7.37926 23.4638L0 19.1784L3.79636e-05 27.7143L7.37926 31.9997Z" fill="white" />\n </g>\n </g>\n </svg>')}"
94
94
  alt="Obi Icon"
95
95
  />
96
- `;var Ih=Object.defineProperty,Ah=Object.getOwnPropertyDescriptor,Nh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Ah(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Ih(t,i,r),r};class Dh extends ph{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=Ot.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return Wu`
97
- ${this.isActive?Wu`
96
+ `;var Ah=Object.defineProperty,Nh=Object.getOwnPropertyDescriptor,Dh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Nh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Ah(t,i,r),r};class Mh extends mh{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=It.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return Ju`
97
+ ${this.isActive?Ju`
98
98
  <obi-nav-icon
99
99
  id="pause"
100
- ?isActive=${this.currentState===Ot.PAUSED}
101
- @click=${()=>this.handleIconClick("pause",this.currentState!==Ot.PAUSED)}
100
+ ?isActive=${this.currentState===It.PAUSED}
101
+ @click=${()=>this.handleIconClick("pause",this.currentState!==It.PAUSED)}
102
102
  >
103
- ${this.currentState===Ot.PAUSED?_h:Eh}
103
+ ${this.currentState===It.PAUSED?Ph:_h}
104
104
  </obi-nav-icon>
105
105
  <obi-nav-icon
106
106
  id="activate"
@@ -108,17 +108,17 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
108
108
  ?isSpecial=${!0}
109
109
  @click=${()=>this.handleIconClick("activate",!this.isActive)}
110
110
  >
111
- ${this.isActive?Rh:Ph}
111
+ ${this.isActive?xh:Rh}
112
112
  </obi-nav-icon>
113
- `:Wu`
113
+ `:Ju`
114
114
  <obi-nav-icon
115
115
  id="experiences"
116
116
  @click=${()=>this.handleIconClick("experiences",!0)}
117
117
  >
118
- ${xh}
118
+ ${Oh}
119
119
  </obi-nav-icon>
120
120
  `}
121
- `}}Dh.styles=hu`
121
+ `}}Mh.styles=pu`
122
122
  :host {
123
123
  display: flex;
124
124
  position: absolute;
@@ -142,13 +142,13 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
142
142
  bottom: auto;
143
143
  flex-direction: column;
144
144
  }
145
- `,Nh([vh({type:Boolean})],Dh.prototype,"isActive",2),Nh([vh({type:Boolean})],Dh.prototype,"isScreenActive",2),Nh([vh({type:Object})],Dh.prototype,"position",2),Nh([vh({type:String})],Dh.prototype,"currentState",2),Nh([vh({type:String})],Dh.prototype,"direction",2),Nh([vh({type:Function})],Dh.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",Dh);const Mh=Object.freeze(Object.defineProperty({__proto__:null,NavigationBar:Dh},Symbol.toStringTag,{value:"Module"}));var Lh=Object.defineProperty,Uh=Object.getOwnPropertyDescriptor,jh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?Uh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Lh(t,i,r),r};class Fh extends ph{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return Wu`
145
+ `,Dh([yh({type:Boolean})],Mh.prototype,"isActive",2),Dh([yh({type:Boolean})],Mh.prototype,"isScreenActive",2),Dh([yh({type:Object})],Mh.prototype,"position",2),Dh([yh({type:String})],Mh.prototype,"currentState",2),Dh([yh({type:String})],Mh.prototype,"direction",2),Dh([yh({type:Function})],Mh.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",Mh);const Lh=Object.freeze(Object.defineProperty({__proto__:null,NavigationBar:Mh},Symbol.toStringTag,{value:"Module"}));var Uh=Object.defineProperty,jh=Object.getOwnPropertyDescriptor,Fh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?jh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Uh(t,i,r),r};class $h extends mh{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return Ju`
146
146
  <div class="course-container" @click=${this.handleClick}>
147
147
  <img src=${this.imageSrc} alt="Course Preview" class="course-image" />
148
148
  <h2 class="course-title">${this.name}</h2>
149
- ${this.description?Wu`<p class="course-description">${this.description}</p>`:""}
149
+ ${this.description?Ju`<p class="course-description">${this.description}</p>`:""}
150
150
  </div>
151
- `}}Fh.styles=hu`
151
+ `}}$h.styles=pu`
152
152
  :host {
153
153
  display: block;
154
154
  }
@@ -193,9 +193,9 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
193
193
  color: #71717a;
194
194
  margin: 0;
195
195
  }
196
- `,jh([vh({type:String})],Fh.prototype,"id",2),jh([vh({type:String})],Fh.prototype,"name",2),jh([vh({type:String})],Fh.prototype,"description",2),jh([vh({type:String})],Fh.prototype,"imageSrc",2),jh([vh({type:Function})],Fh.prototype,"onSelect",2);class $h extends ph{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return Wu`<div class="loading">Loading...</div>`;if(this.error)return Wu`<div class="error">${this.error}</div>`;if(!this.courses||0===this.courses.length)return Wu`<div class="empty">No courses available</div>`;const e=1===this.courses.length?"grid-cols-1":2===this.courses.length?"grid-cols-2":"grid-cols-3";return Wu`
196
+ `,Fh([yh({type:String})],$h.prototype,"id",2),Fh([yh({type:String})],$h.prototype,"name",2),Fh([yh({type:String})],$h.prototype,"description",2),Fh([yh({type:String})],$h.prototype,"imageSrc",2),Fh([yh({type:Function})],$h.prototype,"onSelect",2);class Bh extends mh{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return Ju`<div class="loading">Loading...</div>`;if(this.error)return Ju`<div class="error">${this.error}</div>`;if(!this.courses||0===this.courses.length)return Ju`<div class="empty">No courses available</div>`;const e=1===this.courses.length?"grid-cols-1":2===this.courses.length?"grid-cols-2":"grid-cols-3";return Ju`
197
197
  <div class="course-grid ${e}">
198
- ${this.courses.map((e=>Wu`
198
+ ${this.courses.map((e=>Ju`
199
199
  <obi-course
200
200
  id=${e.id}
201
201
  name=${e.name}
@@ -205,7 +205,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
205
205
  ></obi-course>
206
206
  `))}
207
207
  </div>
208
- `}}$h.styles=hu`
208
+ `}}Bh.styles=pu`
209
209
  :host {
210
210
  display: block;
211
211
  }
@@ -240,7 +240,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
240
240
  .error {
241
241
  color: #ef4444;
242
242
  }
243
- `,jh([vh({type:Array})],$h.prototype,"courses",2),jh([vh({type:Boolean})],$h.prototype,"loading",2),jh([vh({type:String})],$h.prototype,"error",2),jh([vh({type:Function})],$h.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",Fh),customElements.get("obi-course-list")||customElements.define("obi-course-list",$h);const Bh=Object.freeze(Object.defineProperty({__proto__:null,Course:Fh,CourseList:$h},Symbol.toStringTag,{value:"Module"}));var Vh=Object.defineProperty,qh=Object.getOwnPropertyDescriptor,zh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?qh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&Vh(t,i,r),r};class Zh extends ph{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiBaseUrl="",this.apiKey=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const e=await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`),t=(await e.json()).map((e=>({id:e.uuid,name:e.onboarding_plan.name,description:e.onboarding_plan.description,imageSrc:e.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"}))).filter((e=>!!e.name));this.courses=[...t],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig?.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig?.apiBaseUrl&&(this.apiBaseUrl=window.obiWidgetConfig.apiBaseUrl),this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return Wu`
243
+ `,Fh([yh({type:Array})],Bh.prototype,"courses",2),Fh([yh({type:Boolean})],Bh.prototype,"loading",2),Fh([yh({type:String})],Bh.prototype,"error",2),Fh([yh({type:Function})],Bh.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",$h),customElements.get("obi-course-list")||customElements.define("obi-course-list",Bh);const Vh=Object.freeze(Object.defineProperty({__proto__:null,Course:$h,CourseList:Bh},Symbol.toStringTag,{value:"Module"}));var qh=Object.defineProperty,zh=Object.getOwnPropertyDescriptor,Kh=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?zh(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&qh(t,i,r),r};class Zh extends mh{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiBaseUrl="",this.apiKey=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const e=await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`),t=(await e.json()).map((e=>({id:e.uuid,name:e.onboarding_plan.name,description:e.onboarding_plan.description,imageSrc:e.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"}))).filter((e=>!!e.name));this.courses=[...t],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig?.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),this.apiBaseUrl=Rt,this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return Ju`
244
244
  <div class="backdrop" @click=${this.handleClose}></div>
245
245
  <div class="container">
246
246
  <button class="close-button" @click=${this.handleClose}>×</button>
@@ -256,7 +256,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
256
256
  @course-select=${this.handleCourseSelect}
257
257
  ></obi-course-list>
258
258
  </div>
259
- `}}Zh.styles=hu`
259
+ `}}Zh.styles=pu`
260
260
  :host {
261
261
  display: block;
262
262
  font-family: "Syne", sans-serif;
@@ -339,7 +339,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
339
339
  font-size: 24px;
340
340
  color: #6b7280;
341
341
  }
342
- `,zh([vh({type:Array})],Zh.prototype,"courses",2),zh([vh({type:Boolean})],Zh.prototype,"loading",2),zh([vh({type:String})],Zh.prototype,"error",2),zh([vh({type:String})],Zh.prototype,"apiBaseUrl",2),zh([vh({type:String})],Zh.prototype,"apiKey",2),zh([vh({type:Function})],Zh.prototype,"onCourseSelect",2),zh([vh({type:Function})],Zh.prototype,"onClose",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",Zh);const Hh=Object.freeze(Object.defineProperty({__proto__:null,CourseModal:Zh},Symbol.toStringTag,{value:"Module"}));class Kh{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}const Gh=(e,t)=>{const i=e._$AN;if(void 0===i)return!1;for(const n of i)n._$AO?.(t,!1),Gh(n,t);return!0},Wh=e=>{let t,i;do{if(void 0===(t=e._$AM))break;i=t._$AN,i.delete(e),e=t}while(0===i?.size)},Jh=e=>{for(let t;t=e._$AM;e=t){let i=t._$AN;if(void 0===i)t._$AN=i=new Set;else if(i.has(e))break;i.add(e),Xh(t)}};function Yh(e){void 0!==this._$AN?(Wh(this),this._$AM=e,Jh(this)):this._$AM=e}function Qh(e,t=!1,i=0){const n=this._$AH,s=this._$AN;if(void 0!==s&&0!==s.size)if(t)if(Array.isArray(n))for(let r=i;r<n.length;r++)Gh(n[r],!1),Wh(n[r]);else null!=n&&(Gh(n,!1),Wh(n));else Gh(this,e)}const Xh=e=>{2==e.type&&(e._$AP??(e._$AP=Qh),e._$AQ??(e._$AQ=Yh))};class ep extends Kh{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),Jh(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Gh(this,e),Wh(this))}setValue(e){if(void 0===this._$Ct.strings)this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}class tp{}const ip=new WeakMap,np=(sp=class extends ep{render(e){return Qu}update(e,[t]){const i=t!==this.G;return i&&void 0!==this.G&&this.rt(void 0),(i||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),Qu}rt(e){if(this.isConnected||(e=void 0),"function"==typeof this.G){const t=this.ht??globalThis;let i=ip.get(t);void 0===i&&(i=new WeakMap,ip.set(t,i)),void 0!==i.get(this.G)&&this.G.call(this.ht,void 0),i.set(this.G,e),void 0!==e&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return"function"==typeof this.G?ip.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}},(...e)=>({_$litDirective$:sp,values:e}));var sp,rp=Object.defineProperty,op=Object.getOwnPropertyDescriptor,ap=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?op(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&rp(t,i,r),r};class cp extends ph{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=new tp,this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const i=window.devicePixelRatio||1,n=e.clientWidth,s=e.clientHeight;e.width=n*i,e.height=s*i,t.scale(i,i),t.clearRect(0,0,n,s);const r=Math.max(1,(n-3*(this.barCount-1))/this.barCount),o=s/2,a=(this.volume.speaker,this.volume.volume),c=(this.volume.speaker,this.volume.spectrum);if(0===a)return;let d=[];if(c&&c.length>0){const e=c.length,t=Math.ceil(e/10);let i=[];for(let d=0;d<10;d++){const n=d*t,s=Math.min((d+1)*t,e);let r=0;for(let e=n;e<s;e++)r+=c[e]||0;i.push({region:d,startIdx:n,endIdx:s,energy:r})}i.sort(((e,t)=>t.energy-e.energy));const n=i.slice(0,3),s=Math.min(...n.map((e=>e.startIdx))),r=Math.max(...n.map((e=>e.endIdx)));if(r>s)for(let l=0;l<this.barCount;l++){const t=s+l/(this.barCount-1)*(r-s),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}else for(let l=0;l<this.barCount;l++){const t=l/(this.barCount-1)*(e/2),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}const o=Math.max(...d,1),a="USER"===this.volume.speaker?.7:.6;d=d.map(((e,t)=>{const i=e/o,n=a+t/(this.barCount-1)*.3;return Math.min(1,i*n)}))}else if("USER"!==this.volume.speaker)for(let l=0;l<this.barCount;l++){const e=.002*Date.now(),t=.3+.2*Math.sin(e+.7*l);d[l]=t}for(let l=0;l<this.barCount;l++){const e=d.length>0&&void 0!==d[l]?d[l]:a;"USER"===this.volume.speaker?t.fillStyle=`rgba(109, 40, 217, ${.5*e+.5})`:t.fillStyle=`rgba(255, 255, 255, ${.5*e+.5})`;const i=Math.max(2,.8*e*o),c=n-(this.barCount-l)*(r+3),u=r/2;t.beginPath(),t.moveTo(c+u,s/2-i),t.lineTo(c+r-u,s/2-i),t.quadraticCurveTo(c+r,s/2-i,c+r,s/2-i+u),t.lineTo(c+r,s/2),t.lineTo(c,s/2),t.lineTo(c,s/2-i+u),t.quadraticCurveTo(c,s/2-i,c+u,s/2-i),t.fill(),t.beginPath(),t.moveTo(c,s/2),t.lineTo(c+r,s/2),t.lineTo(c+r,s/2+i-u),t.quadraticCurveTo(c+r,s/2+i,c+r-u,s/2+i),t.lineTo(c+u,s/2+i),t.quadraticCurveTo(c,s/2+i,c,s/2+i-u),t.lineTo(c,s/2),t.fill()}}render(){return Wu` <canvas ${np(this.canvasRef)} width="52" height="52"></canvas> `}}cp.styles=hu`
342
+ `,Kh([yh({type:Array})],Zh.prototype,"courses",2),Kh([yh({type:Boolean})],Zh.prototype,"loading",2),Kh([yh({type:String})],Zh.prototype,"error",2),Kh([yh({type:String})],Zh.prototype,"apiBaseUrl",2),Kh([yh({type:String})],Zh.prototype,"apiKey",2),Kh([yh({type:Function})],Zh.prototype,"onCourseSelect",2),Kh([yh({type:Function})],Zh.prototype,"onClose",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",Zh);const Hh=Object.freeze(Object.defineProperty({__proto__:null,CourseModal:Zh},Symbol.toStringTag,{value:"Module"}));class Gh{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}const Wh=(e,t)=>{const i=e._$AN;if(void 0===i)return!1;for(const n of i)n._$AO?.(t,!1),Wh(n,t);return!0},Jh=e=>{let t,i;do{if(void 0===(t=e._$AM))break;i=t._$AN,i.delete(e),e=t}while(0===i?.size)},Yh=e=>{for(let t;t=e._$AM;e=t){let i=t._$AN;if(void 0===i)t._$AN=i=new Set;else if(i.has(e))break;i.add(e),ep(t)}};function Qh(e){void 0!==this._$AN?(Jh(this),this._$AM=e,Yh(this)):this._$AM=e}function Xh(e,t=!1,i=0){const n=this._$AH,s=this._$AN;if(void 0!==s&&0!==s.size)if(t)if(Array.isArray(n))for(let r=i;r<n.length;r++)Wh(n[r],!1),Jh(n[r]);else null!=n&&(Wh(n,!1),Jh(n));else Wh(this,e)}const ep=e=>{2==e.type&&(e._$AP??(e._$AP=Xh),e._$AQ??(e._$AQ=Qh))};class tp extends Gh{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),Yh(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Wh(this,e),Jh(this))}setValue(e){if(void 0===this._$Ct.strings)this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}class ip{}const np=new WeakMap,sp=(rp=class extends tp{render(e){return Xu}update(e,[t]){const i=t!==this.G;return i&&void 0!==this.G&&this.rt(void 0),(i||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),Xu}rt(e){if(this.isConnected||(e=void 0),"function"==typeof this.G){const t=this.ht??globalThis;let i=np.get(t);void 0===i&&(i=new WeakMap,np.set(t,i)),void 0!==i.get(this.G)&&this.G.call(this.ht,void 0),i.set(this.G,e),void 0!==e&&this.G.call(this.ht,e)}else this.G.value=e}get lt(){return"function"==typeof this.G?np.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}},(...e)=>({_$litDirective$:rp,values:e}));var rp,op=Object.defineProperty,ap=Object.getOwnPropertyDescriptor,cp=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?ap(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&op(t,i,r),r};class dp extends mh{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=new ip,this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const i=window.devicePixelRatio||1,n=e.clientWidth,s=e.clientHeight;e.width=n*i,e.height=s*i,t.scale(i,i),t.clearRect(0,0,n,s);const r=Math.max(1,(n-3*(this.barCount-1))/this.barCount),o=s/2,a=(this.volume.speaker,this.volume.volume),c=(this.volume.speaker,this.volume.spectrum);if(0===a)return;let d=[];if(c&&c.length>0){const e=c.length,t=Math.ceil(e/10);let i=[];for(let d=0;d<10;d++){const n=d*t,s=Math.min((d+1)*t,e);let r=0;for(let e=n;e<s;e++)r+=c[e]||0;i.push({region:d,startIdx:n,endIdx:s,energy:r})}i.sort(((e,t)=>t.energy-e.energy));const n=i.slice(0,3),s=Math.min(...n.map((e=>e.startIdx))),r=Math.max(...n.map((e=>e.endIdx)));if(r>s)for(let l=0;l<this.barCount;l++){const t=s+l/(this.barCount-1)*(r-s),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}else for(let l=0;l<this.barCount;l++){const t=l/(this.barCount-1)*(e/2),i=Math.min(e-1,Math.floor(t));d[l]=c[i]||0}const o=Math.max(...d,1),a="USER"===this.volume.speaker?.7:.6;d=d.map(((e,t)=>{const i=e/o,n=a+t/(this.barCount-1)*.3;return Math.min(1,i*n)}))}else if("USER"!==this.volume.speaker)for(let l=0;l<this.barCount;l++){const e=.002*Date.now(),t=.3+.2*Math.sin(e+.7*l);d[l]=t}for(let l=0;l<this.barCount;l++){const e=d.length>0&&void 0!==d[l]?d[l]:a;"USER"===this.volume.speaker?t.fillStyle=`rgba(109, 40, 217, ${.5*e+.5})`:t.fillStyle=`rgba(255, 255, 255, ${.5*e+.5})`;const i=Math.max(2,.8*e*o),c=n-(this.barCount-l)*(r+3),u=r/2;t.beginPath(),t.moveTo(c+u,s/2-i),t.lineTo(c+r-u,s/2-i),t.quadraticCurveTo(c+r,s/2-i,c+r,s/2-i+u),t.lineTo(c+r,s/2),t.lineTo(c,s/2),t.lineTo(c,s/2-i+u),t.quadraticCurveTo(c,s/2-i,c+u,s/2-i),t.fill(),t.beginPath(),t.moveTo(c,s/2),t.lineTo(c+r,s/2),t.lineTo(c+r,s/2+i-u),t.quadraticCurveTo(c+r,s/2+i,c+r-u,s/2+i),t.lineTo(c+u,s/2+i),t.quadraticCurveTo(c,s/2+i,c,s/2+i-u),t.lineTo(c,s/2),t.fill()}}render(){return Ju` <canvas ${sp(this.canvasRef)} width="52" height="52"></canvas> `}}dp.styles=pu`
343
343
  :host {
344
344
  display: block;
345
345
  width: 40px;
@@ -351,16 +351,16 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
351
351
  width: 100%;
352
352
  height: 100%;
353
353
  }
354
- `,ap([vh({type:Object})],cp.prototype,"volume",2),ap([yh()],cp.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",cp);const dp=Object.freeze(Object.defineProperty({__proto__:null,AudioEqualizer:cp},Symbol.toStringTag,{value:"Module"}));var lp=Object.defineProperty;Object.getOwnPropertyDescriptor;class up extends ph{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach((e=>window.clearTimeout(e))),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const e=t*(this.animationDuration*this.overlapFactor),i=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const e=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1}),this.animationDuration);this.timeoutIds.push(e)}),e);this.timeoutIds.push(i)}const e=window.setTimeout((()=>{this.animateSequence()}),this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return Wu`
354
+ `,cp([yh({type:Object})],dp.prototype,"volume",2),cp([bh()],dp.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",dp);const lp=Object.freeze(Object.defineProperty({__proto__:null,AudioEqualizer:dp},Symbol.toStringTag,{value:"Module"}));var up=Object.defineProperty;Object.getOwnPropertyDescriptor;class hp extends mh{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach((e=>window.clearTimeout(e))),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const e=t*(this.animationDuration*this.overlapFactor),i=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const e=window.setTimeout((()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1}),this.animationDuration);this.timeoutIds.push(e)}),e);this.timeoutIds.push(i)}const e=window.setTimeout((()=>{this.animateSequence()}),this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return Ju`
355
355
  <div class="dot-loader">
356
- ${this.activeDots.map((e=>Wu`
356
+ ${this.activeDots.map((e=>Ju`
357
357
  <div
358
358
  class="dot"
359
359
  style="transform: ${e?`translateY(-${this.bounceHeight}px)`:"translateY(0)"}"
360
360
  ></div>
361
361
  `))}
362
362
  </div>
363
- `}}up.styles=hu`
363
+ `}}hp.styles=pu`
364
364
  :host {
365
365
  display: block;
366
366
  }
@@ -387,10 +387,10 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
387
387
  transition: transform 0.2s ease-in-out;
388
388
  opacity: 1;
389
389
  }
390
- `,((e,t,i)=>{for(var n,s=void 0,r=e.length-1;r>=0;r--)(n=e[r])&&(s=n(t,i,s)||s);s&&lp(t,i,s)})([yh()],up.prototype,"activeDots"),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",up);const hp=Object.freeze(Object.defineProperty({__proto__:null,DotLoader:up},Symbol.toStringTag,{value:"Module"}));class pp extends ph{render(){return Wu`
390
+ `,((e,t,i)=>{for(var n,s=void 0,r=e.length-1;r>=0;r--)(n=e[r])&&(s=n(t,i,s)||s);s&&up(t,i,s)})([bh()],hp.prototype,"activeDots"),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",hp);const pp=Object.freeze(Object.defineProperty({__proto__:null,DotLoader:hp},Symbol.toStringTag,{value:"Module"}));class mp extends mh{render(){return Ju`
391
391
  <obi-dot-loader loading style="margin-left: 2px"></obi-dot-loader>
392
392
  <span class="text">Searching the knowledge base</span>
393
- `}}pp.styles=hu`
393
+ `}}mp.styles=pu`
394
394
  :host {
395
395
  display: flex;
396
396
  align-items: center;
@@ -405,31 +405,30 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
405
405
  font-weight: 500;
406
406
  font-size: 14px;
407
407
  }
408
- `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",pp);const mp=Object.freeze(Object.defineProperty({__proto__:null,SearchingLoader:pp},Symbol.toStringTag,{value:"Module"}));var gp=Object.defineProperty,fp=Object.getOwnPropertyDescriptor,vp=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?fp(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&gp(t,i,r),r};class yp extends ph{constructor(){super(),this.apiBaseUrl="https://iamobi.ai/api",this.apiKey="",this.position="bottom-right",this.state=Ot.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.screenPosition=this.calculateScreenPosition(),this.closeNavTimeoutRef=null,this.handleResize=()=>{this.screenPosition=this.calculateScreenPosition()},window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.apiBaseUrl&&(this.apiBaseUrl=window.obiWidgetConfig.apiBaseUrl),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position))}calculateScreenPosition(){return iu(this.position).with("top-right",(()=>({top:20,left:window.innerWidth-100}))).with("bottom-right",(()=>({top:window.innerHeight-100,left:window.innerWidth-100}))).with("top-left",(()=>({top:20,left:20}))).with("bottom-left",(()=>({top:window.innerHeight-100,left:20}))).otherwise((()=>({top:window.innerHeight-100,left:window.innerWidth-100})))}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.handleResize),window.obiWidgetConfig||(window.obiWidgetConfig={}),window.obiWidgetConfig.apiBaseUrl=this.apiBaseUrl,this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("resize",this.handleResize),null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}handleItemSelect(e,t){"experiences"!==e?iu([e,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.activeSession?.disconnect()})).otherwise((()=>{})):this.showCourseModal=!0}async handleSessionStart(e){this.showCourseModal=!1,this.state=Ot.LOADING;try{const{ObiSession:t}=await Promise.resolve().then((()=>ou)),i=new t({token:e,apiBaseUrl:this.apiBaseUrl});i.on("stateChanged",(e=>{this.state=e.newState})),i.on("volume",(e=>{this.volume=e})),i.on("error",(e=>{console.error("Session error:",e.error),this.state=Ot.ERROR,this.activeSession=null})),await i.connect(),this.activeSession=i}catch(t){console.error("Failed to connect to session:",t),this.state=Ot.ERROR}}render(){const{top:e,left:t}=this.screenPosition,i=this.state===Ot.RESEARCHING?t-265+56:t,n=iu(this.state).with(Ot.LOADING,(()=>Wu`<obi-dot-loader></obi-dot-loader>`)).with(Ot.RESEARCHING,(()=>Wu`<obi-searching-loader></obi-searching-loader>`)).with(Xl.union(Ot.USER_SPEAKING,Ot.AGENT_SPEAKING),(()=>Wu`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(Ot.PAUSED,(()=>Oh)).otherwise((()=>Oh));return Wu`
408
+ `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",mp);const gp=Object.freeze(Object.defineProperty({__proto__:null,SearchingLoader:mp},Symbol.toStringTag,{value:"Module"}));var fp=Object.defineProperty,vp=Object.getOwnPropertyDescriptor,yp=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?vp(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&fp(t,i,r),r};class bp extends mh{constructor(){super(),this.apiBaseUrl=Rt,this.apiKey="",this.position="bottom-right",this.user=null,this.state=It.READY,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.closeNavTimeoutRef=null,window.obiWidgetConfig&&(window.obiWidgetConfig.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),window.obiWidgetConfig.position&&(this.position=window.obiWidgetConfig.position),window.obiWidgetConfig.user&&(this.user=window.obiWidgetConfig.user))}connectedCallback(){super.connectedCallback(),window.obiWidgetConfig||(window.obiWidgetConfig={apiKey:this.apiKey||""}),this.apiKey&&(window.obiWidgetConfig.apiKey=this.apiKey),this.setAttribute("position",this.position)}disconnectedCallback(){super.disconnectedCallback(),null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null)}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,null!==this.closeNavTimeoutRef&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout((()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null}),300)}handleItemSelect(e,t){"experiences"!==e?iu([e,t]).with(["pause",!0],(()=>{this.activeSession?.pauseRecording()})).with(["pause",!1],(()=>{this.activeSession?.resumeRecording()})).with(["activate",!1],(()=>{this.activeSession?.disconnect()})).otherwise((()=>{})):this.showCourseModal=!0}async handleSessionStart(e){this.showCourseModal=!1,this.state=It.LOADING;try{const{ObiSession:t}=await Promise.resolve().then((()=>ou)),i=new t({token:e,apiBaseUrl:this.apiBaseUrl});i.on("stateChanged",(e=>{this.state=e.newState})),i.on("volume",(e=>{this.volume=e})),i.on("error",(e=>{console.error("Session error:",e.error),this.state=It.ERROR,this.activeSession=null})),await i.connect(),this.activeSession=i}catch(t){console.error("Failed to connect to session:",t),this.state=It.ERROR}}render(){const e=iu(this.state).with(It.LOADING,(()=>Ju`<obi-dot-loader></obi-dot-loader>`)).with(It.RESEARCHING,(()=>Ju`<obi-searching-loader></obi-searching-loader>`)).with(Xl.union(It.USER_SPEAKING,It.AGENT_SPEAKING),(()=>Ju`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`)).with(It.PAUSED,(()=>Ih)).otherwise((()=>Ih));return Ju`
409
409
  <div
410
- class="widget-container ${this.state===Ot.USER_SPEAKING||this.state===Ot.AGENT_SPEAKING?"pulse":""} ${this.state!==Ot.READY||this.navVisible?"rounded":""} ${this.state===Ot.RESEARCHING?"researching":""} ${this.state===Ot.USER_SPEAKING?"user-speaking":""}"
411
- style="top: ${e}px; left: ${i}px;"
410
+ class="widget-container ${this.state===It.USER_SPEAKING||this.state===It.AGENT_SPEAKING?"pulse":""} ${this.state!==It.READY||this.navVisible?"rounded":""} ${this.state===It.RESEARCHING?"researching":""} ${this.state===It.USER_SPEAKING?"user-speaking":""}"
412
411
  @mouseenter=${this.handleMouseEnter}
413
412
  @mouseleave=${this.handleMouseLeave}
414
413
  >
415
- ${n}
416
- ${this.navVisible&&this.state!==Ot.RESEARCHING?Wu`
414
+ ${e}
415
+ ${this.navVisible&&this.state!==It.RESEARCHING?Ju`
417
416
  <obi-navigation-bar
418
- ?isActive=${this.state!==Ot.READY}
419
- .position=${{top:e,left:i}}
417
+ ?isActive=${this.state!==It.READY}
418
+ .position=${this.position}
420
419
  data-direction="up"
421
420
  .currentState=${this.state}
422
421
  .onItemSelect=${this.handleItemSelect.bind(this)}
423
422
  ></obi-navigation-bar>
424
- `:Qu}
423
+ `:Xu}
425
424
  </div>
426
- ${this.showCourseModal?Wu`<obi-course-modal
425
+ ${this.showCourseModal?Ju`<obi-course-modal
427
426
  .onClose=${()=>this.showCourseModal=!1}
428
427
  .onCourseSelect=${this.handleSessionStart.bind(this)}
429
428
  .apiBaseUrl=${this.apiBaseUrl}
430
429
  .apiKey=${this.apiKey}
431
- ></obi-course-modal>`:Qu}
432
- `}}yp.styles=hu`
430
+ ></obi-course-modal>`:Xu}
431
+ `}}bp.styles=pu`
433
432
  :host {
434
433
  display: block;
435
434
  position: fixed;
@@ -440,6 +439,36 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
440
439
  --obi-gray: #6b7280;
441
440
  }
442
441
 
442
+ /* Position-specific styles */
443
+ :host([position="bottom-right"]) {
444
+ bottom: 80px;
445
+ right: 80px;
446
+ }
447
+
448
+ :host([position="bottom-left"]) {
449
+ bottom: 80px;
450
+ left: 20px;
451
+ }
452
+
453
+ :host([position="top-right"]) {
454
+ top: 20px;
455
+ right: 80px;
456
+ }
457
+
458
+ :host([position="top-left"]) {
459
+ top: 20px;
460
+ left: 20px;
461
+ }
462
+
463
+ /* Adjust position when in researching state to accommodate wider container */
464
+ :host([position="bottom-right"]) .widget-container.researching {
465
+ right: 20px;
466
+ }
467
+
468
+ :host([position="top-right"]) .widget-container.researching {
469
+ right: 20px;
470
+ }
471
+
443
472
  .widget-container {
444
473
  position: fixed;
445
474
  width: 56px;
@@ -498,12 +527,12 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
498
527
  .pulse {
499
528
  animation: pulse-shadow 2s ease-in-out infinite;
500
529
  }
501
- `,vp([vh({type:String})],yp.prototype,"apiBaseUrl",2),vp([vh({type:String})],yp.prototype,"apiKey",2),vp([vh({type:String})],yp.prototype,"position",2),vp([yh()],yp.prototype,"state",2),vp([yh()],yp.prototype,"showCourseModal",2),vp([yh()],yp.prototype,"isHovering",2),vp([yh()],yp.prototype,"navVisible",2),vp([yh()],yp.prototype,"activeSession",2),vp([yh()],yp.prototype,"volume",2),vp([yh()],yp.prototype,"screenPosition",2),customElements.get("obi-widget")||customElements.define("obi-widget",yp);const bp=Object.freeze(Object.defineProperty({__proto__:null,ObiWidget:yp},Symbol.toStringTag,{value:"Module"}));function kp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tp={exports:{}},Sp={},Cp=Symbol.for("react.element"),wp=Symbol.for("react.portal"),Ep=Symbol.for("react.fragment"),_p=Symbol.for("react.strict_mode"),Pp=Symbol.for("react.profiler"),Rp=Symbol.for("react.provider"),xp=Symbol.for("react.context"),Op=Symbol.for("react.forward_ref"),Ip=Symbol.for("react.suspense"),Ap=Symbol.for("react.memo"),Np=Symbol.for("react.lazy"),Dp=Symbol.iterator,Mp={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Lp=Object.assign,Up={};function jp(e,t,i){this.props=e,this.context=t,this.refs=Up,this.updater=i||Mp}function Fp(){}function $p(e,t,i){this.props=e,this.context=t,this.refs=Up,this.updater=i||Mp}jp.prototype.isReactComponent={},jp.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},jp.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},Fp.prototype=jp.prototype;var Bp=$p.prototype=new Fp;Bp.constructor=$p,Lp(Bp,jp.prototype),Bp.isPureReactComponent=!0;var Vp=Array.isArray,qp=Object.prototype.hasOwnProperty,zp={current:null},Zp={key:!0,ref:!0,__self:!0,__source:!0};function Hp(e,t,i){var n,s={},r=null,o=null;if(null!=t)for(n in void 0!==t.ref&&(o=t.ref),void 0!==t.key&&(r=""+t.key),t)qp.call(t,n)&&!Zp.hasOwnProperty(n)&&(s[n]=t[n]);var a=arguments.length-2;if(1===a)s.children=i;else if(1<a){for(var c=Array(a),d=0;d<a;d++)c[d]=arguments[d+2];s.children=c}if(e&&e.defaultProps)for(n in a=e.defaultProps)void 0===s[n]&&(s[n]=a[n]);return{$$typeof:Cp,type:e,key:r,ref:o,props:s,_owner:zp.current}}function Kp(e){return"object"==typeof e&&null!==e&&e.$$typeof===Cp}var Gp=/\/+/g;function Wp(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function Jp(e,t,i,n,s){var r=typeof e;"undefined"!==r&&"boolean"!==r||(e=null);var o=!1;if(null===e)o=!0;else switch(r){case"string":case"number":o=!0;break;case"object":switch(e.$$typeof){case Cp:case wp:o=!0}}if(o)return s=s(o=e),e=""===n?"."+Wp(o,0):n,Vp(s)?(i="",null!=e&&(i=e.replace(Gp,"$&/")+"/"),Jp(s,t,i,"",(function(e){return e}))):null!=s&&(Kp(s)&&(s=function(e,t){return{$$typeof:Cp,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(s,i+(!s.key||o&&o.key===s.key?"":(""+s.key).replace(Gp,"$&/")+"/")+e)),t.push(s)),1;if(o=0,n=""===n?".":n+":",Vp(e))for(var a=0;a<e.length;a++){var c=n+Wp(r=e[a],a);o+=Jp(r,t,i,c,s)}else if(c=function(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=Dp&&e[Dp]||e["@@iterator"])?e:null}(e),"function"==typeof c)for(e=c.call(e),a=0;!(r=e.next()).done;)o+=Jp(r=r.value,t,i,c=n+Wp(r,a++),s);else if("object"===r)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return o}function Yp(e,t,i){if(null==e)return e;var n=[],s=0;return Jp(e,n,"","",(function(e){return t.call(i,e,s++)})),n}function Qp(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var Xp={current:null},em={transition:null},tm={ReactCurrentDispatcher:Xp,ReactCurrentBatchConfig:em,ReactCurrentOwner:zp};function im(){throw Error("act(...) is not supported in production builds of React.")}Sp.Children={map:Yp,forEach:function(e,t,i){Yp(e,(function(){t.apply(this,arguments)}),i)},count:function(e){var t=0;return Yp(e,(function(){t++})),t},toArray:function(e){return Yp(e,(function(e){return e}))||[]},only:function(e){if(!Kp(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},Sp.Component=jp,Sp.Fragment=Ep,Sp.Profiler=Pp,Sp.PureComponent=$p,Sp.StrictMode=_p,Sp.Suspense=Ip,Sp.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=tm,Sp.act=im,Sp.cloneElement=function(e,t,i){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var n=Lp({},e.props),s=e.key,r=e.ref,o=e._owner;if(null!=t){if(void 0!==t.ref&&(r=t.ref,o=zp.current),void 0!==t.key&&(s=""+t.key),e.type&&e.type.defaultProps)var a=e.type.defaultProps;for(c in t)qp.call(t,c)&&!Zp.hasOwnProperty(c)&&(n[c]=void 0===t[c]&&void 0!==a?a[c]:t[c])}var c=arguments.length-2;if(1===c)n.children=i;else if(1<c){a=Array(c);for(var d=0;d<c;d++)a[d]=arguments[d+2];n.children=a}return{$$typeof:Cp,type:e.type,key:s,ref:r,props:n,_owner:o}},Sp.createContext=function(e){return(e={$$typeof:xp,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:Rp,_context:e},e.Consumer=e},Sp.createElement=Hp,Sp.createFactory=function(e){var t=Hp.bind(null,e);return t.type=e,t},Sp.createRef=function(){return{current:null}},Sp.forwardRef=function(e){return{$$typeof:Op,render:e}},Sp.isValidElement=Kp,Sp.lazy=function(e){return{$$typeof:Np,_payload:{_status:-1,_result:e},_init:Qp}},Sp.memo=function(e,t){return{$$typeof:Ap,type:e,compare:void 0===t?null:t}},Sp.startTransition=function(e){var t=em.transition;em.transition={};try{e()}finally{em.transition=t}},Sp.unstable_act=im,Sp.useCallback=function(e,t){return Xp.current.useCallback(e,t)},Sp.useContext=function(e){return Xp.current.useContext(e)},Sp.useDebugValue=function(){},Sp.useDeferredValue=function(e){return Xp.current.useDeferredValue(e)},Sp.useEffect=function(e,t){return Xp.current.useEffect(e,t)},Sp.useId=function(){return Xp.current.useId()},Sp.useImperativeHandle=function(e,t,i){return Xp.current.useImperativeHandle(e,t,i)},Sp.useInsertionEffect=function(e,t){return Xp.current.useInsertionEffect(e,t)},Sp.useLayoutEffect=function(e,t){return Xp.current.useLayoutEffect(e,t)},Sp.useMemo=function(e,t){return Xp.current.useMemo(e,t)},Sp.useReducer=function(e,t,i){return Xp.current.useReducer(e,t,i)},Sp.useRef=function(e){return Xp.current.useRef(e)},Sp.useState=function(e){return Xp.current.useState(e)},Sp.useSyncExternalStore=function(e,t,i){return Xp.current.useSyncExternalStore(e,t,i)},Sp.useTransition=function(){return Xp.current.useTransition()},Sp.version="18.3.1",Tp.exports=Sp;var nm=Tp.exports;const sm=kp(nm);var rm=Object.defineProperty;Object.getOwnPropertyDescriptor;class om extends ph{constructor(){super(...arguments),this.state=Ot.READY}render(){return Wu`
530
+ `,yp([yh({type:String})],bp.prototype,"apiBaseUrl",2),yp([yh({type:String})],bp.prototype,"apiKey",2),yp([yh({type:String})],bp.prototype,"position",2),yp([yh({type:Object})],bp.prototype,"user",2),yp([bh()],bp.prototype,"state",2),yp([bh()],bp.prototype,"showCourseModal",2),yp([bh()],bp.prototype,"isHovering",2),yp([bh()],bp.prototype,"navVisible",2),yp([bh()],bp.prototype,"activeSession",2),yp([bh()],bp.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",bp);const kp=Object.freeze(Object.defineProperty({__proto__:null,ObiWidget:bp},Symbol.toStringTag,{value:"Module"}));function Tp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Sp={exports:{}},Cp={},wp=Symbol.for("react.element"),Ep=Symbol.for("react.portal"),_p=Symbol.for("react.fragment"),Pp=Symbol.for("react.strict_mode"),Rp=Symbol.for("react.profiler"),xp=Symbol.for("react.provider"),Op=Symbol.for("react.context"),Ip=Symbol.for("react.forward_ref"),Ap=Symbol.for("react.suspense"),Np=Symbol.for("react.memo"),Dp=Symbol.for("react.lazy"),Mp=Symbol.iterator,Lp={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Up=Object.assign,jp={};function Fp(e,t,i){this.props=e,this.context=t,this.refs=jp,this.updater=i||Lp}function $p(){}function Bp(e,t,i){this.props=e,this.context=t,this.refs=jp,this.updater=i||Lp}Fp.prototype.isReactComponent={},Fp.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},Fp.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},$p.prototype=Fp.prototype;var Vp=Bp.prototype=new $p;Vp.constructor=Bp,Up(Vp,Fp.prototype),Vp.isPureReactComponent=!0;var qp=Array.isArray,zp=Object.prototype.hasOwnProperty,Kp={current:null},Zp={key:!0,ref:!0,__self:!0,__source:!0};function Hp(e,t,i){var n,s={},r=null,o=null;if(null!=t)for(n in void 0!==t.ref&&(o=t.ref),void 0!==t.key&&(r=""+t.key),t)zp.call(t,n)&&!Zp.hasOwnProperty(n)&&(s[n]=t[n]);var a=arguments.length-2;if(1===a)s.children=i;else if(1<a){for(var c=Array(a),d=0;d<a;d++)c[d]=arguments[d+2];s.children=c}if(e&&e.defaultProps)for(n in a=e.defaultProps)void 0===s[n]&&(s[n]=a[n]);return{$$typeof:wp,type:e,key:r,ref:o,props:s,_owner:Kp.current}}function Gp(e){return"object"==typeof e&&null!==e&&e.$$typeof===wp}var Wp=/\/+/g;function Jp(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function Yp(e,t,i,n,s){var r=typeof e;"undefined"!==r&&"boolean"!==r||(e=null);var o=!1;if(null===e)o=!0;else switch(r){case"string":case"number":o=!0;break;case"object":switch(e.$$typeof){case wp:case Ep:o=!0}}if(o)return s=s(o=e),e=""===n?"."+Jp(o,0):n,qp(s)?(i="",null!=e&&(i=e.replace(Wp,"$&/")+"/"),Yp(s,t,i,"",(function(e){return e}))):null!=s&&(Gp(s)&&(s=function(e,t){return{$$typeof:wp,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(s,i+(!s.key||o&&o.key===s.key?"":(""+s.key).replace(Wp,"$&/")+"/")+e)),t.push(s)),1;if(o=0,n=""===n?".":n+":",qp(e))for(var a=0;a<e.length;a++){var c=n+Jp(r=e[a],a);o+=Yp(r,t,i,c,s)}else if(c=function(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=Mp&&e[Mp]||e["@@iterator"])?e:null}(e),"function"==typeof c)for(e=c.call(e),a=0;!(r=e.next()).done;)o+=Yp(r=r.value,t,i,c=n+Jp(r,a++),s);else if("object"===r)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return o}function Qp(e,t,i){if(null==e)return e;var n=[],s=0;return Yp(e,n,"","",(function(e){return t.call(i,e,s++)})),n}function Xp(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var em={current:null},tm={transition:null},im={ReactCurrentDispatcher:em,ReactCurrentBatchConfig:tm,ReactCurrentOwner:Kp};function nm(){throw Error("act(...) is not supported in production builds of React.")}Cp.Children={map:Qp,forEach:function(e,t,i){Qp(e,(function(){t.apply(this,arguments)}),i)},count:function(e){var t=0;return Qp(e,(function(){t++})),t},toArray:function(e){return Qp(e,(function(e){return e}))||[]},only:function(e){if(!Gp(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},Cp.Component=Fp,Cp.Fragment=_p,Cp.Profiler=Rp,Cp.PureComponent=Bp,Cp.StrictMode=Pp,Cp.Suspense=Ap,Cp.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=im,Cp.act=nm,Cp.cloneElement=function(e,t,i){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var n=Up({},e.props),s=e.key,r=e.ref,o=e._owner;if(null!=t){if(void 0!==t.ref&&(r=t.ref,o=Kp.current),void 0!==t.key&&(s=""+t.key),e.type&&e.type.defaultProps)var a=e.type.defaultProps;for(c in t)zp.call(t,c)&&!Zp.hasOwnProperty(c)&&(n[c]=void 0===t[c]&&void 0!==a?a[c]:t[c])}var c=arguments.length-2;if(1===c)n.children=i;else if(1<c){a=Array(c);for(var d=0;d<c;d++)a[d]=arguments[d+2];n.children=a}return{$$typeof:wp,type:e.type,key:s,ref:r,props:n,_owner:o}},Cp.createContext=function(e){return(e={$$typeof:Op,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:xp,_context:e},e.Consumer=e},Cp.createElement=Hp,Cp.createFactory=function(e){var t=Hp.bind(null,e);return t.type=e,t},Cp.createRef=function(){return{current:null}},Cp.forwardRef=function(e){return{$$typeof:Ip,render:e}},Cp.isValidElement=Gp,Cp.lazy=function(e){return{$$typeof:Dp,_payload:{_status:-1,_result:e},_init:Xp}},Cp.memo=function(e,t){return{$$typeof:Np,type:e,compare:void 0===t?null:t}},Cp.startTransition=function(e){var t=tm.transition;tm.transition={};try{e()}finally{tm.transition=t}},Cp.unstable_act=nm,Cp.useCallback=function(e,t){return em.current.useCallback(e,t)},Cp.useContext=function(e){return em.current.useContext(e)},Cp.useDebugValue=function(){},Cp.useDeferredValue=function(e){return em.current.useDeferredValue(e)},Cp.useEffect=function(e,t){return em.current.useEffect(e,t)},Cp.useId=function(){return em.current.useId()},Cp.useImperativeHandle=function(e,t,i){return em.current.useImperativeHandle(e,t,i)},Cp.useInsertionEffect=function(e,t){return em.current.useInsertionEffect(e,t)},Cp.useLayoutEffect=function(e,t){return em.current.useLayoutEffect(e,t)},Cp.useMemo=function(e,t){return em.current.useMemo(e,t)},Cp.useReducer=function(e,t,i){return em.current.useReducer(e,t,i)},Cp.useRef=function(e){return em.current.useRef(e)},Cp.useState=function(e){return em.current.useState(e)},Cp.useSyncExternalStore=function(e,t,i){return em.current.useSyncExternalStore(e,t,i)},Cp.useTransition=function(){return em.current.useTransition()},Cp.version="18.3.1",Sp.exports=Cp;var sm=Sp.exports;const rm=Tp(sm);var om=Object.defineProperty;Object.getOwnPropertyDescriptor;class am extends mh{constructor(){super(...arguments),this.state=It.READY}render(){return Ju`
502
531
  <div class="status-container">
503
532
  <div class="status-indicator ${this.state}"></div>
504
533
  <div class="status-text">${this.getStatusText()}</div>
505
534
  </div>
506
- `}getStatusText(){switch(this.state){case Ot.READY:return"Ready";case Ot.ERROR:return"Error";default:return"Unknown"}}}om.styles=hu`
535
+ `}getStatusText(){switch(this.state){case It.READY:return"Ready";case It.ERROR:return"Error";default:return"Unknown"}}}am.styles=pu`
507
536
  :host {
508
537
  display: inline-block;
509
538
  font-family: Arial, sans-serif;
@@ -542,7 +571,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
542
571
  font-weight: 500;
543
572
  color: #1f2937;
544
573
  }
545
- `,((e,t,i)=>{for(var n,s=void 0,r=e.length-1;r>=0;r--)(n=e[r])&&(s=n(t,i,s)||s);s&&rm(t,i,s)})([vh({type:String})],om.prototype,"state"),customElements.get("obi-status-widget")||customElements.define("obi-status-widget",om);const am=Object.freeze(Object.defineProperty({__proto__:null,ObiStatusWidget:om},Symbol.toStringTag,{value:"Module"}));var cm=Object.defineProperty,dm=Object.getOwnPropertyDescriptor,lm=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?dm(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&cm(t,i,r),r};class um extends ph{constructor(){super(...arguments),this.state=Ot.READY,this.voiceEnabled=!0,this.screenEnabled=!0}render(){const e=this.state===Ot.AGENT_SPEAKING,t=this.state===Ot.READY;return Wu`
574
+ `,((e,t,i)=>{for(var n,s=void 0,r=e.length-1;r>=0;r--)(n=e[r])&&(s=n(t,i,s)||s);s&&om(t,i,s)})([yh({type:String})],am.prototype,"state"),customElements.get("obi-status-widget")||customElements.define("obi-status-widget",am);const cm=Object.freeze(Object.defineProperty({__proto__:null,ObiStatusWidget:am},Symbol.toStringTag,{value:"Module"}));var dm=Object.defineProperty,lm=Object.getOwnPropertyDescriptor,um=(e,t,i,n)=>{for(var s,r=n>1?void 0:n?lm(t,i):t,o=e.length-1;o>=0;o--)(s=e[o])&&(r=(n?s(t,i,r):s(r))||r);return n&&r&&dm(t,i,r),r};class hm extends mh{constructor(){super(...arguments),this.state=It.READY,this.voiceEnabled=!0,this.screenEnabled=!0}render(){const e=this.state===It.AGENT_SPEAKING,t=this.state===It.READY;return Ju`
546
575
  <div class="control-container">
547
576
  <div class="control-header">Obi Controls</div>
548
577
  <div class="control-buttons">
@@ -567,7 +596,7 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
567
596
  </button>
568
597
  </div>
569
598
  </div>
570
- `}handleVoiceClick(){this.dispatchEvent(new CustomEvent("voice-start"))}handleScreenClick(){this.dispatchEvent(new CustomEvent("screen-start"))}handleStopClick(){this.dispatchEvent(new CustomEvent("stop"))}}um.styles=hu`
599
+ `}handleVoiceClick(){this.dispatchEvent(new CustomEvent("voice-start"))}handleScreenClick(){this.dispatchEvent(new CustomEvent("screen-start"))}handleStopClick(){this.dispatchEvent(new CustomEvent("stop"))}}hm.styles=pu`
571
600
  :host {
572
601
  display: block;
573
602
  font-family: Arial, sans-serif;
@@ -630,5 +659,5 @@ var e=function(e){"use strict";var t,i,n;(i=t||(t={})).assertEqual=e=>e,i.assert
630
659
  background-color: var(--obi-danger);
631
660
  color: white;
632
661
  }
633
- `,lm([vh({type:String})],um.prototype,"state",2),lm([vh({type:Boolean})],um.prototype,"voiceEnabled",2),lm([vh({type:Boolean})],um.prototype,"screenEnabled",2),customElements.get("obi-control-panel")||customElements.define("obi-control-panel",um);const hm=Object.freeze(Object.defineProperty({__proto__:null,ObiControlPanel:um},Symbol.toStringTag,{value:"Module"}));return e.AudioEqualizer=cp,e.Course=Fh,e.CourseList=$h,e.CourseModal=Zh,e.DotLoader=up,e.EventType=xt,e.NavIcon=Sh,e.NavigationBar=Dh,e.ObiControlPanel=um,e.ObiControlPanelReact=function({state:e=Ot.READY,voiceEnabled:t=!0,screenEnabled:i=!0,onVoiceStart:n,onScreenStart:s,onStop:r,className:o}){return sm.createElement("obi-control-panel",{state:e,voiceEnabled:t,screenEnabled:i,onvoicestart:()=>{n&&n()},onscreenstart:()=>{s&&s()},onstop:()=>{r&&r()},className:o})},e.ObiSDK=At,e.ObiSDKConfigSchema=Rt,e.ObiSession=ru,e.ObiStatusWidget=om,e.ObiStatusWidgetReact=function({state:e=Ot.READY,className:t}){return sm.createElement("obi-status-widget",{state:e,className:t})},e.ObiWidget=yp,e.SDKState=Ot,e.SearchingLoader=pp,e.VERSION="0.1.0",e.createSession=async(e={})=>{const{ObiSession:t}=await Promise.resolve().then((()=>ou));return new t(e)},e.defineCustomElements=function(){Promise.resolve().then((()=>am)),Promise.resolve().then((()=>hm)),Promise.resolve().then((()=>bp)),Promise.resolve().then((()=>dp)),Promise.resolve().then((()=>hp)),Promise.resolve().then((()=>Ch)),Promise.resolve().then((()=>Mh)),Promise.resolve().then((()=>mp)),Promise.resolve().then((()=>Bh)),Promise.resolve().then((()=>Hh))},e.useObiSDK=function(e){const[t,i]=nm.useState(null),[n,s]=nm.useState(Ot.READY),[r,o]=nm.useState(null);return nm.useEffect((()=>{const t=new At(e);return i(t),t.init().catch((e=>{console.error("Failed to initialize Obi SDK:",e)})),t.on(xt.STATE_CHANGE,(e=>{s(e)})),t.on(xt.ERROR,(e=>{o(e)})),()=>{t.dispose()}}),[]),{sdk:t,state:n,error:r,startVoiceRecording:async()=>{if(t)return t.startVoiceRecording()},stopVoiceRecording:async()=>t?t.stopVoiceRecording():{transcript:void 0},startScreenCapture:async()=>{if(t)return t.startScreenCapture()},stopScreenCapture:async()=>t?t.stopScreenCapture():{screenshot:void 0},isReady:n===Ot.READY,isActive:n!==Ot.READY,isError:n===Ot.ERROR}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
662
+ `,um([yh({type:String})],hm.prototype,"state",2),um([yh({type:Boolean})],hm.prototype,"voiceEnabled",2),um([yh({type:Boolean})],hm.prototype,"screenEnabled",2),customElements.get("obi-control-panel")||customElements.define("obi-control-panel",hm);const pm=Object.freeze(Object.defineProperty({__proto__:null,ObiControlPanel:hm},Symbol.toStringTag,{value:"Module"}));return e.API_BASE_URL=Rt,e.AudioEqualizer=dp,e.Course=$h,e.CourseList=Bh,e.CourseModal=Zh,e.DotLoader=hp,e.EventType=Ot,e.NavIcon=Ch,e.NavigationBar=Mh,e.ObiAssistant=class{static init(e){customElements.get("obi-widget")||customElements.define("obi-widget",bp);const t=document.createElement("obi-widget");return e.apiKey&&(t.apiKey=e.apiKey),e.position&&(t.position=e.position),e.user&&(t.user=e.user),window.obiWidgetConfig=e,document.body.appendChild(t),console.log("Obi Widget initialized and mounted"),t}},e.ObiControlPanel=hm,e.ObiControlPanelReact=function({state:e=It.READY,voiceEnabled:t=!0,screenEnabled:i=!0,onVoiceStart:n,onScreenStart:s,onStop:r,className:o}){return rm.createElement("obi-control-panel",{state:e,voiceEnabled:t,screenEnabled:i,onvoicestart:()=>{n&&n()},onscreenstart:()=>{s&&s()},onstop:()=>{r&&r()},className:o})},e.ObiSDK=au,e.ObiSDKConfigSchema=xt,e.ObiSession=ru,e.ObiStatusWidget=am,e.ObiStatusWidgetReact=function({state:e=It.READY,className:t}){return rm.createElement("obi-status-widget",{state:e,className:t})},e.ObiWidget=bp,e.SDKState=It,e.SearchingLoader=mp,e.VERSION="0.1.0",e.createSession=async(e={})=>{const{ObiSession:t}=await Promise.resolve().then((()=>ou));return new t(e)},e.defineCustomElements=function(){Promise.resolve().then((()=>cm)),Promise.resolve().then((()=>pm)),Promise.resolve().then((()=>kp)),Promise.resolve().then((()=>lp)),Promise.resolve().then((()=>pp)),Promise.resolve().then((()=>wh)),Promise.resolve().then((()=>Lh)),Promise.resolve().then((()=>gp)),Promise.resolve().then((()=>Vh)),Promise.resolve().then((()=>Hh))},e.useObiSDK=function(e){const[t,i]=sm.useState(null),[n,s]=sm.useState(It.READY),[r,o]=sm.useState(null);return sm.useEffect((()=>{const t=new au(e);return i(t),t.init().catch((e=>{console.error("Failed to initialize Obi SDK:",e)})),t.on(Ot.STATE_CHANGE,(e=>{s(e)})),t.on(Ot.ERROR,(e=>{o(e)})),()=>{t.dispose()}}),[]),{sdk:t,state:n,error:r,startVoiceRecording:async()=>{if(t)return t.startVoiceRecording()},stopVoiceRecording:async()=>t?t.stopVoiceRecording():{transcript:void 0},startScreenCapture:async()=>{if(t)return t.startScreenCapture()},stopScreenCapture:async()=>t?t.stopScreenCapture():{screenshot:void 0},isReady:n===It.READY,isActive:n!==It.READY,isError:n===It.ERROR}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
634
663
  //# sourceMappingURL=obi-sdk.standalone.iife.js.map